Compare commits

...

47 Commits

Author SHA1 Message Date
walon dad411f4e2 [version] 发布v3.4.3版本 2023-09-26 21:13:52 +08:00
walon 1f9faf49a3 [version] 发布v3.4.2版本 2023-08-13 13:07:49 +08:00
walon 3f1b34682d [fix] 修复计算 AOTGenericReferences时未考虑到泛型中调用泛型的问题,导致间接调用的泛型未被统计在内的bug 2023-08-13 13:07:37 +08:00
walon c3f6325e4a [version] 发布v3.4.1版本 2023-07-31 11:06:02 +08:00
walon a9f5608ecf [change] 检查Settings中热更新程序集列表配置中程序集名不能为空
[fix] 修复当某个热更新程序集正好是另一个AOT程序集后缀时,由于只对比字符串尾部,意外将该AOT程序集也过滤的bug
2023-07-21 18:05:12 +08:00
walon 8a95fd57f5 [version] 发布v3.4.0版本 2023-07-17 12:33:23 +08:00
walon 679c21da43 [fix] 修复计算桥接函数未考虑到泛型类的成员函数中可能包含Native2Manager调用 2023-07-12 23:09:58 +08:00
walon 52bab856ed [change] README中新增RELEASELOG的链接 2023-07-11 15:15:18 +08:00
walon 844b2fb62f [change] 从hybridclr仓库同步 README 2023-07-11 15:01:20 +08:00
walon 88404cbbfc [refactor] 重构Installer 2023-07-11 12:27:11 +08:00
walon 9b4aa904ef [new] 整理 RELEASELOG.md 较旧的版本记录 2023-07-09 13:59:46 +08:00
walon a71153d414 [change] 修正RuntimeApi.cs文件某些代码的缩进问题 2023-07-07 21:38:38 +08:00
walon bec8c84c56 [fix] 修复Win下生成的Lump文件中include路径以\为目录分隔符导致同步到Mac后找不到路径的bug 2023-07-07 21:37:18 +08:00
walon 79bab0459c [change] link.xml及AOTGenericReferences.cs默认输出路径改为HybridCLRGenerate,避免与顶层HybridCLRData混淆 2023-07-04 12:25:35 +08:00
walon 1d09f72460 [change] RuntimeApi::GetInterpreterThreadFrameStackSize 之类的函数在Editor下为空非extern函数,避免Editor下调用时出错 2023-07-03 22:54:33 +08:00
walon 058270c658 [version] 发布v3.3.0版本 2023-07-03 10:48:16 +08:00
walon 210c781fad [change] 禁用hybridclr后打包ios时不再修改导出的xcode工程 2023-07-02 21:50:52 +08:00
walon 6757f6df5b [fix] 修复2020-2021编译libil2cpp.a未包含brotli相关代码文件导致出现编译错误的bug 2023-06-30 20:15:03 +08:00
walon 41c73fe35b [fix] 修复使用不兼容版本打开Installer时出现异常的bug 2023-06-30 12:20:56 +08:00
walon 4d487fa4c4 [fix] 修复Installer中将hybridclr拼成bybridclr的错误 2023-06-28 11:46:04 +08:00
walon 2f71bb515d [change] 调整CompileDll ScriptCompilationSettings设置相关代码 2023-06-27 08:58:08 +08:00
walon 0d8b001dd2 [fix] 解决ReversePInvokeWrap生成不稳定的问题 2023-06-27 08:57:14 +08:00
walon 3d68dc4db3 [fix] 解决MethodBridge生成不稳定的问题 2023-06-27 08:57:02 +08:00
walon 2988aef85a [change] 优化LinkXml生成 2023-06-27 08:18:11 +08:00
walon 768512bcfa [change] 解决AOTGenericReference生成不稳定的问题 2023-06-27 08:13:16 +08:00
walon 4492449b73 [fix] 修复从导出xcode项目包含绝对路径导致传送到其他机器上编译时找不到路径的bug 2023-06-23 16:19:58 +08:00
walon be113567ba [version] 发布v3.2.1版本 2023-06-21 11:08:13 +08:00
walon e45a789569 [change] 为Anaylizer加上using 限定,解决某些情况下与项目的类型同名而产生编译冲突的问题 2023-06-21 11:07:00 +08:00
walon 0a82b0d339 [new] Installer界面新增显示package版本 2023-06-16 18:20:18 +08:00
walon c8cd323bb0 [fix] 修复重构文档站后的帮助文档的链接错误 2023-06-15 17:06:55 +08:00
walon 2f09f88ca2 [new] CompileDll新增MacOS、Linux、WebGL目标 2023-06-15 17:05:46 +08:00
walon 8e178c0e37 [version] 发布v3.2.0版本 2023-06-15 12:00:05 +08:00
walon 40711cbf38 [new] iOS打包时直接将源码包含到工程,不再需要单独编译libil2cpp.a
[remove] 移除无用的iOSBuild目录
2023-06-15 09:57:15 +08:00
walon 7749b6448e [change] 当用不兼容版本打开Installer时不再抛出异常,而是显示“与当前版本不兼容” 2023-06-12 13:30:32 +08:00
walon 1459992ec4 [version] 发布v3.1.1版本 2023-06-12 10:34:00 +08:00
walon c09dad4ae1 [remove] CheckSettings中不再自动设置Api Compatible Level 2023-06-08 13:24:00 +08:00
walon 271dc70626 [opt] 生成AOTGenericReferences时,补充元数据assembly列表由注释改成List<string>列表,方便在代码中直接使用。 2023-06-07 12:17:10 +08:00
walon c462aeb2ef [fix] 修复计算桥接函数时未考虑到补充元数据泛型实例化会导致访问到一些非公开的函数的情况,导致少生成一些必要的桥接函数 2023-06-07 11:47:17 +08:00
walon adbdbf3a00 [remove] 删除无用的复制Unity 2019 Unity.IL2CPP.dll 的代码 2023-06-06 15:51:18 +08:00
walon 10684d29cd [fix] CompileDll后主动关闭进度条,临时解决Unity 2022版本Editor的bug 2023-06-06 11:28:27 +08:00
walon 7d58454fdd [version] 发布v3.1.0版本 2023-06-03 19:51:05 +08:00
walon 21b85aa2d3 [fix] 修复WebGL平台ABI的bug 2023-06-03 19:44:50 +08:00
walon 8439e4176d [new] 新增对Unity 2020的支持 2023-06-03 19:42:56 +08:00
walon 4b43870ff2 [version] 发布v3.0.3版本 2023-06-02 15:49:08 +08:00
walon b49b94521e [version] 发布v3.0.2版本 2023-06-01 11:52:49 +08:00
walon 49873ba6ed [new] 新增菜单命令HybridCLR/CompileDll/ActiveBuildTarget_Development,用于编译出DevelopmentBuild模式的热更新dll 2023-06-01 11:43:41 +08:00
walon 97f083f07d [revert] Revert "[new] HybridCLRSettings新增AOT dll快照目录,由于保存打包时生成的AOT dlls"
This reverts commit 8d0634620a.
2023-06-01 11:15:40 +08:00
46 changed files with 1297 additions and 813 deletions
+9 -4
View File
@@ -1,14 +1,19 @@
{
"versions": [
{
"unity_version":"2020",
"hybridclr" : { "branch":"v3.3.3"},
"il2cpp_plus": { "branch":"v2020-3.3.2"}
},
{
"unity_version":"2021",
"hybridclr" : { "branch":"v3.0.1"},
"il2cpp_plus": { "branch":"v2021-3.0.0"}
"hybridclr" : { "branch":"v3.3.3"},
"il2cpp_plus": { "branch":"v2021-3.3.2"}
},
{
"unity_version":"2022",
"hybridclr" : { "branch":"v3.0.1"},
"il2cpp_plus": { "branch":"v2022-3.0.0"}
"hybridclr" : { "branch":"v3.3.3"},
"il2cpp_plus": { "branch":"v2022-3.3.3"}
}
]
}
-88
View File
@@ -1,88 +0,0 @@
# file: CMakeList.txt
cmake_minimum_required(VERSION 3.0)
set(CMAKE_OSX_DEPLOYMENT_TARGET iOS)
set(TMP $ENV{HUATUO_IL2CPP_SOURCE_DIR})
if ( NOT TMP )
message(FATAL_ERROR "需要设置环境变量: HUATUO_IL2CPP_SOURCE_DIR")
else()
message(STATUS "unity il2cpp 路径为: ${TMP}")
endif()
set(SDK_VERSION $ENV{IPHONESIMULATOR_VERSION})
if ( SDK_VERSION )
message(STATUS "使用iPhoneSimulator版本:" ${SDK_VERSION})
else()
message(STATUS "当前使用默认版本的iPhoneSimulator,可以通过设置环境变量IPHONESIMULATOR_VERSION,指定版本")
endif()
project(il2cpp)
execute_process(COMMAND sh gen_lump.sh ${PROJECT_BINARY_DIR} WORKING_DIRECTORY ${CMAKE_SOURCE_DIR})
add_subdirectory(external)
add_subdirectory(objective)
set(IL2CPP_SOURCE_DIR $ENV{HUATUO_IL2CPP_SOURCE_DIR})
message(STATUS "il2cpp project, binary dir: " ${CMAKE_BINARY_DIR})
message(STATUS "il2cpp project, build dir: " ${PROJECT_BINARY_DIR})
message(STATUS "il2cpp project, il2cpp source dir: " ${IL2CPP_SOURCE_DIR})
SET_PROPERTY(GLOBAL PROPERTY USE_FOLDERS ON)
find_program(CLANG_EXECUTABLE NAMES clang clang-7 clang-8 clang-9 clang-10)
if (NOT CLANG_EXECUTABLE)
message(FATAL_ERROR "Cannot find any clang executable.")
endif()
set(CMAKE_OSX_SYSROOT /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator${SDK_VERSION}.sdk)
#set(CMAKE_VERBOSE_MAKEFILE ON)
set(CMAKE_CXX_COMPILER clang++)
set(CMAKE_C_COMPILER clang)
#add_compile_options(-x objective-c++)
# 以下命令为复制的Xcode生成中的命令
set(CMAKE_CXX_FLAGS "-target arm64-apple-ios11.0 -fmessage-length=0 -fdiagnostics-show-note-include-stack -fmacro-backtrace-limit=0 -std=gnu++1z -fmodules -fmodules-prune-interval=86400 -fmodules-prune-after=345600 -fmodules-ignore-macro=IL2CPP_TARGET_IOS=1 -fembed-bitcode -fmodules-ignore-macro=BASELIB_DYNAMICLIBRARY=1 -fmodules-ignore-macro=BASELIB_INLINE_NAMESPACE=il2cpp_baselib -fmodules-ignore-macro=AARCH64 -fmodules-ignore-macro=__aarch64__ -fmodules-ignore-macro=IL2CPP_SUPPORT_THREADS -fmodules-ignore-macro=IL2CPP_THREADS_PTHREAD -Wnon-modular-include-in-framework-module -Werror=non-modular-include-in-framework-module -Wno-trigraphs -fpascal-strings -Os -fno-common -Wno-missing-field-initializers -Wno-missing-prototypes -Werror=return-type -Wdocumentation -Wunreachable-code -Wquoted-include-in-framework-header -Werror=deprecated-objc-isa-usage -Werror=objc-root-class -Wno-non-virtual-dtor -Wno-overloaded-virtual -Wno-exit-time-destructors -Wno-missing-braces -Wparentheses -Wswitch -Wno-unused-function -Wno-unused-label -Wno-unused-parameter -Wno-unused-variable -Wunused-value -Wempty-body -Wuninitialized -Wconditional-uninitialized -Wno-unknown-pragmas -Wno-shadow -Wno-four-char-constants -Wno-conversion -Wconstant-conversion -Wint-conversion -Wbool-conversion -Wenum-conversion -Wno-float-conversion -Wnon-literal-null-conversion -Wobjc-literal-conversion -Wshorten-64-to-32 -Wno-newline-eof -Wno-c++11-extensions -DIL2CPP_TARGET_IOS=1 -isysroot ${CMAKE_OSX_SYSROOT} -fasm-blocks -fstrict-aliasing -Wdeprecated-declarations -Winvalid-offsetof -g -Wno-sign-conversion -Winfinite-recursion -Wmove -Wcomma -Wblock-capture-autoreleasing -Wstrict-prototypes -Wrange-loop-analysis -Wno-semicolon-before-method-body -Wunguarded-availability ")
add_definitions(-DIL2CPP_TARGET_IOS=1)
add_definitions(-DBASELIB_DYNAMICLIBRARY=1)
add_definitions(-DBASELIB_INLINE_NAMESPACE=il2cpp_baselib)
add_definitions(-DAARCH64)
add_definitions(-D__aarch64__)
add_definitions(-DIL2CPP_SUPPORT_THREADS)
add_definitions(-DIL2CPP_THREADS_PTHREAD)
#add_definitions(-DCMAKE_C_COMPILER=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang)
#add_definitions(-DCMAKE_CXX_COMPILER=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang++)
#add_definitions(-DIL2CPP_TARGET_DARWIN)
add_definitions(-DIL2CPP_PLATFORM_SUPPORTS_TIMEZONEINFO)
add_definitions(-MMD)
add_definitions(-MT dependencies)
include_directories(${IL2CPP_SOURCE_DIR}/libil2cpp/)
include_directories(${IL2CPP_SOURCE_DIR}/external/)
include_directories(${IL2CPP_SOURCE_DIR}/external/baselib/Include/)
include_directories(${IL2CPP_SOURCE_DIR}/external/bdwgc/include/)
include_directories(${IL2CPP_SOURCE_DIR}/external/baselib/Platforms/OSX/Include/)
# 修改为本机对应SDK路径
include_directories(SYSTEM /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/usr/include/c++/v1)
include_directories(SYSTEM /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/usr/include)
aux_source_directory(${PROJECT_BINARY_DIR}/lump_cpp LUMP_SOURCE_LIST)
aux_source_directory(${IL2CPP_SOURCE_DIR}/libil2cpp LIBIL2CPP_SOURCE_LIST)
#find_library(zlib ${PROJECT_SOURCE_DIR}/external)
add_library(il2cpp_original STATIC ${LIBIL2CPP_SOURCE_LIST} ${LUMP_SOURCE_LIST})
add_dependencies(il2cpp_original external objective)
add_custom_command(TARGET il2cpp_original
POST_BUILD
COMMAND xcrun -r libtool -static -o libil2cpp.a libil2cpp_original.a external/libexternal.a objective/libobjective.a
COMMENT "post build this is command combine libil2cpp_original.a, libojjective.a and libzlib.a into libil2cpp"
)
-19
View File
@@ -1,19 +0,0 @@
#!/bin/bash
export HUATUO_IL2CPP_SOURCE_DIR=$(pushd ../LocalIl2CppData-OSXEditor/il2cpp > /dev/null && pwd && popd > /dev/null)
export IPHONESIMULATOR_VERSION=
rm -rf build
mkdir build
cd build
cmake -DCMAKE_SYSTEM_PROCESSOR=arm64 -DCMAKE_OSX_ARCHITECTURES=arm64 ..
make -j24
if [ -f "libil2cpp.a" ]
then
echo 'build succ'
else
echo "build fail"
exit 1
fi
-47
View File
@@ -1,47 +0,0 @@
# file: external/CMakeList.txt
cmake_minimum_required(VERSION 3.0)
set(CMAKE_OSX_DEPLOYMENT_TARGET iOS)
set(IL2CPP_SOURCE_DIR $ENV{HUATUO_IL2CPP_SOURCE_DIR})
set(SDK_VERSION $ENV{IPHONESIMULATOR_VERSION})
message(STATUS "external project, external source dir: " ${IL2CPP_SOURCE_DIR})
SET_PROPERTY(GLOBAL PROPERTY USE_FOLDERS ON)
find_program(CLANG_EXECUTABLE NAMES clang clang-7 clang-8 clang-9 clang-10)
if (NOT CLANG_EXECUTABLE)
message(FATAL_ERROR "Cannot find any clang executable.")
endif()
set(CMAKE_OSX_SYSROOT /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator${SDK_VERSION}.sdk)
set(CMAKE_VERBOSE_MAKEFILE ON)
set(CMAKE_C_COMPILER clang)
set(CMAKE_C_FLAGS "-x c -target arm64-apple-ios11.0 -fmessage-length=0 -fdiagnostics-show-note-include-stack -fmacro-backtrace-limit=0 -std=gnu11 -fmodules -fmodules-prune-interval=86400 -fmodules-prune-after=345600 -fmodules-ignore-macro=IL2CPP_TARGET_IOS=1 -fembed-bitcode -fmodules-ignore-macro=BASELIB_DYNAMICLIBRARY=1 -fmodules-ignore-macro=BASELIB_INLINE_NAMESPACE=il2cpp_baselib -fmodules-ignore-macro=AARCH64 -fmodules-ignore-macro=__aarch64__ -fmodules-ignore-macro=IL2CPP_SUPPORT_THREADS -fmodules-ignore-macro=IL2CPP_THREADS_PTHREAD -Wnon-modular-include-in-framework-module -Werror=non-modular-include-in-framework-module -Wno-trigraphs -fpascal-strings -Os -fno-common -Wno-missing-field-initializers -Wno-missing-prototypes -Werror=return-type -Wdocumentation -Wunreachable-code -Wquoted-include-in-framework-header -Werror=deprecated-objc-isa-usage -Werror=objc-root-class -Wno-missing-braces -Wparentheses -Wswitch -Wunused-function -Wno-unused-label -Wno-unused-parameter -Wunused-variable -Wunused-value -Wempty-body -Wuninitialized -Wconditional-uninitialized -Wno-unknown-pragmas -Wno-shadow -Wno-four-char-constants -Wno-conversion -Wconstant-conversion -Wint-conversion -Wbool-conversion -Wenum-conversion -Wno-float-conversion -Wnon-literal-null-conversion -Wobjc-literal-conversion -Wshorten-64-to-32 -Wpointer-sign -Wno-newline-eof -DIL2CPP_TARGET_IOS=1 -isysroot ${CMAKE_OSX_SYSROOT} -fstrict-aliasing -Wdeprecated-declarations -g -Wno-sign-conversion -Winfinite-recursion -Wcomma -Wblock-capture-autoreleasing -Wstrict-prototypes -Wno-semicolon-before-method-body -Wunguarded-availability")
add_definitions(-DIL2CPP_TARGET_IOS=1)
add_definitions(-DBASELIB_DYNAMICLIBRARY=1)
add_definitions(-DBASELIB_INLINE_NAMESPACE=il2cpp_baselib)
add_definitions(-DAARCH64)
add_definitions(-D__aarch64__)
#add_definitions(-D__arm64__)
add_definitions(-DIL2CPP_SUPPORT_THREADS)
add_definitions(-DIL2CPP_THREADS_PTHREAD)
#add_definitions(-DCMAKE_C_COMPILER=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang)
#add_definitions(-DCMAKE_CXX_COMPILER=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang++)
#add_definitions(-DIL2CPP_TARGET_DARWIN)
add_definitions(-DIL2CPP_PLATFORM_SUPPORTS_TIMEZONEINFO=0)
add_definitions(-MMD)
add_definitions(-MT dependencies)
include_directories(${IL2CPP_SOURCE_DIR}/external/)
include_directories(${IL2CPP_SOURCE_DIR}/external/baselib/Include/)
include_directories(${IL2CPP_SOURCE_DIR}/external/bdwgc/include/)
include_directories(${IL2CPP_SOURCE_DIR}/external/baselib/Platforms/OSX/Include/)
aux_source_directory(${IL2CPP_SOURCE_DIR}/external/zlib/ ZLIB_C_SOURCE_LIST)
add_library(external STATIC ${ZLIB_C_SOURCE_LIST})
-64
View File
@@ -1,64 +0,0 @@
echo '====================================================================='
echo 'gen lump'
echo '$HUATUO_IL2CPP_SOURCE_DIR='${HUATUO_IL2CPP_SOURCE_DIR} #/Applications/Unity/Unity.app/Contents/il2cpp/
GEN_SOURCE_DIR=$1
BASE_DIR=${HUATUO_IL2CPP_SOURCE_DIR}/libil2cpp
echo base dir: ${BASE_DIR}
echo " "
#BASE_DIR=${HUATUO_IL2CPP_SOURCE_DIR}/libil2cpp
function SearchCppFile()
{
for f in $(ls $1)
do
SUB_DIR=$1/$f
if [ -d ${SUB_DIR} ]; then
SearchCppFile ${SUB_DIR}
fi
done
CPP_FILE_NUM=`ls -l $1/ | grep "\.cpp$"|wc -l`
if (( ${CPP_FILE_NUM} > 0 ))
then
for f in $1/*.cpp
do
echo "#include \""$f"\"" >> ${OUTPUT_FILE_NAME}
done
fi
MM_FILE_NUM=`ls -l $1/ | grep "\.mm$"|wc -l`
if (( ${MM_FILE_NUM} > 0 ))
then
for f in $1/*.mm
do
echo "#include \""$f"\"" >> ${OBJECTIVE_FILE_NAME}
done
fi
}
rm -rf "${GEN_SOURCE_DIR}"/lump_cpp
rm -rf "${GEN_SOURCE_DIR}"/lump_mm
mkdir "${GEN_SOURCE_DIR}"/lump_cpp
mkdir "${GEN_SOURCE_DIR}"/lump_mm
OBJECTIVE_FILE_NAME=${GEN_SOURCE_DIR}/lump_mm/lump_libil2cpp_ojective.mm
echo "#include \"${BASE_DIR}/il2cpp-config.h\"" > ${OBJECTIVE_FILE_NAME}
echo gen file: ${OBJECTIVE_FILE_NAME}
for FOLDER in hybridclr vm pch utils vm-utils codegen metadata os debugger mono gc icalls
do
OUTPUT_FILE_NAME=${GEN_SOURCE_DIR}/lump_cpp/lump_libil2cpp_${FOLDER}.cpp
echo "#include \"${BASE_DIR}/il2cpp-config.h\"" > ${OUTPUT_FILE_NAME}
if [ $FOLDER = hybridclr ] || [ $FOLDER = vm ]
then
echo "#include \"${BASE_DIR}/codegen/il2cpp-codegen.h\"" >> ${OUTPUT_FILE_NAME}
fi
SearchCppFile ${BASE_DIR}/${FOLDER}
echo gen file: ${OUTPUT_FILE_NAME}
done
echo gen done.
echo '====================================================================='
echo " "
-62
View File
@@ -1,62 +0,0 @@
# file: CMakeList.txt
cmake_minimum_required(VERSION 3.0)
set(CMAKE_OSX_DEPLOYMENT_TARGET iOS)
project(il2cpp)
set(IL2CPP_SOURCE_DIR $ENV{HUATUO_IL2CPP_SOURCE_DIR})
set(SDK_VERSION $ENV{IPHONESIMULATOR_VERSION})
message(STATUS "objective project, binary dir: " ${PROJECT_BINARY_DIR})
message(STATUS "objective project, il2cpp source dir: " ${PROJECT_SOURCE_DIR})
SET_PROPERTY(GLOBAL PROPERTY USE_FOLDERS ON)
find_program(CLANG_EXECUTABLE NAMES clang clang-7 clang-8 clang-9 clang-10)
if (NOT CLANG_EXECUTABLE)
message(FATAL_ERROR "Cannot find any clang executable.")
endif()
set(CMAKE_OSX_SYSROOT /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator${SDK_VERSION}.sdk)
set(CMAKE_VERBOSE_MAKEFILE ON)
set(CMAKE_CXX_COMPILER clang++)
set(CMAKE_C_COMPILER clang)
#add_compile_options(-x objective-c++)
# 以下命令为复制的Xcode生成中的命令
set(CMAKE_CXX_FLAGS "-target arm64-apple-ios11.0 -fmessage-length=0 -fdiagnostics-show-note-include-stack -fmacro-backtrace-limit=0 -std=gnu++1z -fmodules -fmodules-prune-interval=86400 -fmodules-prune-after=345600 -fmodules-ignore-macro=IL2CPP_TARGET_IOS=1 -fembed-bitcode -fmodules-ignore-macro=BASELIB_DYNAMICLIBRARY=1 -fmodules-ignore-macro=BASELIB_INLINE_NAMESPACE=il2cpp_baselib -fmodules-ignore-macro=AARCH64 -fmodules-ignore-macro=__aarch64__ -fmodules-ignore-macro=IL2CPP_SUPPORT_THREADS -fmodules-ignore-macro=IL2CPP_THREADS_PTHREAD -Wnon-modular-include-in-framework-module -Werror=non-modular-include-in-framework-module -Wno-trigraphs -fpascal-strings -Os -fno-common -Wno-missing-field-initializers -Wno-missing-prototypes -Werror=return-type -Wdocumentation -Wunreachable-code -Wquoted-include-in-framework-header -Werror=deprecated-objc-isa-usage -Werror=objc-root-class -Wno-non-virtual-dtor -Wno-overloaded-virtual -Wno-exit-time-destructors -Wno-missing-braces -Wparentheses -Wswitch -Wno-unused-function -Wno-unused-label -Wno-unused-parameter -Wno-unused-variable -Wunused-value -Wempty-body -Wuninitialized -Wconditional-uninitialized -Wno-unknown-pragmas -Wno-shadow -Wno-four-char-constants -Wno-conversion -Wconstant-conversion -Wint-conversion -Wbool-conversion -Wenum-conversion -Wno-float-conversion -Wnon-literal-null-conversion -Wobjc-literal-conversion -Wshorten-64-to-32 -Wno-newline-eof -Wno-c++11-extensions -DIL2CPP_TARGET_IOS=1 -isysroot ${SDK_VERSION} -fasm-blocks -fstrict-aliasing -Wdeprecated-declarations -Winvalid-offsetof -g -Wno-sign-conversion -Winfinite-recursion -Wmove -Wcomma -Wblock-capture-autoreleasing -Wstrict-prototypes -Wrange-loop-analysis -Wno-semicolon-before-method-body -Wunguarded-availability ")
add_definitions(-DIL2CPP_TARGET_IOS=1)
add_definitions(-DBASELIB_DYNAMICLIBRARY=1)
add_definitions(-DBASELIB_INLINE_NAMESPACE=il2cpp_baselib)
add_definitions(-DAARCH64)
add_definitions(-D__aarch64__)
add_definitions(-DIL2CPP_SUPPORT_THREADS)
add_definitions(-DIL2CPP_THREADS_PTHREAD)
#add_definitions(-DCMAKE_C_COMPILER=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang)
#add_definitions(-DCMAKE_CXX_COMPILER=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang++)
#add_definitions(-DIL2CPP_TARGET_DARWIN)
add_definitions(-DIL2CPP_PLATFORM_SUPPORTS_TIMEZONEINFO)
add_definitions(-MMD)
add_definitions(-MT dependencies)
include_directories(${IL2CPP_SOURCE_DIR}/libil2cpp)
include_directories(${IL2CPP_SOURCE_DIR}/external)
include_directories(${IL2CPP_SOURCE_DIR}/external/baselib/Include/)
include_directories(${IL2CPP_SOURCE_DIR}/external/bdwgc/include/)
include_directories(${IL2CPP_SOURCE_DIR}/external/baselib/Platforms/OSX/Include/)
# 修改为本机对应SDK路径
include_directories(SYSTEM /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/usr/include/c++/v1)
include_directories(SYSTEM /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/usr/include)
get_filename_component(PARENT_PATH ${PROJECT_BINARY_DIR} PATH)
aux_source_directory(${PARENT_PATH}/lump_mm LUMP_SOURCE_LIST)
#find_library(zlib ${PROJECT_SOURCE_DIR}/external)
add_library(objective STATIC ${LUMP_SOURCE_LIST})
+94 -2
View File
@@ -19,8 +19,6 @@ namespace HybridCLR.Editor.ABI
{
public override bool IsArch32 => false;
public override bool IsSupportHFA => true;
protected override TypeInfo OptimizeSigType(TypeInfo type, bool returnType)
{
if (!type.IsGeneralValueType)
@@ -42,5 +40,99 @@ namespace HybridCLR.Editor.ABI
}
return TypeInfo.s_ref;
}
private static bool IsNotHFAFastCheck(int typeSize)
{
return typeSize % 4 != 0 || typeSize > 32;
}
private static bool ComputHFATypeInfo0(TypeSig type, HFATypeInfo typeInfo)
{
TypeDef typeDef = type.ToTypeDefOrRef().ResolveTypeDefThrow();
List<TypeSig> klassInst = type.ToGenericInstSig()?.GenericArguments?.ToList();
GenericArgumentContext ctx = klassInst != null ? new GenericArgumentContext(klassInst, null) : null;
var fields = typeDef.Fields;// typeDef.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
foreach (FieldDef field in fields)
{
if (field.IsStatic)
{
continue;
}
TypeSig ftype = ctx != null ? MetaUtil.Inflate(field.FieldType, ctx) : field.FieldType;
switch (ftype.ElementType)
{
case ElementType.R4:
case ElementType.R8:
{
if (ftype == typeInfo.Type || typeInfo.Type == null)
{
typeInfo.Type = ftype;
++typeInfo.Count;
}
else
{
return false;
}
break;
}
case ElementType.ValueType:
{
if (!ComputHFATypeInfo0(ftype, typeInfo))
{
return false;
}
break;
}
case ElementType.GenericInst:
{
if (!ftype.IsValueType || !ComputHFATypeInfo0(ftype, typeInfo))
{
return false;
}
break;
}
default: return false;
}
}
return typeInfo.Count <= 4;
}
private static bool ComputHFATypeInfo(TypeSig type, int typeSize, out HFATypeInfo typeInfo)
{
typeInfo = new HFATypeInfo();
if (IsNotHFAFastCheck(typeSize))
{
return false;
}
bool ok = ComputHFATypeInfo0(type, typeInfo);
if (ok && typeInfo.Count >= 1 && typeInfo.Count <= 4)
{
int fieldSize = typeInfo.Type.ElementType == ElementType.R4 ? 4 : 8;
return typeSize == fieldSize * typeInfo.Count;
}
return false;
}
protected override bool TryCreateCustomValueTypeInfo(TypeSig type, int typeSize, int typeAligment, out TypeInfo typeInfo)
{
if (ComputHFATypeInfo(type, typeSize, out HFATypeInfo hfaTypeInfo))
{
bool isFloat = hfaTypeInfo.Type.ElementType == ElementType.R4;
switch (hfaTypeInfo.Count)
{
case 1: typeInfo = isFloat ? TypeInfo.s_r4 : TypeInfo.s_r8; break;
case 2: typeInfo = isFloat ? TypeInfo.s_vf2 : TypeInfo.s_vd2; break;
case 3: typeInfo = isFloat ? TypeInfo.s_vf3 : TypeInfo.s_vd3; break;
case 4: typeInfo = isFloat ? TypeInfo.s_vf4 : TypeInfo.s_vd4; break;
default: throw new NotSupportedException();
}
return true;
}
typeInfo = null;
return false;
}
}
}
+22 -194
View File
@@ -13,10 +13,6 @@ namespace HybridCLR.Editor.ABI
{
public abstract bool IsArch32 { get; }
public virtual bool IsSupportHFA => false;
public virtual bool IsSupportWebGLSpecialValueType => false;
public TypeInfo GetNativeIntTypeInfo() => IsArch32 ? TypeInfo.s_i4 : TypeInfo.s_i8;
public ValueTypeSizeAligmentCalculator Calculator => IsArch32 ? ValueTypeSizeAligmentCalculator.Caculator32 : ValueTypeSizeAligmentCalculator.Caculator64;
@@ -24,6 +20,9 @@ namespace HybridCLR.Editor.ABI
private readonly Dictionary<TypeSig, (int, int)> _typeSizeCache = new Dictionary<TypeSig, (int, int)>(TypeEqualityComparer.Instance);
private readonly Dictionary<TypeSig, TypeInfo> _typeInfoCache = new Dictionary<TypeSig, TypeInfo>(TypeEqualityComparer.Instance);
public (int Size, int Aligment) ComputeSizeAndAligment(TypeSig t)
{
if (_typeSizeCache.TryGetValue(t, out var sizeAndAligment))
@@ -36,6 +35,16 @@ namespace HybridCLR.Editor.ABI
}
public TypeInfo CreateTypeInfo(TypeSig type)
{
if (!_typeInfoCache.TryGetValue(type, out var typeInfo))
{
typeInfo = CreateTypeInfo0(type);
_typeInfoCache.Add(type, typeInfo);
}
return new TypeInfo(typeInfo.PorType, typeInfo.Size);
}
TypeInfo CreateTypeInfo0(TypeSig type)
{
type = type.RemovePinnedAndModifiers();
if (type.IsByRef)
@@ -103,175 +112,6 @@ namespace HybridCLR.Editor.ABI
}
}
private static bool IsNotHFAFastCheck(int typeSize)
{
return typeSize % 4 != 0 || typeSize > 32;
}
private static bool ComputHFATypeInfo0(TypeSig type, HFATypeInfo typeInfo)
{
TypeDef typeDef = type.ToTypeDefOrRef().ResolveTypeDefThrow();
List<TypeSig> klassInst = type.ToGenericInstSig()?.GenericArguments?.ToList();
GenericArgumentContext ctx = klassInst != null ? new GenericArgumentContext(klassInst, null) : null;
var fields = typeDef.Fields;// typeDef.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
foreach (FieldDef field in fields)
{
if (field.IsStatic)
{
continue;
}
TypeSig ftype = ctx != null ? MetaUtil.Inflate(field.FieldType, ctx) : field.FieldType;
switch (ftype.ElementType)
{
case ElementType.R4:
case ElementType.R8:
{
if (ftype == typeInfo.Type || typeInfo.Type == null)
{
typeInfo.Type = ftype;
++typeInfo.Count;
}
else
{
return false;
}
break;
}
case ElementType.ValueType:
{
if (!ComputHFATypeInfo0(ftype, typeInfo))
{
return false;
}
break;
}
case ElementType.GenericInst:
{
if (!ftype.IsValueType || !ComputHFATypeInfo0(ftype, typeInfo))
{
return false;
}
break;
}
default: return false;
}
}
return typeInfo.Count <= 4;
}
private static bool ComputHFATypeInfo(TypeSig type, int typeSize, out HFATypeInfo typeInfo)
{
typeInfo = new HFATypeInfo();
if (IsNotHFAFastCheck(typeSize))
{
return false;
}
bool ok = ComputHFATypeInfo0(type, typeInfo);
if (ok && typeInfo.Count >= 1 && typeInfo.Count <= 4)
{
int fieldSize = typeInfo.Type.ElementType == ElementType.R4 ? 4 : 8;
return typeSize == fieldSize * typeInfo.Count;
}
return false;
}
public static bool TryComputSingletonStruct(TypeSig type, out SingletonStruct result)
{
result = new SingletonStruct();
return TryComputSingletonStruct0(type, result) && result.Type != null;
}
public static bool TryComputSingletonStruct0(TypeSig type, SingletonStruct result)
{
TypeDef typeDef = type.ToTypeDefOrRef().ResolveTypeDefThrow();
if (typeDef.IsEnum)
{
if (result.Type == null)
{
result.Type = typeDef.GetEnumUnderlyingType();
return true;
}
else
{
return false;
}
}
List<TypeSig> klassInst = type.ToGenericInstSig()?.GenericArguments?.ToList();
GenericArgumentContext ctx = klassInst != null ? new GenericArgumentContext(klassInst, null) : null;
var fields = typeDef.Fields;// typeDef.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
foreach (FieldDef field in fields)
{
if (field.IsStatic)
{
continue;
}
TypeSig ftype = ctx != null ? MetaUtil.Inflate(field.FieldType, ctx) : field.FieldType;
switch (ftype.ElementType)
{
case ElementType.TypedByRef: return false;
case ElementType.ValueType:
{
if (!TryComputSingletonStruct0(ftype, result))
{
return false;
}
break;
}
case ElementType.GenericInst:
{
if (!ftype.IsValueType)
{
goto default;
}
if (!TryComputSingletonStruct0(ftype, result))
{
return false;
}
break;
}
default:
{
if (result.Type != null)
{
return false;
}
result.Type = ftype;
break;
}
}
}
return true;
}
public static bool IsWebGLSpeicalValueType(TypeSig type)
{
TypeDef typeDef = type.ToTypeDefOrRef().ResolveTypeDefThrow();
if (typeDef.IsEnum)
{
return false;
}
var fields = typeDef.Fields;// typeDef.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (fields.Count == 0)
{
return true;
}
if (fields.All(f => f.IsStatic))
{
return true;
}
if (typeDef.IsExplicitLayout && fields.Count(f => !f.IsStatic) > 1)
{
return true;
}
return false;
}
protected static TypeInfo CreateGeneralValueType(TypeSig type, int size, int aligment)
{
System.Diagnostics.Debug.Assert(size % aligment == 0);
@@ -285,31 +125,19 @@ namespace HybridCLR.Editor.ABI
}
}
protected virtual bool TryCreateCustomValueTypeInfo(TypeSig type, int typeSize, int typeAligment, out TypeInfo typeInfo)
{
typeInfo = null;
return false;
}
protected TypeInfo CreateValueType(TypeSig type)
{
(int typeSize, int typeAligment) = ComputeSizeAndAligment(type);
if (IsSupportHFA && ComputHFATypeInfo(type, typeSize, out HFATypeInfo hfaTypeInfo))
if (TryCreateCustomValueTypeInfo(type, typeSize, typeAligment, out var typeInfo))
{
bool isFloat = hfaTypeInfo.Type.ElementType == ElementType.R4;
switch (hfaTypeInfo.Count)
{
case 1: return isFloat ? TypeInfo.s_r4 : TypeInfo.s_r8;
case 2: return isFloat ? TypeInfo.s_vf2 : TypeInfo.s_vd2;
case 3: return isFloat ? TypeInfo.s_vf3 : TypeInfo.s_vd3;
case 4: return isFloat ? TypeInfo.s_vf4 : TypeInfo.s_vd4;
default: throw new NotSupportedException();
}
}
if (IsSupportWebGLSpecialValueType && IsWebGLSpeicalValueType(type))
{
switch (typeAligment)
{
case 1: return new TypeInfo(ParamOrReturnType.SPECIAL_STRUCTURE_ALIGN1, typeSize);
case 2: return new TypeInfo(ParamOrReturnType.SPECIAL_STRUCTURE_ALIGN2, typeSize);
case 4: return new TypeInfo(ParamOrReturnType.SPECIAL_STRUCTURE_ALIGN4, typeSize);
case 8: return new TypeInfo(ParamOrReturnType.SPECIAL_STRUCTURE_ALIGN8, typeSize);
default: throw new NotSupportedException();
}
//Debug.Log($"[{GetType().Name}] CustomeValueType:{type} => {typeInfo.CreateSigName()}");
return typeInfo;
}
else
{
-2
View File
@@ -10,8 +10,6 @@ namespace HybridCLR.Editor.ABI
{
public override bool IsArch32 => true;
public override bool IsSupportHFA => false;
protected override TypeInfo OptimizeSigType(TypeInfo type, bool returnType)
{
if (type.PorType > ParamOrReturnType.STRUCTURE_ALIGN1 && type.PorType <= ParamOrReturnType.STRUCTURE_ALIGN4)
+2 -3
View File
@@ -1,4 +1,5 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -10,8 +11,6 @@ namespace HybridCLR.Editor.ABI
{
public override bool IsArch32 => false;
public override bool IsSupportHFA => false;
protected override TypeInfo OptimizeSigType(TypeInfo type, bool returnType)
{
if (type.PorType > ParamOrReturnType.STRUCTURE_ALIGN1 && type.PorType <= ParamOrReturnType.STRUCTURE_ALIGN8)
+191 -5
View File
@@ -17,11 +17,6 @@ namespace HybridCLR.Editor.ABI
{
public override bool IsArch32 => true;
public override bool IsSupportHFA => false;
public override bool IsSupportWebGLSpecialValueType => true;
protected override TypeInfo OptimizeSigType(TypeInfo type, bool returnType)
{
//if (type.PorType > ParamOrReturnType.STRUCTURE_ALIGN1 && type.PorType <= ParamOrReturnType.STRUCTURE_ALIGN4)
@@ -30,5 +25,196 @@ namespace HybridCLR.Editor.ABI
//}
return type;
}
private static bool IsEmptyOrSpeicalValueType(TypeSig type)
{
TypeDef typeDef = type.ToTypeDefOrRef().ResolveTypeDefThrow();
if (typeDef.IsEnum)
{
return false;
}
var fields = typeDef.Fields;// typeDef.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (fields.Count == 0)
{
return true;
}
if (fields.All(f => f.IsStatic))
{
return true;
}
if (typeDef.IsExplicitLayout && fields.Count(f => !f.IsStatic) > 1)
{
return true;
}
return false;
}
public static bool TryComputSingletonStructTypeInfo(TypeSig type, int typeAligment, int typeSize, out TypeInfo typeInfo)
{
typeInfo = null;
if (typeAligment > 8 || typeSize > 8)
{
return false;
}
var ss = new SingletonStruct();
if (!TryComputSingletonStruct0(type, ss) || ss.Type == null)
{
return false;
}
if (ss.Type.IsByRef)
{
typeInfo = TypeInfo.s_i4;
return true;
}
switch (ss.Type.ElementType)
{
case ElementType.Boolean:
case ElementType.Char:
case ElementType.I1:
case ElementType.U1:
case ElementType.I2:
case ElementType.U2:
case ElementType.I4:
case ElementType.U4:
case ElementType.I:
case ElementType.U:
case ElementType.String:
case ElementType.Ptr:
case ElementType.Class:
case ElementType.Array:
case ElementType.GenericInst:
case ElementType.FnPtr:
case ElementType.Object:
case ElementType.SZArray:
{
if (typeAligment <= 4 && typeSize <= 4)
{
typeInfo = TypeInfo.s_i4;
}
break;
}
case ElementType.I8:
case ElementType.U8:
{
if (typeAligment <= 8 && typeSize <= 8)
{
typeInfo = TypeInfo.s_i8;
}
break;
}
case ElementType.R4:
{
if (typeAligment <= 4 && typeSize <= 4)
{
typeInfo = TypeInfo.s_r4;
}
break;
}
case ElementType.R8:
{
if (typeAligment <= 8 && typeSize <= 8)
{
typeInfo = TypeInfo.s_r8;
}
break;
}
default: return false;
}
return typeInfo != null;
}
public static bool TryComputSingletonStruct(TypeSig type, out SingletonStruct result)
{
result = new SingletonStruct();
return TryComputSingletonStruct0(type, result) && result.Type != null;
}
public static bool TryComputSingletonStruct0(TypeSig type, SingletonStruct result)
{
TypeDef typeDef = type.ToTypeDefOrRef().ResolveTypeDefThrow();
if (typeDef.IsEnum)
{
if (result.Type == null)
{
result.Type = typeDef.GetEnumUnderlyingType();
return true;
}
else
{
return false;
}
}
List<TypeSig> klassInst = type.ToGenericInstSig()?.GenericArguments?.ToList();
GenericArgumentContext ctx = klassInst != null ? new GenericArgumentContext(klassInst, null) : null;
var fields = typeDef.Fields;// typeDef.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
foreach (FieldDef field in fields)
{
if (field.IsStatic)
{
continue;
}
TypeSig ftype = ctx != null ? MetaUtil.Inflate(field.FieldType, ctx) : field.FieldType;
switch (ftype.ElementType)
{
case ElementType.TypedByRef: return false;
case ElementType.ValueType:
{
if (!TryComputSingletonStruct0(ftype, result))
{
return false;
}
break;
}
case ElementType.GenericInst:
{
if (!ftype.IsValueType)
{
goto default;
}
if (!TryComputSingletonStruct0(ftype, result))
{
return false;
}
break;
}
default:
{
if (result.Type != null)
{
return false;
}
result.Type = ftype;
break;
}
}
}
return true;
}
protected override bool TryCreateCustomValueTypeInfo(TypeSig type, int typeSize, int typeAligment, out TypeInfo typeInfo)
{
typeInfo = null;
if (IsEmptyOrSpeicalValueType(type))
{
switch (typeAligment)
{
case 1: typeInfo = new TypeInfo(ParamOrReturnType.SPECIAL_STRUCTURE_ALIGN1, typeSize); break;
case 2: typeInfo = new TypeInfo(ParamOrReturnType.SPECIAL_STRUCTURE_ALIGN2, typeSize); break;
case 4: typeInfo = new TypeInfo(ParamOrReturnType.SPECIAL_STRUCTURE_ALIGN4, typeSize); break;
case 8: typeInfo = new TypeInfo(ParamOrReturnType.SPECIAL_STRUCTURE_ALIGN8, typeSize); break;
default: throw new NotSupportedException();
}
return true;
}
if (TryComputSingletonStructTypeInfo(type, typeAligment, typeSize, out typeInfo))
{
return true;
}
return false;
}
}
}
+8 -12
View File
@@ -58,15 +58,15 @@ namespace HybridCLR.Editor.AOT
return;
}
gc = gc.ToGenericShare();
if (_genericTypes.Add(gc) && NeedWalk(gc.Type))
if (_genericTypes.Add(gc) && NeedWalk(null, gc.Type))
{
WalkType(gc);
}
}
private bool NeedWalk(TypeDef type)
private bool NeedWalk(MethodDef callFrom, TypeDef type)
{
return _hotUpdateAssemblyFiles.Contains(type.Module.Name);
return _hotUpdateAssemblyFiles.Contains(type.Module.Name) || callFrom == null || callFrom.HasGenericParameters;
}
private bool IsAotType(TypeDef type)
@@ -79,13 +79,13 @@ namespace HybridCLR.Editor.AOT
return IsAotType(method.DeclaringType) && method.HasGenericParameters;
}
private void OnNewMethod(GenericMethod method)
private void OnNewMethod(MethodDef methodDef, List<TypeSig> klassGenericInst, List<TypeSig> methodGenericInst, GenericMethod method)
{
if(method == null)
{
return;
}
if (_genericMethods.Add(method) && NeedWalk(method.Method.DeclaringType))
if (NeedWalk(methodDef, method.Method.DeclaringType) && _genericMethods.Add(method))
{
_newMethods.Add(method);
}
@@ -101,7 +101,7 @@ namespace HybridCLR.Editor.AOT
{
return;
}
if (_genericMethods.Add(method) && NeedWalk(method.Method.DeclaringType))
if (NeedWalk(null, method.Method.DeclaringType) && _genericMethods.Add(method))
{
_newMethods.Add(method);
}
@@ -157,9 +157,9 @@ namespace HybridCLR.Editor.AOT
for (uint rid = 1, n = ass.Metadata.TablesStream.TypeSpecTable.Rows; rid <= n; rid++)
{
var ts = ass.ResolveTypeSpec(rid);
if (!ts.ContainsGenericParameter)
var cs = GenericClass.ResolveClass(ts, null)?.ToGenericShare();
if (cs != null)
{
var cs = GenericClass.ResolveClass(ts, null)?.ToGenericShare();
TryAddAndWalkGenericType(cs);
}
}
@@ -167,10 +167,6 @@ namespace HybridCLR.Editor.AOT
for (uint rid = 1, n = ass.Metadata.TablesStream.MethodSpecTable.Rows; rid <= n; rid++)
{
var ms = ass.ResolveMethodSpec(rid);
if (ms.DeclaringType.ContainsGenericParameter || ms.GenericInstMethodSig.ContainsGenericParameter)
{
continue;
}
var gm = GenericMethod.ResolveMethod(ms, null)?.ToGenericShare();
TryAddMethodNotWalkType(gm);
}
+27 -13
View File
@@ -64,18 +64,22 @@ namespace HybridCLR.Editor.AOT
Directory.CreateDirectory(parentDir);
List<string> codes = new List<string>();
codes.Add("using System.Collections.Generic;");
codes.Add("public class AOTGenericReferences : UnityEngine.MonoBehaviour");
codes.Add("{");
codes.Add("");
codes.Add("\t// {{ AOT assemblies");
codes.Add("\tpublic static readonly IReadOnlyList<string> PatchedAOTAssemblyList = new List<string>");
codes.Add("\t{");
List<dnlib.DotNet.ModuleDef> modules = new HashSet<dnlib.DotNet.ModuleDef>(
types.Select(t => t.Type.Module).Concat(methods.Select(m => m.Method.Module))).ToList();
modules.Sort((a, b) => a.Name.CompareTo(b.Name));
foreach (dnlib.DotNet.ModuleDef module in modules)
{
codes.Add($"\t// {module.Name}");
codes.Add($"\t\t\"{module.Name}\",");
}
codes.Add("\t};");
codes.Add("\t// }}");
@@ -86,11 +90,12 @@ namespace HybridCLR.Editor.AOT
codes.Add("");
codes.Add("\t// {{ AOT generic types");
types.Sort((a, b) => a.Type.FullName.CompareTo(b.Type.FullName));
foreach(var type in types)
List<string> typeNames = types.Select(t => PrettifyTypeSig(t.ToTypeSig().ToString())).ToList();
typeNames.Sort(string.CompareOrdinal);
foreach(var typeName in typeNames)
{
codes.Add($"\t// {PrettifyTypeSig(type.ToTypeSig().ToString())}");
codes.Add($"\t// {typeName}");
}
codes.Add("\t// }}");
@@ -98,27 +103,36 @@ namespace HybridCLR.Editor.AOT
codes.Add("");
codes.Add("\tpublic void RefMethods()");
codes.Add("\t{");
methods.Sort((a, b) =>
List<(string, string, string)> methodTypeAndNames = methods.Select(m =>
(PrettifyTypeSig(m.Method.DeclaringType.ToString()), PrettifyMethodSig(m.Method.Name), PrettifyMethodSig(m.ToMethodSpec().ToString())))
.ToList();
methodTypeAndNames.Sort((a, b) =>
{
int c = a.Method.DeclaringType.FullName.CompareTo(b.Method.DeclaringType.FullName);
int c = String.Compare(a.Item1, b.Item1, StringComparison.Ordinal);
if (c != 0)
{
return c;
}
c = a.Method.Name.CompareTo(b.Method.Name);
return c;
c = String.Compare(a.Item2, b.Item2, StringComparison.Ordinal);
if (c != 0)
{
return c;
}
return String.Compare(a.Item3, b.Item3, StringComparison.Ordinal);
});
foreach(var method in methods)
foreach(var method in methodTypeAndNames)
{
codes.Add($"\t\t// {PrettifyMethodSig(method.ToMethodSpec().ToString())}");
codes.Add($"\t\t// {PrettifyMethodSig(method.Item3)}");
}
codes.Add("\t}");
codes.Add("}");
var utf8WithoutBOM = new System.Text.UTF8Encoding(false);
File.WriteAllText(outputFile, string.Join("\n", codes), utf8WithoutBOM);
var utf8WithoutBom = new System.Text.UTF8Encoding(false);
File.WriteAllText(outputFile, string.Join("\n", codes), utf8WithoutBom);
Debug.Log($"[GenericReferenceWriter] write {outputFile}");
}
}
@@ -0,0 +1,256 @@
using System;
using HybridCLR.Editor.Installer;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using UnityEditor;
#if (UNITY_2020 || UNITY_2021) && UNITY_IOS
using UnityEditor.Build;
using UnityEditor.Callbacks;
using UnityEditor.iOS.Xcode;
using UnityEngine;
namespace HybridCLR.Editor
{
public static class AddLil2cppSourceCodeToXcodeproj2021OrOlder
{
//[MenuItem("Test/GenProj")]
//public static void Modify()
//{
// OnPostProcessBuild(BuildTarget.iOS, $"{SettingsUtil.ProjectDir}/Build-iOS");
//}
//[MenuItem("Test/CreateLumps")]
//public static void CreateLumpsCmd()
//{
// CreateLumps($"{SettingsUtil.LocalIl2CppDir}/libil2cpp", $"{SettingsUtil.HybridCLRDataDir}/lumps");
//}
[PostProcessBuild]
public static void OnPostProcessBuild(BuildTarget target, string pathToBuiltProject)
{
if (target != BuildTarget.iOS || !HybridCLRSettings.Instance.enable)
return;
/*
* 1. 生成lump,并且添加到工程
3. 将libil2cpp目录复制到 Library/. 删除旧的. search paths里修改 libil2cpp/include为libil2cpp
3. Libraries/bdwgc/include -> Libraries/external/bdwgc/include
4. 将external目录复制到 Library/external。删除旧目录
5. 将Library/external/baselib/Platforms/OSX改名为 IOS 全大写
6. 将 external/zlib下c 文件添加到工程
7. 移除libil2cpp.a
8. Include path add libil2cpp/os/ClassLibraryPAL/brotli/include
9. add external/xxHash
*/
string pbxprojFile = $"{pathToBuiltProject}/Unity-iPhone.xcodeproj/project.pbxproj";
string srcLibil2cppDir = $"{SettingsUtil.LocalIl2CppDir}/libil2cpp";
string dstLibil2cppDir = $"{pathToBuiltProject}/Libraries/libil2cpp";
string lumpDir = $"{pathToBuiltProject}/Libraries/lumps";
string srcExternalDir = $"{SettingsUtil.LocalIl2CppDir}/external";
string dstExternalDir = $"{pathToBuiltProject}/Libraries/external";
//RemoveExternalLibil2cppOption(srcExternalDir, dstExternalDir);
CopyLibil2cppToXcodeProj(srcLibil2cppDir, dstLibil2cppDir);
CopyExternalToXcodeProj(srcExternalDir, dstExternalDir);
var lumpFiles = CreateLumps(dstLibil2cppDir, lumpDir);
var extraSources = GetExtraSourceFiles(dstExternalDir, dstLibil2cppDir);
var cflags = new List<string>()
{
"-DIL2CPP_MONO_DEBUGGER_DISABLED",
};
ModifyPBXProject(pathToBuiltProject, pbxprojFile, lumpFiles, extraSources, cflags);
}
private static string GetRelativePathFromProj(string path)
{
return path.Substring(path.IndexOf("Libraries", StringComparison.Ordinal)).Replace('\\', '/');
}
private static void ModifyPBXProject(string pathToBuiltProject, string pbxprojFile, List<LumpFile> lumpFiles, List<string> extraFiles, List<string> cflags)
{
var proj = new PBXProject();
proj.ReadFromFile(pbxprojFile);
string targetGUID = proj.GetUnityFrameworkTargetGuid();
// 移除旧的libil2cpp.a
var libil2cppGUID = proj.FindFileGuidByProjectPath("Libraries/libil2cpp.a");
if (!string.IsNullOrEmpty(libil2cppGUID))
{
proj.RemoveFileFromBuild(targetGUID, libil2cppGUID);
proj.RemoveFile(libil2cppGUID);
File.Delete(Path.Combine(pathToBuiltProject, "Libraries", "libil2cpp.a"));
}
//var lumpGroupGuid = proj.AddFile("Lumps", $"Classes/Lumps", PBXSourceTree.Group);
foreach (var lumpFile in lumpFiles)
{
string lumpFileName = Path.GetFileName(lumpFile.lumpFile);
string projPathOfFile = $"Classes/Lumps/{lumpFileName}";
string relativePathOfFile = GetRelativePathFromProj(lumpFile.lumpFile);
string lumpGuid = proj.FindFileGuidByProjectPath(projPathOfFile);
if (!string.IsNullOrEmpty(lumpGuid))
{
proj.RemoveFileFromBuild(targetGUID, lumpGuid);
proj.RemoveFile(lumpGuid);
}
lumpGuid = proj.AddFile(relativePathOfFile, projPathOfFile, PBXSourceTree.Source);
proj.AddFileToBuild(targetGUID, lumpGuid);
}
foreach (var extraFile in extraFiles)
{
string projPathOfFile = $"Classes/Extrals/{Path.GetFileName(extraFile)}";
string extraFileGuid = proj.FindFileGuidByProjectPath(projPathOfFile);
if (!string.IsNullOrEmpty(extraFileGuid))
{
proj.RemoveFileFromBuild(targetGUID, extraFileGuid);
proj.RemoveFile(extraFileGuid);
//Debug.LogWarning($"remove exist extra file:{projPathOfFile} guid:{extraFileGuid}");
}
var lumpGuid = proj.AddFile(GetRelativePathFromProj(extraFile), projPathOfFile, PBXSourceTree.Source);
proj.AddFileToBuild(targetGUID, lumpGuid);
}
foreach(var configName in proj.BuildConfigNames())
{
//Debug.Log($"build config:{bcn}");
string configGuid = proj.BuildConfigByName(targetGUID, configName);
string headerSearchPaths = "HEADER_SEARCH_PATHS";
string hspProp = proj.GetBuildPropertyForConfig(configGuid, headerSearchPaths);
//Debug.Log($"config guid:{configGuid} prop:{hspProp}");
string newPro = hspProp.Replace("libil2cpp/include", "libil2cpp")
.Replace("Libraries/bdwgc", "Libraries/external/bdwgc");
if (!newPro.Contains("Libraries/libil2cpp/os/ClassLibraryPAL/brotli/include"))
{
newPro += " $(SRCROOT)/Libraries/libil2cpp/os/ClassLibraryPAL/brotli/include";
}
if (!newPro.Contains("Libraries/external/xxHash"))
{
newPro += " $(SRCROOT)/Libraries/external/xxHash";
}
//Debug.Log($"config:{bcn} new prop:{newPro}");
proj.SetBuildPropertyForConfig(configGuid, headerSearchPaths, newPro);
string cflagKey = "OTHER_CFLAGS";
string cfProp = proj.GetBuildPropertyForConfig(configGuid, cflagKey);
foreach (var flag in cflags)
{
if (!cfProp.Contains(flag))
{
cfProp += " " + flag;
}
}
if (configName.Contains("Debug") && !cfProp.Contains("-DIL2CPP_DEBUG="))
{
cfProp += " -DIL2CPP_DEBUG=1 -DDEBUG=1";
}
proj.SetBuildPropertyForConfig(configGuid, cflagKey, cfProp);
}
proj.WriteToFile(pbxprojFile);
}
private static void CopyLibil2cppToXcodeProj(string srcLibil2cppDir, string dstLibil2cppDir)
{
BashUtil.RemoveDir(dstLibil2cppDir);
BashUtil.CopyDir(srcLibil2cppDir, dstLibil2cppDir, true);
}
private static void CopyExternalToXcodeProj(string srcExternalDir, string dstExternalDir)
{
BashUtil.RemoveDir(dstExternalDir);
BashUtil.CopyDir(srcExternalDir, dstExternalDir, true);
string baselibPlatfromsDir = $"{dstExternalDir}/baselib/Platforms";
BashUtil.RemoveDir($"{baselibPlatfromsDir}/IOS");
BashUtil.CopyDir($"{baselibPlatfromsDir}/OSX", $"{baselibPlatfromsDir}/IOS", true);
}
class LumpFile
{
public List<string> cppFiles = new List<string>();
public readonly string lumpFile;
public readonly string il2cppConfigFile;
public LumpFile(string lumpFile, string il2cppConfigFile)
{
this.lumpFile = lumpFile;
this.il2cppConfigFile = il2cppConfigFile;
this.cppFiles.Add(il2cppConfigFile);
}
public void SaveFile()
{
var lumpFileContent = new List<string>();
foreach (var file in cppFiles)
{
lumpFileContent.Add($"#include \"{GetRelativePathFromProj(file)}\"");
}
File.WriteAllLines(lumpFile, lumpFileContent, Encoding.UTF8);
Debug.Log($"create lump file:{lumpFile}");
}
}
private static List<LumpFile> CreateLumps(string libil2cppDir, string outputDir)
{
BashUtil.RecreateDir(outputDir);
var cppFiles = Directory.GetFiles(libil2cppDir, "*.cpp", SearchOption.AllDirectories);
int maxCppFilePerLump = 50;
string il2cppConfigFile = $"{libil2cppDir}/il2cpp-config.h";
var lumpFiles = new List<LumpFile>();
for (int i = 0; i < (cppFiles.Length + maxCppFilePerLump - 1) / maxCppFilePerLump; i++)
{
var lumpFile = new LumpFile($"{outputDir}/lump_{i}.cpp", il2cppConfigFile);
for (int j = 0; j < maxCppFilePerLump; j++)
{
int index = i * maxCppFilePerLump + j;
if (index >= cppFiles.Length)
{
break;
}
lumpFile.cppFiles.Add(cppFiles[index]);
}
lumpFile.SaveFile();
lumpFiles.Add(lumpFile);
}
var mmFiles = Directory.GetFiles(libil2cppDir, "*.mm", SearchOption.AllDirectories);
if (mmFiles.Length > 0)
{
var lumpFile = new LumpFile($"{outputDir}/lump_mm.mm", il2cppConfigFile);
foreach (var file in mmFiles)
{
lumpFile.cppFiles.Add(file);
}
lumpFile.SaveFile();
lumpFiles.Add(lumpFile);
}
return lumpFiles;
}
private static List<string> GetExtraSourceFiles(string externalDir, string libil2cppDir)
{
var files = new List<string>();
foreach (string extraDir in new string[]
{
$"{externalDir}/zlib",
$"{externalDir}/xxHash",
$"{libil2cppDir}/os/ClassLibraryPAL/brotli",
})
{
if (!Directory.Exists(extraDir))
{
continue;
}
files.AddRange(Directory.GetFiles(extraDir, "*.c", SearchOption.AllDirectories));
}
return files;
}
}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 61948fcb1bc40ba47b8c10b0ae801ebb
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,56 @@
using HybridCLR.Editor.Installer;
using System.IO;
using System.Text;
using UnityEditor;
using UnityEditor.Build;
using UnityEditor.Callbacks;
using UnityEngine;
#if UNITY_2022_2_OR_NEWER && UNITY_IOS
namespace HybridCLR.Editor
{
public static class AddLil2cppSourceCodeToXcodeproj2022OrNewer
{
//[MenuItem("HybridCLR/Modfiyxcode")]
//public static void Modify()
//{
// OnPostProcessBuild(BuildTarget.iOS, $"{SettingsUtil.ProjectDir}/Build-iOS");
//}
[PostProcessBuild]
public static void OnPostProcessBuild(BuildTarget target, string pathToBuiltProject)
{
if (target != BuildTarget.iOS || !HybridCLRSettings.Instance.enable)
return;
string pbxprojFile = $"{pathToBuiltProject}/Unity-iPhone.xcodeproj/project.pbxproj";
RemoveExternalLibil2cppOption(pbxprojFile);
CopyLibil2cppToXcodeProj(pathToBuiltProject);
}
private static void RemoveExternalLibil2cppOption(string pbxprojFile)
{
string pbxprojContent = File.ReadAllText(pbxprojFile, Encoding.UTF8);
string removeBuildOption = @"--external-lib-il2-cpp=\""$PROJECT_DIR/Libraries/libil2cpp.a\""";
if (!pbxprojContent.Contains(removeBuildOption))
{
//throw new BuildFailedException("modified project.pbxproj fail");
Debug.LogError("[AddLil2cppSourceCodeToXcodeproj] modified project.pbxproj fail");
return;
}
pbxprojContent = pbxprojContent.Replace(removeBuildOption, "");
File.WriteAllText(pbxprojFile, pbxprojContent, Encoding.UTF8);
Debug.Log($"[AddLil2cppSourceCodeToXcodeproj] remove il2cpp build option '{removeBuildOption}' from file '{pbxprojFile}'");
}
private static void CopyLibil2cppToXcodeProj(string pathToBuiltProject)
{
string srcLibil2cppDir = $"{SettingsUtil.LocalIl2CppDir}/libil2cpp";
string destLibil2cppDir = $"{pathToBuiltProject}/Il2CppOutputProject/IL2CPP/libil2cpp";
BashUtil.RemoveDir(destLibil2cppDir);
BashUtil.CopyDir(srcLibil2cppDir, destLibil2cppDir, true);
}
}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: a4ce072f7e4a17248a3d9ebfd011356b
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
+1 -17
View File
@@ -17,7 +17,6 @@ namespace HybridCLR.Editor.BuildProcessors
public void OnPreprocessBuild(BuildReport report)
{
HybridCLRSettings globalSettings = SettingsUtil.HybridCLRSettings;
#if !UNITY_2020_1_OR_NEWER || !UNITY_IOS
if (!globalSettings.enable || globalSettings.useGlobalIl2cpp)
{
string oldIl2cppPath = Environment.GetEnvironmentVariable("UNITY_IL2CPP_PATH");
@@ -36,7 +35,6 @@ namespace HybridCLR.Editor.BuildProcessors
Debug.Log($"[CheckSettings] UNITY_IL2CPP_PATH 当前值为:'{curIl2cppPath}',更新为:'{SettingsUtil.LocalIl2CppDir}'");
}
}
#endif
if (!globalSettings.enable)
{
return;
@@ -54,25 +52,11 @@ namespace HybridCLR.Editor.BuildProcessors
Debug.LogError($"[CheckSettings] 当前ScriptingBackend是:{curScriptingImplementation},已经自动切换为:{targetScriptingImplementation}");
PlayerSettings.SetScriptingBackend(buildTargetGroup, targetScriptingImplementation);
}
ApiCompatibilityLevel curApiCompatibilityLevel = PlayerSettings.GetApiCompatibilityLevel(buildTargetGroup);
#if UNITY_2021_1_OR_NEWER
ApiCompatibilityLevel targetApiCompatibilityLevel = ApiCompatibilityLevel.NET_Unity_4_8;
#else
ApiCompatibilityLevel targetApiCompatibilityLevel = ApiCompatibilityLevel.NET_4_6;
#endif
if (curApiCompatibilityLevel != targetApiCompatibilityLevel)
{
Debug.LogError($"[CheckSettings] 当前ApiCompatibilityLevel是:{curApiCompatibilityLevel},已经自动切换为 {targetApiCompatibilityLevel}。由于下一次打包才生效,主动打断本次打包。");
PlayerSettings.SetApiCompatibilityLevel(buildTargetGroup, ApiCompatibilityLevel.NET_4_6);
throw new BuildFailedException("ApiCompatibilityLevel error");
}
var installer = new Installer.InstallerController();
if (!installer.HasInstalledHybridCLR())
{
throw new Exception($"你没有初始化HybridCLR,请通过菜单'HybridCLR/Installer'安装");
throw new BuildFailedException($"你没有初始化HybridCLR,请通过菜单'HybridCLR/Installer'安装");
}
HybridCLRSettings gs = SettingsUtil.HybridCLRSettings;
@@ -1,6 +1,7 @@
using HybridCLR.Editor.Meta;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@@ -25,15 +26,18 @@ namespace HybridCLR.Editor.BuildProcessors
return assemblies;
}
List<string> allHotUpdateDllNames = SettingsUtil.HotUpdateAssemblyNamesExcludePreserved;
List<string> allHotupdateDllFiles = SettingsUtil.HotUpdateAssemblyFilesExcludePreserved;
// 检查是否重复填写
var hotUpdateDllSet = new HashSet<string>();
foreach(var hotUpdateDll in allHotUpdateDllNames)
{
if (string.IsNullOrWhiteSpace(hotUpdateDll))
{
throw new BuildFailedException($"热更新 assembly 名不能为空");
}
if (!hotUpdateDllSet.Add(hotUpdateDll))
{
throw new Exception($"热更新 assembly:{hotUpdateDll} 在列表中重复,请除去重复条目");
throw new BuildFailedException($"热更新 assembly:{hotUpdateDll} 在列表中重复,请除去重复条目");
}
}
@@ -41,16 +45,24 @@ namespace HybridCLR.Editor.BuildProcessors
// 检查是否填写了正确的dll名称
foreach (var hotUpdateDllName in allHotUpdateDllNames)
{
string hotUpdateDllFile = hotUpdateDllName + ".dll";
if (assemblies.All(ass => !ass.EndsWith(hotUpdateDllFile)) && string.IsNullOrEmpty(assResolver.ResolveAssembly(hotUpdateDllName, false)))
if (assemblies.Select(Path.GetFileNameWithoutExtension).All(ass => ass != hotUpdateDllName)
&& string.IsNullOrEmpty(assResolver.ResolveAssembly(hotUpdateDllName, false)))
{
throw new Exception($"热更新 assembly:{hotUpdateDllFile} 不存在,请检查拼写错误");
throw new BuildFailedException($"热更新 assembly:{hotUpdateDllName} 不存在,请检查拼写错误");
}
Debug.Log($"[FilterHotFixAssemblies] 过滤热更新assembly:{hotUpdateDllFile}");
}
// 将热更dll从打包列表中移除
return assemblies.Where(ass => allHotupdateDllFiles.All(dll => !ass.EndsWith(dll, StringComparison.OrdinalIgnoreCase))).ToArray();
return assemblies.Where(ass =>
{
string assName = Path.GetFileNameWithoutExtension(ass);
bool reserved = allHotUpdateDllNames.All(dll => !assName.Equals(dll, StringComparison.Ordinal));
if (!reserved)
{
Debug.Log($"[FilterHotFixAssemblies] 过滤热更新assembly:{assName}");
}
return reserved;
}).ToArray();
}
}
}
@@ -10,6 +10,7 @@ using UnityEngine;
namespace HybridCLR.Editor.Commands
{
using Analyzer = HybridCLR.Editor.AOT.Analyzer;
public static class AOTReferenceGeneratorCommand
{
+33 -9
View File
@@ -12,25 +12,25 @@ namespace HybridCLR.Editor.Commands
{
public class CompileDllCommand
{
public static void CompileDll(string buildDir, BuildTarget target)
public static void CompileDll(string buildDir, BuildTarget target, bool developmentBuild)
{
var group = BuildPipeline.GetBuildTargetGroup(target);
ScriptCompilationSettings scriptCompilationSettings = new ScriptCompilationSettings();
scriptCompilationSettings.group = group;
scriptCompilationSettings.target = target;
scriptCompilationSettings.options = developmentBuild ? ScriptCompilationOptions.DevelopmentBuild : ScriptCompilationOptions.None;
Directory.CreateDirectory(buildDir);
ScriptCompilationResult scriptCompilationResult = PlayerBuildInterface.CompilePlayerScripts(scriptCompilationSettings, buildDir);
foreach (var ass in scriptCompilationResult.assemblies)
{
//Debug.LogFormat("compile assemblies:{1}/{0}", ass, buildDir);
}
#if UNITY_2022
UnityEditor.EditorUtility.ClearProgressBar();
#endif
Debug.Log("compile finish!!!");
}
public static void CompileDll(BuildTarget target)
public static void CompileDll(BuildTarget target, bool developmentBuild = false)
{
CompileDll(SettingsUtil.GetHotUpdateDllsOutputDirByTarget(target), target);
CompileDll(SettingsUtil.GetHotUpdateDllsOutputDirByTarget(target), target, developmentBuild);
}
[MenuItem("HybridCLR/CompileDll/ActiveBuildTarget", priority = 100)]
@@ -39,6 +39,12 @@ namespace HybridCLR.Editor.Commands
CompileDll(EditorUserBuildSettings.activeBuildTarget);
}
[MenuItem("HybridCLR/CompileDll/ActiveBuildTarget_Development", priority = 101)]
public static void CompileDllActiveBuildTargetDevelopment()
{
CompileDll(EditorUserBuildSettings.activeBuildTarget, true);
}
[MenuItem("HybridCLR/CompileDll/Win32", priority = 200)]
public static void CompileDllWin32()
{
@@ -51,16 +57,34 @@ namespace HybridCLR.Editor.Commands
CompileDll(BuildTarget.StandaloneWindows64);
}
[MenuItem("HybridCLR/CompileDll/Android", priority = 202)]
[MenuItem("HybridCLR/CompileDll/MacOS", priority = 202)]
public static void CompileDllMacOS()
{
CompileDll(BuildTarget.StandaloneOSX);
}
[MenuItem("HybridCLR/CompileDll/Linux", priority = 203)]
public static void CompileDllLinux()
{
CompileDll(BuildTarget.StandaloneLinux64);
}
[MenuItem("HybridCLR/CompileDll/Android", priority = 210)]
public static void CompileDllAndroid()
{
CompileDll(BuildTarget.Android);
}
[MenuItem("HybridCLR/CompileDll/IOS", priority = 203)]
[MenuItem("HybridCLR/CompileDll/IOS", priority = 220)]
public static void CompileDllIOS()
{
CompileDll(BuildTarget.iOS);
}
[MenuItem("HybridCLR/CompileDll/WebGL", priority = 230)]
public static void CompileDllWebGL()
{
CompileDll(BuildTarget.WebGL);
}
}
}
+1
View File
@@ -8,6 +8,7 @@ using UnityEngine;
namespace HybridCLR.Editor.Commands
{
using Analyzer = HybridCLR.Editor.Link.Analyzer;
public static class LinkGeneratorCommand
{
@@ -14,6 +14,7 @@ using UnityEngine;
namespace HybridCLR.Editor.Commands
{
using Analyzer = HybridCLR.Editor.MethodBridge.Analyzer;
public class MethodBridgeGeneratorCommand
{
@@ -37,6 +38,7 @@ namespace HybridCLR.Editor.Commands
OutputFile = outputFile,
GenericMethods = analyzer.GenericMethods,
NotGenericMethods = analyzer.NotGenericMethods,
SpeicalPreserveMethods = analyzer.SpeicalPreserveMethods,
});
g.PrepareMethods();
-7
View File
@@ -12,13 +12,6 @@ namespace HybridCLR.Editor.Commands
{
public static class StripAOTDllCommand
{
[MenuItem("HybridCLR/CreateAOTDllSnapshot", priority = 201)]
public static void CreateAOTDllSnapshot()
{
BuildTarget target = EditorUserBuildSettings.activeBuildTarget;
BashUtil.CopyDir(SettingsUtil.GetAssembliesPostIl2CppStripDir(target), SettingsUtil.GetAOTAssemblySnapshotDir(target), true);
}
[MenuItem("HybridCLR/Generate/AOTDlls", priority = 105)]
public static void GenerateStripedAOTDlls()
{
+38 -59
View File
@@ -6,6 +6,7 @@ using UnityEditor;
using UnityEngine;
using Debug = UnityEngine.Debug;
using System.Text.RegularExpressions;
using System.Linq;
namespace HybridCLR.Editor.Installer
{
@@ -23,11 +24,14 @@ namespace HybridCLR.Editor.Installer
private readonly HybridclrVersionManifest _versionManifest;
private readonly HybridclrVersionInfo _curDefaultVersion;
public string PackageVersion { get; private set; }
public InstallerController()
{
_curVersion = ParseUnityVersion(Application.unityVersion);
_versionManifest = GetHybridCLRVersionManifest();
_curDefaultVersion = _versionManifest.versions.Find(v => v.unity_version == _curVersion.major.ToString());
_curDefaultVersion = _versionManifest.versions.FirstOrDefault(v => v.unity_version == _curVersion.major.ToString());
PackageVersion = LoadPackageInfo().version;
}
private HybridclrVersionManifest GetHybridCLRVersionManifest()
@@ -36,6 +40,21 @@ namespace HybridCLR.Editor.Installer
return JsonUtility.FromJson<HybridclrVersionManifest>(File.ReadAllText(versionFile, Encoding.UTF8));
}
private PackageInfo LoadPackageInfo()
{
string packageJson = $"{SettingsUtil.ProjectDir}/Packages/{SettingsUtil.PackageName}/package.json";
return JsonUtility.FromJson<PackageInfo>(File.ReadAllText(packageJson, Encoding.UTF8));
}
[Serializable]
class PackageInfo
{
public string name;
public string version;
}
[Serializable]
class VersionDesc
{
@@ -74,9 +93,6 @@ namespace HybridCLR.Editor.Installer
private static readonly Regex s_unityVersionPat = new Regex(@"(\d+)\.(\d+)\.(\d+)");
public const int min2021_3_CompatibleMinorVersion = 0;
public const int min2022_3_CompatibleMinorVersion = 0;
private UnityVersion ParseUnityVersion(string versionStr)
{
var matches = s_unityVersionPat.Matches(versionStr);
@@ -84,9 +100,7 @@ namespace HybridCLR.Editor.Installer
{
return null;
}
// 找最后一个匹配的
Match match = matches[matches.Count - 1];
// Debug.Log($"capture count:{match.Groups.Count} {match.Groups[1].Value} {match.Groups[2].Value}");
int major = int.Parse(match.Groups[1].Value);
int minor1 = int.Parse(match.Groups[2].Value);
int minor2 = int.Parse(match.Groups[3].Value);
@@ -102,40 +116,30 @@ namespace HybridCLR.Editor.Installer
{
switch(majorVersion)
{
case 2021: return $"2021.3.{min2021_3_CompatibleMinorVersion}";
case 2022: return $"2022.3.{min2022_3_CompatibleMinorVersion}";
default: throw new Exception($"not support version:{majorVersion}");
case 2020: return $"2020.3.0";
case 2021: return $"2021.3.0";
case 2022: return $"2022.3.0";
default: return $"2020.3.0";
}
}
public bool IsComaptibleVersion()
public bool IsCompatibleVersion()
{
UnityVersion version = _curVersion;
switch (version.major)
if (version == null)
{
case 2021:
{
if (version.minor1 != 3)
{
return false;
}
return version.minor2 >= min2021_3_CompatibleMinorVersion;
}
case 2022:
{
if (version.minor1 != 3)
{
return false;
}
return version.minor2 >= min2022_3_CompatibleMinorVersion;
}
default: throw new Exception($"not support il2cpp_plus branch:{version.major}");
return false;
}
if (version.minor1 != 3)
{
return false;
}
return true;
}
public string HybridclrLocalVersion => _curDefaultVersion.hybridclr.branch;
public string HybridclrLocalVersion => _curDefaultVersion?.hybridclr?.branch;
public string Il2cppPlusLocalVersion => _curDefaultVersion.il2cpp_plus.branch;
public string Il2cppPlusLocalVersion => _curDefaultVersion?.il2cpp_plus?.branch;
private string GetIl2CppPathByContentPath(string contentPath)
@@ -155,25 +159,6 @@ namespace HybridCLR.Editor.Installer
return Directory.Exists($"{SettingsUtil.LocalIl2CppDir}/libil2cpp/hybridclr");
}
private string GetUnityIl2CppDllInstallLocation()
{
#if UNITY_EDITOR_WIN
return $"{SettingsUtil.LocalIl2CppDir}/build/deploy/net471/Unity.IL2CPP.dll";
#else
return $"{SettingsUtil.LocalIl2CppDir}/build/deploy/il2cppcore/Unity.IL2CPP.dll";
#endif
}
private string GetUnityIl2CppDllModifiedPath(string curVersionStr)
{
#if UNITY_EDITOR_WIN
return $"{SettingsUtil.ProjectDir}/{SettingsUtil.HybridCLRDataPathInPackage}/ModifiedUnityAssemblies/{curVersionStr}/Unity.IL2CPP-Win.dll.bytes";
#else
return $"{SettingsUtil.ProjectDir}/{SettingsUtil.HybridCLRDataPathInPackage}/ModifiedUnityAssemblies/{curVersionStr}/Unity.IL2CPP-Mac.dll.bytes";
#endif
}
void CloneBranch(string workDir, string repoUrl, string branch, string repoDir)
{
BashUtil.RemoveDir(repoDir);
@@ -217,19 +202,13 @@ namespace HybridCLR.Editor.Installer
private void RunInitLocalIl2CppData(string editorIl2cppPath, string libil2cppWithHybridclrSourceDir, UnityVersion version)
{
if (!IsComaptibleVersion())
if (!IsCompatibleVersion())
{
Debug.LogError($"il2cpp 版本不兼容,最小版本为 {GetCurrentUnityVersionMinCompatibleVersionStr()}");
Debug.LogError($"Incompatible with current version, minimum compatible version: {GetCurrentUnityVersionMinCompatibleVersionStr()}");
return;
}
string workDir = SettingsUtil.HybridCLRDataDir;
Directory.CreateDirectory(workDir);
//BashUtil.RecreateDir(workDir);
string buildiOSDir = $"{workDir}/iOSBuild";
BashUtil.RemoveDir(buildiOSDir);
BashUtil.CopyDir($"{SettingsUtil.HybridCLRDataPathInPackage}/iOSBuild", buildiOSDir, true);
// create LocalIl2Cpp
string localUnityDataDir = SettingsUtil.LocalUnityDataDir;
@@ -250,11 +229,11 @@ namespace HybridCLR.Editor.Installer
if (HasInstalledHybridCLR())
{
Debug.Log("安装成功");
Debug.Log("Install Sucessfully");
}
else
{
Debug.LogError("安装失败");
Debug.LogError("Installation failed!");
}
}
}
+30 -43
View File
@@ -30,7 +30,7 @@ namespace HybridCLR.Editor.Installer
height = 24
};
var content = EditorGUIUtility.IconContent("Settings");
content.tooltip = "点击打开HybridCLR Settings";
content.tooltip = "HybridCLR Settings";
if (GUI.Button(rect, content, GUI.skin.GetStyle("IconButton")))
{
SettingsService.OpenProjectSettings("Project/HybridCLR Settings");
@@ -41,70 +41,57 @@ namespace HybridCLR.Editor.Installer
GUILayout.Space(10f);
EditorGUILayout.BeginVertical("box");
EditorGUILayout.LabelField($"安装状态:{(hasInstall ? "已安装" : "未安装")}", EditorStyles.boldLabel);
EditorGUILayout.LabelField($"Installed: {hasInstall}", EditorStyles.boldLabel);
GUILayout.Space(10f);
EditorGUILayout.LabelField($"HybridCLR 版本: {_controller.HybridclrLocalVersion}");
EditorGUILayout.LabelField($"Package Version: v{_controller.PackageVersion}");
GUILayout.Space(5f);
EditorGUILayout.LabelField($"il2cpp_plus 版本: {_controller.Il2cppPlusLocalVersion}");
GUILayout.Space(5f);
//GUIInstallButton("检查更新", "检查", UpdateHybridCLR);
//GUILayout.Space(40f);
GUILayout.Space(10f);
if (_controller.IsCompatibleVersion())
{
EditorGUILayout.BeginHorizontal();
_installFromDir = EditorGUILayout.Toggle("Copy libil2cpp from local", _installFromDir, GUILayout.MinWidth(100));
EditorGUI.BeginDisabledGroup(!_installFromDir);
EditorGUILayout.TextField(_installLibil2cppWithHybridclrSourceDir, GUILayout.Width(400));
if (GUILayout.Button("Choose", GUILayout.Width(100)))
{
_installLibil2cppWithHybridclrSourceDir = EditorUtility.OpenFolderPanel("Select libil2cpp", Application.dataPath, "libil2cpp");
}
EditorGUI.EndDisabledGroup();
EditorGUILayout.EndHorizontal();
//EditorGUILayout.BeginHorizontal();
//EditorGUILayout.LabelField("待安装的 hybridclr 仓库版本号(或branch或tag)(默认取最新版本):", GUILayout.MaxWidth(400));
//_hybridclrVersion = EditorGUILayout.TextField(_hybridclrVersion);
//EditorGUILayout.EndHorizontal();
GUILayout.Space(20f);
//EditorGUILayout.BeginHorizontal();
//EditorGUILayout.LabelField($"待安装的 il2cpp_plus 仓库版本号(或branch或tag)(默认取{_controller.MajorVersion}-main分支最新版本):", GUILayout.MaxWidth(400));
//_il2cppPlusVersion = EditorGUILayout.TextField(_il2cppPlusVersion);
//EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("Install", GUILayout.Width(100)))
{
InstallLocalHybridCLR();
GUIUtility.ExitGUI();
}
EditorGUILayout.EndHorizontal();
}
else
{
EditorGUILayout.HelpBox($"Incompatible with current version, minimum compatible version:{_controller.GetCurrentUnityVersionMinCompatibleVersionStr()}", MessageType.Error);
}
GUIInstallButton("安装hybridclr+il2cpp_plus代码到本地目录", "安装");
EditorGUILayout.EndVertical();
}
private void GUIInstallButton(string content, string button)
{
EditorGUILayout.BeginHorizontal();
_installFromDir = EditorGUILayout.Toggle("从本地复制libil2cpp", _installFromDir);
EditorGUI.BeginDisabledGroup(!_installFromDir);
EditorGUILayout.TextField(_installLibil2cppWithHybridclrSourceDir, GUILayout.Width(400));
if (GUILayout.Button("选择目录", GUILayout.Width(100)))
{
_installLibil2cppWithHybridclrSourceDir = EditorUtility.OpenFolderPanel("选择libil2cpp目录", Application.dataPath, "libil2cpp");
}
EditorGUI.EndDisabledGroup();
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField(content);
if (GUILayout.Button(button, GUILayout.Width(100)))
{
InstallLocalHybridCLR();
GUIUtility.ExitGUI();
}
EditorGUILayout.EndHorizontal();
}
private void InstallLocalHybridCLR()
{
if (_installFromDir)
{
if (!Directory.Exists(_installLibil2cppWithHybridclrSourceDir))
{
Debug.LogError($"本地libil2cpp复制目录不存在. '{_installLibil2cppWithHybridclrSourceDir}'");
Debug.LogError($"Source libil2cpp:'{_installLibil2cppWithHybridclrSourceDir}' doesn't exist.");
return;
}
if (!File.Exists($"{_installLibil2cppWithHybridclrSourceDir}/il2cpp-config.h") || !File.Exists($"{_installLibil2cppWithHybridclrSourceDir}/hybridclr/RuntimeApi.cpp"))
{
Debug.LogError($"本地libil2cpp不是合法有效的源码目录. '{_installLibil2cppWithHybridclrSourceDir}'");
Debug.LogError($"Source libil2cpp:' {_installLibil2cppWithHybridclrSourceDir} ' is invalid");
return;
}
_controller.InstallFromLocal(_installLibil2cppWithHybridclrSourceDir);
+5 -5
View File
@@ -22,18 +22,18 @@ namespace HybridCLR.Editor.Link
writer.WriteStartElement("linker");
var typesByAssembly = refTypes.GroupBy(t => t.DefinitionAssembly.Name.String).ToList();
typesByAssembly.Sort((a, b) => a.Key.CompareTo(b.Key));
typesByAssembly.Sort((a, b) => String.Compare(a.Key, b.Key, StringComparison.Ordinal));
foreach(var assembly in typesByAssembly)
{
writer.WriteStartElement("assembly");
writer.WriteAttributeString("fullname", assembly.Key);
List<TypeRef> assTypes = assembly.ToList();
assTypes.Sort((a, b) => a.FullName.CompareTo(b.FullName));
foreach(var type in assTypes)
List<string> assTypeNames = assembly.Select(t => t.FullName).ToList();
assTypeNames.Sort(string.CompareOrdinal);
foreach(var typeName in assTypeNames)
{
writer.WriteStartElement("type");
writer.WriteAttributeString("fullname", type.FullName);
writer.WriteAttributeString("fullname", typeName);
writer.WriteAttributeString("preserve", "all");
writer.WriteEndElement();
}
+2
View File
@@ -93,6 +93,8 @@ namespace HybridCLR.Editor.Meta
case ElementType.SZArray: return corTypes.Object;
case ElementType.Array: return corTypes.Object;
case ElementType.ValueType: return typeSig;
case ElementType.Var:
case ElementType.MVar:
case ElementType.Class: return corTypes.Object;
case ElementType.GenericInst:
{
+5 -13
View File
@@ -1,4 +1,5 @@
using dnlib.DotNet;
using HybridCLR.Editor.ABI;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
@@ -10,26 +11,17 @@ namespace HybridCLR.Editor.Meta
{
public class MethodReferenceAnalyzer
{
private readonly Action<GenericMethod> _onNewMethod;
private readonly Action<MethodDef, List<TypeSig>, List<TypeSig>, GenericMethod> _onNewMethod;
private readonly ConcurrentDictionary<MethodDef, List<IMethod>> _methodEffectInsts = new ConcurrentDictionary<MethodDef, List<IMethod>>();
public MethodReferenceAnalyzer(Action<GenericMethod> onNewMethod)
public MethodReferenceAnalyzer(Action<MethodDef, List<TypeSig>, List<TypeSig>, GenericMethod> onNewMethod)
{
_onNewMethod = onNewMethod;
}
public void WalkMethod(MethodDef method, List<TypeSig> klassGenericInst, List<TypeSig> methodGenericInst)
{
if (klassGenericInst != null || methodGenericInst != null)
{
//var typeSig = klassGenericInst != null ? new GenericInstSig(method.DeclaringType.ToTypeSig().ToClassOrValueTypeSig(), klassGenericInst) : method.DeclaringType?.ToTypeSig();
//Debug.Log($"== walk generic method {typeSig}::{method.Name} {method.MethodSig}");
}
else
{
//Debug.Log($"== walk not geneeric method:{method}");
}
var ctx = new GenericArgumentContext(klassGenericInst, methodGenericInst);
if (_methodEffectInsts.TryGetValue(method, out var effectInsts))
@@ -37,7 +29,7 @@ namespace HybridCLR.Editor.Meta
foreach (var met in effectInsts)
{
var resolveMet = GenericMethod.ResolveMethod(met, ctx)?.ToGenericShare();
_onNewMethod(resolveMet);
_onNewMethod(method, klassGenericInst, methodGenericInst, resolveMet);
}
return;
}
@@ -69,7 +61,7 @@ namespace HybridCLR.Editor.Meta
continue;
}
effectInsts.Add(met);
_onNewMethod(resolveMet);
_onNewMethod(method, klassGenericInst, methodGenericInst, resolveMet);
break;
}
case ITokenOperand token:
+12 -15
View File
@@ -30,6 +30,8 @@ namespace HybridCLR.Editor.MethodBridge
private readonly HashSet<GenericClass> _genericTypes = new HashSet<GenericClass>();
private readonly HashSet<GenericMethod> _genericMethods = new HashSet<GenericMethod>();
private readonly HashSet<GenericMethod> _speicalPreserveMethods = new HashSet<GenericMethod>();
private List<GenericMethod> _processingMethods = new List<GenericMethod>();
private List<GenericMethod> _newMethods = new List<GenericMethod>();
@@ -37,6 +39,8 @@ namespace HybridCLR.Editor.MethodBridge
public IReadOnlyList<MethodDef> NotGenericMethods => _notGenericMethods;
public HashSet<GenericMethod> SpeicalPreserveMethods => _speicalPreserveMethods;
public IReadOnlyCollection<GenericClass> GenericTypes => _genericTypes;
public IReadOnlyCollection<GenericMethod> GenericMethods => _genericMethods;
@@ -67,7 +71,7 @@ namespace HybridCLR.Editor.MethodBridge
}
}
private void OnNewMethod(GenericMethod method)
private void OnNewMethod(MethodDef methodDef, List<TypeSig> klassGenericInst, List<TypeSig> methodGenericInst, GenericMethod method)
{
lock(_lock)
{
@@ -75,6 +79,10 @@ namespace HybridCLR.Editor.MethodBridge
{
_newMethods.Add(method);
}
if (methodDef.HasGenericParameters)
{
_speicalPreserveMethods.Add(method);
}
if (method.KlassInst != null)
{
TryAddAndWalkGenericType(new GenericClass(method.Method.DeclaringType, method.KlassInst));
@@ -141,23 +149,16 @@ namespace HybridCLR.Editor.MethodBridge
for (uint rid = 1, n = ass.Metadata.TablesStream.TypeSpecTable.Rows; rid <= n; rid++)
{
var ts = ass.ResolveTypeSpec(rid);
if (!ts.ContainsGenericParameter)
var cs = GenericClass.ResolveClass(ts, null)?.ToGenericShare();
if (cs != null)
{
var cs = GenericClass.ResolveClass(ts, null)?.ToGenericShare();
if (cs != null)
{
TryAddAndWalkGenericType(cs);
}
TryAddAndWalkGenericType(cs);
}
}
for (uint rid = 1, n = ass.Metadata.TablesStream.MethodSpecTable.Rows; rid <= n; rid++)
{
var ms = ass.ResolveMethodSpec(rid);
if(ms.DeclaringType.ContainsGenericParameter || ms.GenericInstMethodSig.ContainsGenericParameter)
{
continue;
}
var gm = GenericMethod.ResolveMethod(ms, null)?.ToGenericShare();
if (gm == null)
{
@@ -168,10 +169,6 @@ namespace HybridCLR.Editor.MethodBridge
{
_newMethods.Add(gm);
}
//if (gm.KlassInst != null)
//{
// TryAddAndWalkGenericType(new GenericClass(gm.Method.DeclaringType, gm.KlassInst));
//}
}
}
Debug.Log($"PostPrepare allMethods:{_notGenericMethods.Count} newMethods:{_newMethods.Count}");
+42 -44
View File
@@ -4,6 +4,7 @@ using HybridCLR.Editor.Meta;
using HybridCLR.Editor.Template;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Reflection;
@@ -28,13 +29,17 @@ namespace HybridCLR.Editor.MethodBridge
public IReadOnlyList<MethodDef> NotGenericMethods { get; set; }
public IReadOnlyCollection<GenericMethod> GenericMethods { get; set; }
public HashSet<GenericMethod> SpeicalPreserveMethods { get; set; }
}
private PlatformABI _platformABI;
private readonly IReadOnlyList<MethodDef> _notGenericMethods;
private readonly List<MethodDef> _notGenericMethods;
private readonly IReadOnlyCollection<GenericMethod> _genericMethods;
private readonly List<GenericMethod> _genericMethods;
private readonly HashSet<GenericMethod> _preservedMethods;
private readonly string _templateCode;
@@ -46,21 +51,23 @@ namespace HybridCLR.Editor.MethodBridge
private readonly HashSet<MethodDesc> _managed2nativeMethodSet = new HashSet<MethodDesc>();
private List<MethodDesc> _managed2nativeMethodList;
private readonly HashSet<MethodDesc> _native2managedMethodSet = new HashSet<MethodDesc>();
private List<MethodDesc> _native2managedMethodList;
private readonly HashSet<MethodDesc> _adjustThunkMethodSet = new HashSet<MethodDesc>();
private List<MethodDesc> _adjustThunkMethodList;
public Generator(Options options)
{
_platformABI = options.PlatformABI;
_notGenericMethods = options.NotGenericMethods;
_genericMethods = options.GenericMethods;
List<(MethodDef, string)> notGenericMethodInfo = options.NotGenericMethods.Select(m => (m, m.FullName)).ToList();
notGenericMethodInfo.Sort((a, b) => string.Compare(a.Item2, b.Item2, StringComparison.Ordinal));
_notGenericMethods = notGenericMethodInfo.Select(m => m.Item1).ToList();
List<(GenericMethod, string)> genericMethodInfo = options.GenericMethods.Select(m => (m, m.ToString())).ToList();
genericMethodInfo.Sort((a, b) => string.CompareOrdinal(a.Item2, b.Item2));
_genericMethods = genericMethodInfo.Select(m => m.Item1).ToList();
_preservedMethods = options.SpeicalPreserveMethods;
_templateCode = options.TemplateCode;
_outputFile = options.OutputFile;
_platformAdaptor = CreatePlatformAdaptor(options.PlatformABI);
@@ -122,7 +129,14 @@ namespace HybridCLR.Editor.MethodBridge
{
if (method.IsPrivate || (method.IsAssembly && !method.IsPublic && !method.IsFamily))
{
return;
if (!_preservedMethods.Contains(new GenericMethod(method, klassInst, methodInst)))
{
return;
}
else
{
//Debug.Log($"[PreservedMethod] method:{method}");
}
}
TypeSig returnType;
@@ -169,31 +183,6 @@ namespace HybridCLR.Editor.MethodBridge
{
ProcessMethod(method.Method, method.KlassInst, method.MethodInst);
}
{
var sortedMethods = new SortedDictionary<string, MethodDesc>();
foreach (var method in _managed2nativeMethodSet)
{
sortedMethods.Add(method.CreateCallSigName(), method);
}
_managed2nativeMethodList = sortedMethods.Values.ToList();
}
{
var sortedMethods = new SortedDictionary<string, MethodDesc>();
foreach (var method in _native2managedMethodSet)
{
sortedMethods.Add(method.CreateCallSigName(), method);
}
_native2managedMethodList = sortedMethods.Values.ToList();
}
{
var sortedMethods = new SortedDictionary<string, MethodDesc>();
foreach (var method in _adjustThunkMethodSet)
{
sortedMethods.Add(method.CreateCallSigName(), method);
}
_adjustThunkMethodList = sortedMethods.Values.ToList();
}
}
public void Generate()
@@ -202,29 +191,38 @@ namespace HybridCLR.Editor.MethodBridge
List<string> lines = new List<string>(20_0000);
Debug.LogFormat("== managed2native:{0} native2managed:{1} adjustThunk:{2}",
_managed2nativeMethodList.Count, _native2managedMethodList.Count, _adjustThunkMethodList.Count);
List<MethodDesc> managed2NativeMethodList = _managed2nativeMethodSet.ToList();
managed2NativeMethodList.Sort((a, b) => string.CompareOrdinal(a.Sig, b.Sig));
foreach(var method in _managed2nativeMethodList)
List<MethodDesc> native2ManagedMethodList = _native2managedMethodSet.ToList();
native2ManagedMethodList.Sort((a, b) => string.CompareOrdinal(a.Sig, b.Sig));
List<MethodDesc> adjustThunkMethodList = _adjustThunkMethodSet.ToList();
adjustThunkMethodList.Sort((a, b) => string.CompareOrdinal(a.Sig, b.Sig));
Debug.LogFormat("== managed2native:{0} native2managed:{1} adjustThunk:{2}",
managed2NativeMethodList.Count, native2ManagedMethodList.Count, adjustThunkMethodList.Count);
foreach(var method in managed2NativeMethodList)
{
_platformAdaptor.GenerateManaged2NativeMethod(method, lines);
}
_platformAdaptor.GenerateManaged2NativeStub(_managed2nativeMethodList, lines);
_platformAdaptor.GenerateManaged2NativeStub(managed2NativeMethodList, lines);
foreach (var method in _native2managedMethodList)
foreach (var method in native2ManagedMethodList)
{
_platformAdaptor.GenerateNative2ManagedMethod(method, lines);
}
_platformAdaptor.GenerateNative2ManagedStub(_native2managedMethodList, lines);
_platformAdaptor.GenerateNative2ManagedStub(native2ManagedMethodList, lines);
foreach (var method in _adjustThunkMethodList)
foreach (var method in adjustThunkMethodList)
{
_platformAdaptor.GenerateAdjustThunkMethod(method, lines);
}
_platformAdaptor.GenerateAdjustThunkStub(_adjustThunkMethodList, lines);
_platformAdaptor.GenerateAdjustThunkStub(adjustThunkMethodList, lines);
frr.Replace("CODE", string.Join("\n", lines));
@@ -19,12 +19,10 @@ namespace HybridCLR.Editor.MethodBridge
public override void GenerateManaged2NativeMethod(MethodDesc method, List<string> lines)
{
int totalQuadWordNum = method.ParamInfos.Count + method.ReturnInfo.GetParamSlotNum(this.PlatformABI);
string paramListStr = string.Join(", ", method.ParamInfos.Select(p => $"{p.Type.GetTypeName()} __arg{p.Index}").Concat(new string[] { "const MethodInfo* method" }));
string paramNameListStr = string.Join(", ", method.ParamInfos.Select(p => p.Managed2NativeParamValue(this.PlatformABI)).Concat(new string[] { "method" }));
lines.Add($@"
// {method.MethodDef}
static void __M2N_{method.CreateCallSigName()}(const MethodInfo* method, uint16_t* argVarIndexs, StackObject* localVarBase, void* ret)
{{
typedef {method.ReturnInfo.Type.GetTypeName()} (*NativeMethod)({paramListStr});
@@ -39,7 +37,6 @@ static void __M2N_{method.CreateCallSigName()}(const MethodInfo* method, uint16_
string paramListStr = string.Join(", ", method.ParamInfos.Select(p => $"{p.Type.GetTypeName()} __arg{p.Index}").Concat(new string[] { "const MethodInfo* method" }));
lines.Add($@"
// {method.MethodDef}
static {method.ReturnInfo.Type.GetTypeName()} __N2M_{method.CreateCallSigName()}({paramListStr})
{{
StackObject args[{Math.Max(totalQuadWordNum, 1)}] = {{{string.Join(", ", method.ParamInfos.Select(p => p.Native2ManagedParamValue(this.PlatformABI)))} }};
@@ -57,7 +54,6 @@ static {method.ReturnInfo.Type.GetTypeName()} __N2M_{method.CreateCallSigName()}
string paramListStr = string.Join(", ", method.ParamInfos.Select(p => $"{p.Type.GetTypeName()} __arg{p.Index}").Concat(new string[] { "const MethodInfo* method" }));
lines.Add($@"
// {method.MethodDef}
static {method.ReturnInfo.Type.GetTypeName()} __N2M_AdjustorThunk_{method.CreateCallSigName()}({paramListStr})
{{
StackObject args[{Math.Max(totalQuadWordNum, 1)}] = {{{string.Join(", ", method.ParamInfos.Select(p => (p.Index == 0 ? $"(uint64_t)(*(uint8_t**)&__arg{p.Index} + sizeof(Il2CppObject))" : p.Native2ManagedParamValue(this.PlatformABI))))} }};
@@ -20,7 +20,6 @@ namespace HybridCLR.Editor.MethodBridge
string paramNameListStr = string.Join(", ", method.ParamInfos.Select(p => p.Managed2NativeParamValue(this.PlatformABI)).Concat(new string[] { "method" }));
lines.Add($@"
// {method.MethodDef}
static void __M2N_{method.CreateCallSigName()}(const MethodInfo* method, uint16_t* argVarIndexs, StackObject* localVarBase, void* ret)
{{
typedef {method.ReturnInfo.Type.GetTypeName()} (*NativeMethod)({paramListStr});
@@ -34,7 +33,6 @@ static void __M2N_{method.CreateCallSigName()}(const MethodInfo* method, uint16_
string paramListStr = string.Join(", ", method.ParamInfos.Select(p => $"{p.Type.GetTypeName()} __arg{p.Index}").Concat(new string[] { "const MethodInfo* method" }));
lines.Add($@"
// {method.MethodDef}
static {method.ReturnInfo.Type.GetTypeName()} __N2M_{method.CreateCallSigName()}({paramListStr})
{{
StackObject args[{Math.Max(totalQuadWordNum, 1)}] = {{{string.Join(", ", method.ParamInfos.Select(p => p.Native2ManagedParamValue(this.PlatformABI)))} }};
@@ -51,7 +49,6 @@ static {method.ReturnInfo.Type.GetTypeName()} __N2M_{method.CreateCallSigName()}
string paramListStr = string.Join(", ", method.ParamInfos.Select(p => $"{p.Type.GetTypeName()} __arg{p.Index}").Concat(new string[] { "const MethodInfo* method" }));
lines.Add($@"
// {method.MethodDef}
static {method.ReturnInfo.Type.GetTypeName()} __N2M_AdjustorThunk_{method.CreateCallSigName()}({paramListStr})
{{
StackObject args[{Math.Max(totalQuadWordNum, 1)}] = {{{string.Join(", ", method.ParamInfos.Select(p => (p.Index == 0 ? $"(uint64_t)(*(uint8_t**)&__arg{p.Index} + sizeof(Il2CppObject))" : p.Native2ManagedParamValue(this.PlatformABI))))} }};
@@ -17,14 +17,11 @@ namespace HybridCLR.Editor.MethodBridge
public override void GenerateManaged2NativeMethod(MethodDesc method, List<string> lines)
{
int totalQuadWordNum = method.ParamInfos.Count + method.ReturnInfo.GetParamSlotNum(this.PlatformABI);
string paramListStr = string.Join(", ", method.ParamInfos.Select(p => $"{p.Type.GetTypeName()} __arg{p.Index}").Concat(new string[] { "const MethodInfo* method" }));
string paramTypeListStr = string.Join(", ", method.ParamInfos.Select(p => $"{p.Type.GetTypeName()}").Concat(new string[] { "const MethodInfo*" })); ;
string paramNameListStr = string.Join(", ", method.ParamInfos.Select(p => p.Managed2NativeParamValue(this.PlatformABI)).Concat(new string[] { "method" }));
lines.Add($@"
// {method.MethodDef}
static void __M2N_{method.CreateCallSigName()}(const MethodInfo* method, uint16_t* argVarIndexs, StackObject* localVarBase, void* ret)
{{
typedef {method.ReturnInfo.Type.GetTypeName()} (*NativeMethod)({paramListStr});
@@ -37,7 +34,6 @@ static void __M2N_{method.CreateCallSigName()}(const MethodInfo* method, uint16_
int totalQuadWordNum = method.ParamInfos.Count + method.ReturnInfo.GetParamSlotNum(this.PlatformABI);
string paramListStr = string.Join(", ", method.ParamInfos.Select(p => $"{p.Type.GetTypeName()} __arg{p.Index}").Concat(new string[] { "const MethodInfo* method" }));
lines.Add($@"
// {method.MethodDef}
static {method.ReturnInfo.Type.GetTypeName()} __N2M_{method.CreateCallSigName()}({paramListStr})
{{
StackObject args[{Math.Max(totalQuadWordNum, 1)}] = {{{string.Join(", ", method.ParamInfos.Select(p => p.Native2ManagedParamValue(this.PlatformABI)))} }};
@@ -53,7 +49,6 @@ static {method.ReturnInfo.Type.GetTypeName()} __N2M_{method.CreateCallSigName()}
int totalQuadWordNum = method.ParamInfos.Count + method.ReturnInfo.GetParamSlotNum(this.PlatformABI);
string paramListStr = string.Join(", ", method.ParamInfos.Select(p => $"{p.Type.GetTypeName()} __arg{p.Index}").Concat(new string[] { "const MethodInfo* method" }));
lines.Add($@"
// {method.MethodDef}
static {method.ReturnInfo.Type.GetTypeName()} __N2M_AdjustorThunk_{method.CreateCallSigName()}({paramListStr})
{{
StackObject args[{Math.Max(totalQuadWordNum, 1)}] = {{{string.Join(", ", method.ParamInfos.Select(p => (p.Index == 0 ? $"(uint64_t)(*(uint8_t**)&__arg{p.Index} + sizeof(Il2CppObject))" : p.Native2ManagedParamValue(this.PlatformABI))))} }};
@@ -21,7 +21,6 @@ namespace HybridCLR.Editor.MethodBridge
string paramNameListStr = string.Join(", ", method.ParamInfos.Select(p => p.Managed2NativeParamValue(this.PlatformABI)).Concat(new string[] { "method" }));
lines.Add($@"
// {method.MethodDef}
static void __M2N_{method.CreateCallSigName()}(const MethodInfo* method, uint16_t* argVarIndexs, StackObject* localVarBase, void* ret)
{{
typedef {method.ReturnInfo.Type.GetTypeName()} (*NativeMethod)({paramListStr});
@@ -35,7 +34,6 @@ static void __M2N_{method.CreateCallSigName()}(const MethodInfo* method, uint16_
string paramListStr = string.Join(", ", method.ParamInfos.Select(p => $"{p.Type.GetTypeName()} __arg{p.Index}").Concat(new string[] { "const MethodInfo* method" }));
lines.Add($@"
// {method.MethodDef}
static {method.ReturnInfo.Type.GetTypeName()} __N2M_{method.CreateCallSigName()}({paramListStr})
{{
StackObject args[{Math.Max(totalQuadWordNum, 1)}] = {{{string.Join(", ", method.ParamInfos.Select(p => p.Native2ManagedParamValue(this.PlatformABI)))} }};
@@ -52,7 +50,6 @@ static {method.ReturnInfo.Type.GetTypeName()} __N2M_{method.CreateCallSigName()}
string paramListStr = string.Join(", ", method.ParamInfos.Select(p => $"{p.Type.GetTypeName()} __arg{p.Index}").Concat(new string[] { "const MethodInfo* method" }));
lines.Add($@"
// {method.MethodDef}
static {method.ReturnInfo.Type.GetTypeName()} __N2M_AdjustorThunk_{method.CreateCallSigName()}({paramListStr})
{{
StackObject args[{Math.Max(totalQuadWordNum, 1)}] = {{{string.Join(", ", method.ParamInfos.Select(p => (p.Index == 0 ? $"(uint64_t)(*(uint8_t**)&__arg{p.Index} + sizeof(Il2CppObject))" : p.Native2ManagedParamValue(this.PlatformABI))))} }};
+1 -1
View File
@@ -97,7 +97,7 @@ namespace HybridCLR.Editor.ReversePInvokeWrap
arm.Count += preserveCount;
}
var methods = methodsBySig.Values.ToList();
methods.Sort((a, b) => a.Method.Sig.CompareTo(b.Method.Sig));
methods.Sort((a, b) => String.CompareOrdinal(a.Method.Sig, b.Method.Sig));
return methods;
}
@@ -19,7 +19,6 @@ namespace HybridCLR.Editor
private SerializedProperty _hotUpdateDllCompileOutputRootDir;
private SerializedProperty _externalHotUpdateAssembliyDirs;
private SerializedProperty _strippedAOTDllOutputRootDir;
private SerializedProperty _strippedAOTDllSnapshotDir;
private SerializedProperty _patchAOTAssemblies;
private SerializedProperty _outputLinkFile;
private SerializedProperty _outputAOTGenericReferenceFile;
@@ -47,7 +46,6 @@ namespace HybridCLR.Editor
_hotUpdateDllCompileOutputRootDir = _serializedObject.FindProperty("hotUpdateDllCompileOutputRootDir");
_externalHotUpdateAssembliyDirs = _serializedObject.FindProperty("externalHotUpdateAssembliyDirs");
_strippedAOTDllOutputRootDir = _serializedObject.FindProperty("strippedAOTDllOutputRootDir");
_strippedAOTDllSnapshotDir = _serializedObject.FindProperty("strippedAOTDllSnapshotDir");
_patchAOTAssemblies = _serializedObject.FindProperty("patchAOTAssemblies");
_outputLinkFile = _serializedObject.FindProperty("outputLinkFile");
_outputAOTGenericReferenceFile = _serializedObject.FindProperty("outputAOTGenericReferenceFile");
@@ -136,7 +134,6 @@ namespace HybridCLR.Editor
EditorGUILayout.PropertyField(_hotUpdateDllCompileOutputRootDir);
EditorGUILayout.PropertyField(_externalHotUpdateAssembliyDirs);
EditorGUILayout.PropertyField(_strippedAOTDllOutputRootDir);
EditorGUILayout.PropertyField(_strippedAOTDllSnapshotDir);
EditorGUILayout.PropertyField(_patchAOTAssemblies);
EditorGUILayout.PropertyField(_outputLinkFile);
EditorGUILayout.PropertyField(_outputAOTGenericReferenceFile);
+4 -7
View File
@@ -32,20 +32,17 @@ namespace HybridCLR.Editor
[Header("外部热更新dll搜索路径")]
public string[] externalHotUpdateAssembliyDirs;
[Header("裁减后AOT dll的输出目录")]
public string strippedAOTDllOutputRootDir = "HybridCLRData/AOTDllOutput";
[Header("裁减后AOT dll的备份目录")]
public string strippedAOTDllSnapshotDir = "HybridCLRData/AOTDllSnapshot";
[Header("裁减后AOT dll输出根目录")]
public string strippedAOTDllOutputRootDir = "HybridCLRData/AssembliesPostIl2CppStrip";
[Header("补充元数据AOT dlls")]
public string[] patchAOTAssemblies;
[Header("生成的link.xml路径")]
public string outputLinkFile = "HybridCLRData/Generated/link.xml";
public string outputLinkFile = "HybridCLRGenerate/link.xml";
[Header("自动扫描生成的AOTGenericReferences.cs路径")]
public string outputAOTGenericReferenceFile = "HybridCLRData/Generated/AOTGenericReferences.cs";
public string outputAOTGenericReferenceFile = "HybridCLRGenerate/AOTGenericReferences.cs";
[Header("AOT泛型实例化搜索迭代次数")]
public int maxGenericReferenceIteration = 10;
+7 -7
View File
@@ -6,7 +6,7 @@ public static class MenuProvider
{
[MenuItem("HybridCLR/About HybridCLR", priority = 0)]
public static void OpenAbout() => Application.OpenURL("https://hybridclr.doc.code-philosophy.com/#/README");
public static void OpenAbout() => Application.OpenURL("https://hybridclr.doc.code-philosophy.com/docs/intro");
[MenuItem("HybridCLR/Installer...", priority = 60)]
private static void Open()
@@ -19,18 +19,18 @@ public static class MenuProvider
public static void OpenSettings() => SettingsService.OpenProjectSettings("Project/HybridCLR Settings");
[MenuItem("HybridCLR/Documents/Quick Start")]
public static void OpenQuickStart() => Application.OpenURL("https://hybridclr.doc.code-philosophy.com/#/beginner/quickstart");
public static void OpenQuickStart() => Application.OpenURL("https://hybridclr.doc.code-philosophy.com/docs/beginner/quickstart");
[MenuItem("HybridCLR/Documents/Benchmark")]
public static void OpenBenchmark() => Application.OpenURL("https://hybridclr.doc.code-philosophy.com/#/basic/performance");
[MenuItem("HybridCLR/Documents/Performance")]
public static void OpenPerformance() => Application.OpenURL("https://hybridclr.doc.code-philosophy.com/docs/basic/performance");
[MenuItem("HybridCLR/Documents/FAQ")]
public static void OpenFAQ() => Application.OpenURL("https://hybridclr.doc.code-philosophy.com/#/help/faq");
public static void OpenFAQ() => Application.OpenURL("https://hybridclr.doc.code-philosophy.com/docs/help/faq");
[MenuItem("HybridCLR/Documents/Common Errors")]
public static void OpenCommonErrors() => Application.OpenURL("https://hybridclr.doc.code-philosophy.com/#/help/commonerrors");
public static void OpenCommonErrors() => Application.OpenURL("https://hybridclr.doc.code-philosophy.com/docs/help/commonerrors");
[MenuItem("HybridCLR/Documents/Bug Report")]
public static void OpenBugReport() => Application.OpenURL("https://hybridclr.doc.code-philosophy.com/#/help/issue");
public static void OpenBugReport() => Application.OpenURL("https://hybridclr.doc.code-philosophy.com/docs/help/issue");
}
-5
View File
@@ -55,11 +55,6 @@ namespace HybridCLR.Editor
return $"{AssembliesPostIl2CppStripDir}/{target}";
}
public static string GetAOTAssemblySnapshotDir(BuildTarget target)
{
return $"{HybridCLRSettings.Instance.strippedAOTDllSnapshotDir}/{target}";
}
class AssemblyDefinitionData
{
public string name;
+91 -5
View File
@@ -1,11 +1,97 @@
# hybridclr_unity
- [README 中文](./README_zh.md)
- [README English](./README.md)
# HybridCLR
Unity Package for HybridCLR
## 改动日志
[![license](http://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/focus-creative-games/hybridclr/blob/main/LICENSE)
- v2.3.0 支持从本地目录直接复制hybridclr源码。轻微修复2019版本某些情况下路径过长导致安装失败的问题。
- v2.2.0 支持2020.3.47及2021.3.23
- v2.0.5 Installer使用tag而不是commit id,安装时不必拉取整个branch,大幅缩短安装时间
![logo](https://github.com/focus-creative-games/hybridclr/raw/main/docs/images/logo.jpg)
<br/>
<br/>
HybridCLR is the excellent work of **Code Philosophy** company. We hope to profoundly change the entire industry through our ingenuity and help game teams make better games.
HybridCLR is a **almost perfect** full-platform native c# hot update solution for Unity with complete features, zero cost, high performance, and low memory.
HybridCLR expands the ability of il2cpp, making it change from pure [AOT](https://en.wikipedia.org/wiki/Ahead-of-time_compilation) runtime to 'AOT+Interpreter' hybrid runtime, and then natively supports dynamic loading of assembly , so that the games packaged based on il2cpp backend can be executed not only on the Android platform, but also on IOS, Consoles and other platforms that limit JIT efficiently in **AOT+interpreter** hybrid mode, completely supporting hot updates from the bottom layer.
HybridCLR not only supports the traditional fully interpreted execution mode, but also pioneered [Differential Hybrid Execution](https://hybridclr.doc.code-philosophy.com/en/docs/business/ultimate/differentialhybridexecution) technique. That is, you can add, delete, or modify the AOT dll at will, and intelligently make the changed or newly added classes and functions run in interpreter mode, but the unchanged classes and functions run in AOT mode, so that the running performance of the hot-updated game logic basically reaches the original AOT level.
Welcome to embrace modern native C# hot update technology! ! !
## Documentation
- [Official Documentation](https://hybridclr.doc.code-philosophy.com/en/docs/intro)
- [Quickstart](https://hybridclr.doc.code-philosophy.com/en/docs/beginner/quickstart)
- [Release Log](./RELEASELOG.md)
## Features
- Features complete. A nearly complete implementation of the [ECMA-335 specification](https://www.ecma-international.org/publications-and-standards/standards/ecma-335/), with only a very small number of [unsupported features](https://hybridclr.doc.code-philosophy.com/en/docs/basic/notsupportedfeatures).
- Zero learning and use costs. HybridCLR enhances the pure AOT runtime into a complete runtime, making hot update code work seamlessly with AOT code. The script class and the AOT class are in the same runtime, and you can freely write codes such as inheritance, reflection, and multi-threading (volatile, ThreadStatic, Task, async). No need to write any special code, no code generation, almost unlimited.
- Efficient execution. Implemented an extremely efficient register interpreter, all indicators are significantly better than other hot update schemes. [Performance Test Report](https://hybridclr.doc.code-philosophy.com/en/docs/basic/performance)
- Memory efficient. The classes defined in the hot update script occupy the same memory space as ordinary c# classes, which is far superior to other hot update solutions. [Memory and GC](https://hybridclr.doc.code-philosophy.com/en/docs/basic/memory)
- Due to the perfect support for generics, libraries that are not compatible with il2cpp due to AOT generics issues can now run perfectly under il2cpp
- Support some features not supported by il2cpp, such as __makeref, __reftype, __refvalue directives
- [Differential Hybrid Execution](https://hybridclr.doc.code-philosophy.com/en/docs/business/ultimate/differentialhybridexecution)
## working principle
HybridCLR is inspired by mono's [mixed mode execution](https://www.mono-project.com/news/2017/11/13/mono-interpreter/) technology, and provides additional AOT runtimes such as unity's il2cpp The interpreter module is provided to transform them from pure AOT runtime to "AOT + Interpreter" hybrid operation mode.
![icon](https://github.com/focus-creative-games/hybridclr/raw/main/docs/images/architecture.png)
More specifically, HybridCLR does the following:
- Implemented an efficient metadata (dll) parsing library
- Modified the metadata management module to realize the dynamic registration of metadata
- Implemented a compiler from IL instruction set to custom register instruction set
- Implemented an efficient register interpreter
- Provide a large number of instinct functions to improve the performance of the interpreter
## The difference from other popular c# hot update schemes
HybridCLR is a native c# hot update solution. In layman's terms, il2cpp is equivalent to the aot module of mono, and HybridCLR is equivalent to the interpreter module of mono, and the combination of the two becomes a complete mono. HybridCLR makes il2cpp a full-featured runtime, natively (that is, through System.Reflection.Assembly.Load) supports dynamic loading of dlls, thereby supporting hot updates of the ios platform.
Just because HybridCLR is implemented at the native runtime level, the types of the hot update part and the AOT part of the main project are completely equivalent and seamlessly unified. You can call, inherit, reflect, and multi-thread at will, without generating code or writing adapters.
Other hot update solutions are independent vm, and the relationship with il2cpp is essentially equivalent to the relationship of embedding lua in mono. Therefore, the type system is not uniform. In order to allow the hot update type to inherit some AOT types, an adapter needs to be written, and the type in the interpreter cannot be recognized by the type system of the main project. Incomplete features, troublesome development, and low operating efficiency.
## Compatibility
- Support 2019.4.x, 2020.3.x, 2021.3.x, 2022.3.x, 2023.2.x series LTS versions
- Supports all platforms supported by il2cpp. At present, it has fully supported PC (Win32 and Win64), macOS (x86, x64, Arm64), Android (armv7, armv8), iOS (64bit), WebGL, **WeChat applet platform**, and the remaining platforms are yet to be tested.
- Tested a large number of common game libraries, and did not find a library that is natively compatible with il2cpp but incompatible after using HybridCLR. As long as the library can work under the il2cpp backend, it can work normally under HybridCLR. Even those libraries that are incompatible with il2cpp due to AOT issues can now run normally because of HybridCLR's ability to expand il2cpp.
## Stability Status
At present, **extremely stable** official versions 1.x, 2.x, and 3.x have been released, which are sufficient to meet the stability requirements of large and medium-sized commercial projects. Since the first game was launched on June 7, 2022, only one small bug occurred in the online project, and it was quickly fixed within a few hours.
At present, at least thousands of commercial game projects have completed access, and hundreds of them have been launched on both ends. The online projects include games such as MMORPG, heavy card, and heavy tower defense.
Most leading companies such as Tencent, NetEase, Baidu, funplus, Perfect, Stacked Paper, and Byte have already connected to multiple projects and will soon (or already) go online.
## Support and Contact
- Official 1 group: 651188171 (full)
- Novice group 1: 428404198 (full)
- Novice group 2: **680274677 (recommended)**
- QQ reward mutual aid group: 762953653. Offer a reward for asking questions and solving problems quickly.
- discord channel [https://discord.gg/BATfNfJnm2](https://discord.gg/BATfNfJnm2)
- Business cooperation email: business@code-philosophy.com
- [Commercial support](https://hybridclr.doc.code-philosophy.com/en/docs/business/intro)
## About the author
**walon** : Founder of **Code Philosophy (code philosophy)**
Graduated from the Department of Physics of Tsinghua University, won the CMO gold medal in 2006, a member of the National Mathematical Olympiad Training Team, and was recommended to Tsinghua University for basic courses. Focus on game technology, good at developing architecture and basic technical facilities.
## license
HybridCLR is licensed under the [MIT](https://github.com/focus-creative-games/hybridclr/blob/main/LICENSE) license
+93
View File
@@ -0,0 +1,93 @@
- [README 中文](./README_zh.md)
- [README English](./README.md)
# HybridCLR
[![license](http://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/focus-creative-games/hybridclr/blob/main/LICENSE)
![logo](https://github.com/focus-creative-games/hybridclr/raw/main/docs/images/logo.jpg)
<br/>
<br/>
HybridCLR是 **Code Philosophy(代码哲学)** 公司的代表作品,我们希望通过我们的聪明才智深刻地改变整个行业,帮助游戏团队制作出更优秀的游戏。
HybridCLR是一个**特性完整、零成本、高性能、低内存**的**近乎完美**的Unity全平台原生c#热更方案。
HybridCLR扩充了il2cpp的代码,使它由纯[AOT](https://en.wikipedia.org/wiki/Ahead-of-time_compilation) runtime变成‘AOT+Interpreter’ 混合runtime,进而原生支持动态加载assembly,使得基于il2cpp backend打包的游戏不仅能在Android平台,也能在IOS、Consoles等限制了JIT的平台上高效地以**AOT+interpreter**混合模式执行,从底层彻底支持了热更新。
HybridCLR不仅支持传统的全解释执行模式,还开创性地实现了 [Differential Hybrid Execution(差分混合执行技)](https://hybridclr.doc.code-philosophy.com/docs/business/ultimate/differentialhybridexecution) 差分混合执行技术。即可以对AOT dll任意增删改,会智能地让变化或者新增的类和函数以interpreter模式运行,但未改动的类和函数以AOT方式运行,让热更新的游戏逻辑的运行性能基本达到原生AOT的水平。
欢迎拥抱现代原生C#热更新技术 !!!
## 文档
- [官方文档](https://hybridclr.doc.code-philosophy.com/docs/intro)
- [快速上手](https://hybridclr.doc.code-philosophy.com/docs/beginner/quickstart)
- [发布日志](./RELEASELOG.md)
## 特性
- 特性完整。 近乎完整实现了[ECMA-335规范](https://www.ecma-international.org/publications-and-standards/standards/ecma-335/),只有极少量的[不支持的特性](https://hybridclr.doc.code-philosophy.com/docs/basic/notsupportedfeatures)。
- 零学习和使用成本。 HybridCLR将纯AOT runtime增强为完整的runtime,使得热更新代码与AOT代码无缝工作。脚本类与AOT类在同一个运行时内,可以随意写继承、反射、多线程(volatile、ThreadStatic、Task、async)之类的代码。不需要额外写任何特殊代码、没有代码生成,几乎没有限制。
- 执行高效。实现了一个极其高效的寄存器解释器,所有指标都大幅优于其他热更新方案。[性能测试报告](https://hybridclr.doc.code-philosophy.com/docs/basic/performance)
- 内存高效。 热更新脚本中定义的类跟普通c#类占用一样的内存空间,远优于其他热更新方案。[内存与GC](https://hybridclr.doc.code-philosophy.com/docs/basic/memory)
- 由于对泛型的完美支持,使得因为AOT泛型问题跟il2cpp不兼容的库现在能够完美地在il2cpp下运行
- 支持一些il2cpp不支持的特性,如__makeref、 __reftype、__refvalue指令
- [Differential Hybrid Execution(差分混合执行技)](https://hybridclr.doc.code-philosophy.com/docs/business/ultimate/differentialhybridexecution)
## 工作原理
HybridCLR从mono的 [mixed mode execution](https://www.mono-project.com/news/2017/11/13/mono-interpreter/) 技术中得到启发,为unity的il2cpp之类的AOT runtime额外提供了interpreter模块,将它们由纯AOT运行时改造为"AOT + Interpreter"混合运行方式。
![icon](https://github.com/focus-creative-games/hybridclr/raw/main/docs/images/architecture.png)
更具体地说,HybridCLR做了以下几点工作:
- 实现了一个高效的元数据(dll)解析库
- 改造了元数据管理模块,实现了元数据的动态注册
- 实现了一个IL指令集到自定义的寄存器指令集的compiler
- 实现了一个高效的寄存器解释器
- 额外提供大量的instinct函数,提升解释器性能
## 与其他流行的c#热更新方案的区别
HybridCLR是原生的c#热更新方案。通俗地说,il2cpp相当于mono的aot模块,HybridCLR相当于mono的interpreter模块,两者合一成为完整mono。HybridCLR使得il2cpp变成一个全功能的runtime,原生(即通过System.Reflection.Assembly.Load)支持动态加载dll,从而支持ios平台的热更新。
正因为HybridCLR是原生runtime级别实现,热更新部分的类型与主工程AOT部分类型是完全等价并且无缝统一的。可以随意调用、继承、反射、多线程,不需要生成代码或者写适配器。
其他热更新方案则是独立vm,与il2cpp的关系本质上相当于mono中嵌入lua的关系。因此类型系统不统一,为了让热更新类型能够继承AOT部分类型,需要写适配器,并且解释器中的类型不能为主工程的类型系统所识别。特性不完整、开发麻烦、运行效率低下。
## 兼容性
- 支持2019.4.x、2020.3.x、2021.3.x、2022.3.x、2022.2.x 系列LTS版本
- 支持所有il2cpp支持的平台。目前已完善支持 PC(Win32和Win64)、macOS(x86、x64、Arm64)、Android(armv7、armv8)、iOS(64bit)、WebGL、**微信小程序平台**,剩余平台有待测试。
- 测试过大量游戏常见库,未发现跟il2cpp原生兼容但使用HybridCLR后不兼容性的库。只要能在il2cpp backend下工作的库都可以在HybridCLR下正常工作。甚至那些与il2cpp因为AOT问题不兼容的库,现在因为HybridCLR对il2cpp的能力扩充,反而可以正常运行了。
## 稳定性状况
当前已经发布了**极其稳定**的1.x、2.x、3.x正式版本,足以满足大中型商业项目的稳定性要求。自2022.6.7上线第一个游戏起,线上项目中只发生过一起小bug,并且迅速地在几个小时内被修复。
目前至少有上千个商业游戏项目完成接入,其中有几百款已经双端上线,上线的项目中包括MMORPG、重度卡牌、重度塔防之类的游戏。
大多数头部公司如腾讯、网易、百度、funplus、完美、叠纸、字节都已经接入多个项目并且很快要(或者已经)上线。
## 支持与联系
- 官方1群:651188171(满)
- 新手1群:428404198(满)
- 新手2群:**680274677(推荐)**
- QQ悬赏互助群:762953653。悬赏提问,快速解决问题。
- discord频道 https://discord.gg/BATfNfJnm2
- 商业合作邮箱: business@code-philosophy.com
- [商业化支持](https://hybridclr.doc.code-philosophy.com/docs/business/intro)
## 关于作者
**walon** :**Code Philosophy(代码哲学)** 创始人
毕业于清华大学物理系,2006年CMO金牌,奥数国家集训队成员,保送清华基科班。专注于游戏技术,擅长开发架构和基础技术设施。
## license
HybridCLR is licensed under the [MIT](https://github.com/focus-creative-games/hybridclr/blob/main/LICENSE) license
@@ -1,7 +1,6 @@
fileFormatVersion: 2
guid: 59ab7ccacd9a9944bb9456da235d6760
folderAsset: yes
DefaultImporter:
guid: 52688f4469ff9454e8c3d8aaf045d9f4
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
+182 -28
View File
@@ -1,66 +1,220 @@
# 发布日志
## 3.4.3
### Runtime
- [fix] 修复CalcClassNotStaticFields计算泛型类型的泛型父类时未inflate的bug
- [fix] 修复未处理ResolveField获得的Field为nullptr时情形导致崩溃的bug
- [fix] 修复Transform中未析构pendingFlows造成内存泄露的bug
- [opt] TemporaryMemoryArena默认内存块大小由1M调整8K
- [fix] 修复计算interface成员函数slot时未考虑到static之类函数的bug
- [fix] 修复2022版本ExplicitLayout未设置layout.alignment,导致计算出size==0的bug
- [fix] ldobj当T为byte之类size<4的类型时,未将数据展开为int的bug
- [fix] 修复未正确处理AOT及interpreter interface中显式实现父接口函数的bug
## 3.4.2
发布日期 2023.08.14。
### Runtime
- [fix] 修复RawImage::LoadTables读取_4byteGUIDIndex的bug
- [version] 支持2022.3.7版本
- [version] 支持2021.3.29版本
### Editor
- [fix] 修复计算AOTGenericReference未考虑到泛型调用泛型的情况,导致少计算了泛型及补充元数据
## 3.4.1
发布日期 2023.07.31。
### Runtime
- [fix] 修复 InitializeRuntimeMetadata的内存可见性问题
- [fix] 修复CustomAttribute未正确处理父类NamedArg导致崩溃的bug
- [opt] 优化Transfrom Instinct指令的代码,从HashMap中快速查找而不是挨个匹配
### Editor
- [fix] 修复FilterHotFixAssemblies只对比程序集名尾部,导致有AOT的尾部与某个热更新程序集匹配时意外被过滤的bug
- [change] 检查Settings中热更新程序集列表配置中程序集名不能为空
## 3.4.0
发布日期 2023.07.17。
### Runtime
- [version] 支持2021.3.28和2022.3.4版本
- [opt] 删除MachineState::InitEvalStack分配_StackBase后不必要的memset
- [fix] 修复Exception机制的bug
- [fix] 修复CustomAttribute不支持Type[]类型参数的bug
- [fix] 修复不支持new string(xxx)用法的问题
- [refactor] 重构VTableSetup实现
- [fix] 修复未计算子interface中显式实现父interface的函数的bug
- [opt] Lazy初始化CustomAttributeData,而不是加载时全部初始化,明显减少Assembly.Load时间
- [fix] 修复2022 当new byte\[]{a,b,c...}方式初始化较长的byte[]数据时,返回错误数据的bug
### Editor
- [fix] 修复计算桥接函数未考虑到泛型类的成员函数中可能包含的Native2Managed调用
- [change] link.xml及AOTGenericReferences.cs默认输出路径改为HybridCLRGenerate,避免与顶层HybridCLRData混淆
- [fix] 修复Win下生成的Lump文件中include路径以\为目录分隔符导致同步到Mac后找不到路径的bug
- [refactor] 重构Installer
## 3.3.0
发布日期 2023.07.03。
### Runtime
- [fix] 修复localloc分配的内存未释放的bug
- [change] MachineState改用RegisterRoot的方式注册执行栈,避免GC时扫描整个堆栈
- [opt] 优化Managed2NativeCallByReflectionInvoke性能,提前计算好传参方式
- [refactor] 重构ConvertInvokeArgs
### Editor
- [fix] 修复2020-2021编译libil2cpp.a未包含brotli相关代码文件导致出现编译错误的bug
- [fix] 修复从导出xcode项目包含绝对路径导致传送到其他机器上编译时找不到路径的bug
- [fix] 解决Generate LinkXml、 MethodBridge、AOTGenericReference、ReversePInvokeWrap 生成不稳定的问题
- [fix] 修复使用不兼容版本打开Installer时出现异常的bug
- [change] 禁用hybridclr后打包ios时不再修改导出的xcode工程
## 3.2.1
### Runtime
- [fix] 修复il2cpp TypeNameParser未将类型名中转义字符'\'去掉,导致找不到嵌套子类型的bug
### Editor
- [new] Installer界面新增显示package版本
- [new] CompileDll新增MacOS、Linux、WebGL目标
- [fix] 修复重构文档站后的帮助文档的链接错误
- [change] 为Anaylizer加上using 限定,解决某些情况下与项目的类型同名而产生编译冲突的问题
## 3.2.0
### Runtime
- [fix] 修复未在PlaceHolder中的Assembly加载时,如果由于不在Assembly列表,也没有任何解释器栈,导致Class::resolve_parse_info_internal查找不到类型的bug
- [fix] 修复读取CustomAttribute System.Type类型数据崩溃的bug
### Editor
- [new] 支持直接从源码打包iOS,不再需要单独编译libil2cpp.a
- [opt] 优化版本不兼容时错误提示,不再抛出异常,而是显示"与当前版本不兼容"
## 3.1.1
### Runtime
- [fix] 修复2021及更高版本,InterpreterModule::Managed2NativeCallByReflectionInvoke调用值类型成员函数时,对this指针多余this=this-1操作。
- [fix] 修复解析CustomAttribute中Enum[]类型字段的bug
- [fix] 修复2021及更高版本反射调用值类型 close Delegate的Invoke函数时未修复target指针的bug
- [new] 新增对增量式GC宏的检查,避免build.gradle中意外开启增量式GC引发的极其隐蔽的问题
### Editor
- [fix] 修复 Win32、Android32、WebGL平台的编译错误
- [fix] 修复计算桥接函数时未考虑到补充元数据泛型实例化会导致访问到一些非公开的函数的情况,导致少生成一些必要的桥接函数
- [opt] 生成AOTGenericReferences时,补充元数据assembly列表由注释改成List<string>列表,方便在代码中直接使用。
- [change] CheckSettings中不再自动设置Api Compatible Level
## 3.1.0
### Runtime
- [rollback] 还原对Unity 2020.3.x支持
- [fix] 修复 WebGL平台ABI的bug
### Editor
- [rollback] 还原对Unity 2020.3.x支持
## 3.0.3
### Runtime
- [fix] 修复Enum::GetValues返回值不正确的bug
## 3.0.2
### Runtime
- [fix] 修复Memory Profiler中创建内存快照时崩溃的bug
### Editor
- [remove] 移除 `HybridCLR/CreateAOTDllSnapshot`菜单
## 3.0.1
### 改动
### Runtime
- 支持2022.3.0
- [new] 支持2022.3.0
## 3.0.0
### 修复
### Runtime
- 修复不支持访问CustomData字段及值的bug
- [fix] 修复不支持访问CustomData字段及值的bug
- [remove] 移除对2019及2020版本支持
### 改动
### Editor
- 包名更改为com.code-philosophy.hybridclr
- 移除对2019及2020版本支持
- 移除UnityFS插件
- 移除Zip插件
- HybridCLR菜单位置调整
## 2.4.2
### 改动
### Runtime
- 支持 2020.3.48,最后一个2020LTS版本
- 支持 2021.3.25
- hybridclr 升级到 v2.3.1
- il2cpp_plus 升级到 v2020-2.2.1 、v2021-2.2.1
- [version] 支持 2020.3.48,最后一个2020LTS版本
- [version] 支持 2021.3.25
## 2.4.1
### 修复
### Runtime
- 修复遗漏 RELEASELOG.md.meta 文件的问题
### Editor
- [fix] 修复遗漏 RELEASELOG.md.meta 文件的问题
## 2.4.0
### 改动
### Runtime
- CheckSettings中检查ScriptingBackend及ApiCompatibleLevel,切换为正确的值
- hybridclr 升级到v2.3.0版本
- il2cpp_plus 升级到v2019-2.2.0、v2020-2.2.0、v2021-2.2.0版本
### Editor
### 修复
- 新增 MsvcStdextWorkaround.cs 解决2020 vs下stdext编译错误的问题
- 修复当struct只包含一个float或double字段时,在arm64上计算桥接函数签名错误的bug
- [new] CheckSettings中检查ScriptingBackend及ApiCompatibleLevel,切换为正确的值
- [new] 新增 MsvcStdextWorkaround.cs 解决2020 vs下stdext编译错误的问题
- [fix] 修复当struct只包含一个float或double字段时,在arm64上计算桥接函数签名错误的bug
## 2.3.1
### 修复
- 修复本地复制libil2cpp却仍然从仓库下载安装的bug
### Runtime
### Editor
- [fix] 修复本地复制libil2cpp却仍然从仓库下载安装的bug
## 2.3.0
### 改动
### Runtime
- Installer支持从本地目录复制改造后的libil2cpp
### Editor
### 修复
- 修复2019版本MonoBleedingEdge的子目录中包含了过长路径的文件导致Installer复制文件出错的问题
- [new] Installer支持从本地目录复制改造后的libil2cpp
- [fix] 修复2019版本MonoBleedingEdge的子目录中包含了过长路径的文件导致Installer复制文件出错的问题
+37 -3
View File
@@ -42,36 +42,70 @@ namespace HybridCLR
/// <param name="dllBytes"></param>
/// <param name="dllSize"></param>
/// <returns></returns>
#if UNITY_EDITOR
public static unsafe int LoadMetadataForAOTAssembly(byte* dllBytes, int dllSize, int mode)
{
return 0;
}
#else
[DllImport(dllName, EntryPoint = "RuntimeApi_LoadMetadataForAOTAssembly")]
public static extern unsafe int LoadMetadataForAOTAssembly(byte* dllBytes, int dllSize, int mode);
#endif
/// <summary>
/// 获取解释器线程栈的最大StackObject个数(size*8 为最终占用的内存大小)
/// </summary>
/// <returns></returns>
#if UNITY_EDITOR
public static int GetInterpreterThreadObjectStackSize()
{
return 0;
}
#else
[DllImport(dllName, EntryPoint = "RuntimeApi_GetInterpreterThreadObjectStackSize")]
public static extern int GetInterpreterThreadObjectStackSize();
#endif
/// <summary>
/// 设置解释器线程栈的最大StackObject个数(size*8 为最终占用的内存大小)
/// </summary>
/// <param name="size"></param>
#if UNITY_EDITOR
public static void SetInterpreterThreadObjectStackSize(int size)
{
}
#else
[DllImport(dllName, EntryPoint = "RuntimeApi_SetInterpreterThreadObjectStackSize")]
public static extern void SetInterpreterThreadObjectStackSize(int size);
#endif
/// <summary>
/// 获取解释器线程函数帧数量(sizeof(InterpreterFrame)*size 为最终占用的内存大小)
/// </summary>
/// <returns></returns>
#if UNITY_EDITOR
public static int GetInterpreterThreadFrameStackSize()
{
return 0;
}
#else
[DllImport(dllName, EntryPoint = "RuntimeApi_GetInterpreterThreadFrameStackSize")]
public static extern int GetInterpreterThreadFrameStackSize();
#endif
/// <summary>
/// 设置解释器线程函数帧数量(sizeof(InterpreterFrame)*size 为最终占用的内存大小)
/// </summary>
/// <param name="size"></param>
#if UNITY_EDITOR
public static void SetInterpreterThreadFrameStackSize(int size)
{
}
#else
[DllImport(dllName, EntryPoint = "RuntimeApi_SetInterpreterThreadFrameStackSize")]
public static extern void SetInterpreterThreadFrameStackSize(int size);
#endif
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "com.code-philosophy.hybridclr",
"version": "3.0.1",
"version": "3.4.3",
"displayName": "HybridCLR",
"description": "HybridCLR is a fully featured, zero-cost, high-performance, low-memory solution for Unity's all-platform native c# hotupdate.",
"category": "Runtime",