mirror of
https://github.com/focus-creative-games/hybridclr_unity.git
synced 2026-11-20 07:22:39 +08:00
Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 811b4ecf60 |
+1
-1
@@ -1,5 +1,5 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 52688f4469ff9454e8c3d8aaf045d9f4
|
||||
guid: 22f11da50eb60c245b40028549937af6
|
||||
TextScriptImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
+2
-3
@@ -1,7 +1,6 @@
|
||||
fileFormatVersion: 2
|
||||
guid: e60a8b17b0e23a94a8ae875716208030
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
guid: 94322e93a1f61b340bdc1d5042dab659
|
||||
TextScriptImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,20 @@
|
||||
#include <codegen/il2cpp-codegen-metadata.h>
|
||||
#include "vm/ClassInlines.h"
|
||||
#include "vm/Object.h"
|
||||
#include "vm/Class.h"
|
||||
|
||||
#include "../metadata/MetadataModule.h"
|
||||
#include "../metadata/MetadataUtil.h"
|
||||
|
||||
#include "../interpreter/MethodBridge.h"
|
||||
#include "../interpreter/Interpreter.h"
|
||||
#include "../interpreter/MemoryUtil.h"
|
||||
#include "../interpreter/InstrinctDef.h"
|
||||
|
||||
using namespace hybridclr::interpreter;
|
||||
|
||||
#if {PLATFORM_ABI}
|
||||
//!!!{{CODE
|
||||
|
||||
//!!!}}CODE
|
||||
#endif
|
||||
@@ -0,0 +1,32 @@
|
||||
#include "../metadata/ReversePInvokeMethodStub.h"
|
||||
#include "../metadata/MetadataModule.h"
|
||||
|
||||
namespace hybridclr
|
||||
{
|
||||
namespace metadata
|
||||
{
|
||||
#if {PLATFORM_ABI}
|
||||
|
||||
//!!!{{CODE
|
||||
|
||||
void __ReversePInvokeMethod_0(void* xState)
|
||||
{
|
||||
CallLuaFunction(xState, 0);
|
||||
}
|
||||
|
||||
void __ReversePInvokeMethod_1(void* xState)
|
||||
{
|
||||
CallLuaFunction(xState, 1);
|
||||
}
|
||||
|
||||
Il2CppMethodPointer s_ReversePInvokeMethodStub[]
|
||||
{
|
||||
(Il2CppMethodPointer)__ReversePInvokeMethod_0,
|
||||
(Il2CppMethodPointer)__ReversePInvokeMethod_1,
|
||||
nullptr,
|
||||
};
|
||||
|
||||
//!!!}}CODE
|
||||
#endif
|
||||
}
|
||||
}
|
||||
@@ -2,28 +2,18 @@
|
||||
"versions": [
|
||||
{
|
||||
"unity_version":"2019",
|
||||
"hybridclr" : { "branch":"v5.3.0"},
|
||||
"il2cpp_plus": { "branch":"v2019-5.3.0"}
|
||||
"hybridclr" : { "branch":"v2.3.1"},
|
||||
"il2cpp_plus": { "branch":"v2019-2.2.0"}
|
||||
},
|
||||
{
|
||||
"unity_version":"2020",
|
||||
"hybridclr" : { "branch":"v5.3.0"},
|
||||
"il2cpp_plus": { "branch":"v2020-5.3.0"}
|
||||
"hybridclr" : { "branch":"v2.3.1"},
|
||||
"il2cpp_plus": { "branch":"v2020-2.2.1"}
|
||||
},
|
||||
{
|
||||
"unity_version":"2021",
|
||||
"hybridclr" : { "branch":"v5.3.0"},
|
||||
"il2cpp_plus": { "branch":"v2021-5.3.0"}
|
||||
},
|
||||
{
|
||||
"unity_version":"2022",
|
||||
"hybridclr" : { "branch":"v5.3.0"},
|
||||
"il2cpp_plus": { "branch":"v2022-5.3.0"}
|
||||
},
|
||||
{
|
||||
"unity_version":"2022-tuanjie",
|
||||
"hybridclr" : { "branch":"v5.3.0"},
|
||||
"il2cpp_plus": { "branch":"v2022-tuanjie-5.3.0"}
|
||||
"hybridclr" : { "branch":"v2.3.1"},
|
||||
"il2cpp_plus": { "branch":"v2021-2.2.1"}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
# 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"
|
||||
)
|
||||
@@ -0,0 +1,19 @@
|
||||
#!/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
@@ -0,0 +1,47 @@
|
||||
# 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})
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
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 " "
|
||||
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
# 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})
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 8f2dd29d56a640d4ebd1c2fd374b7638
|
||||
guid: 4455f7304f8678f408dd6cf21734f55e
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
|
||||
@@ -12,7 +12,7 @@ using System.IO;
|
||||
|
||||
namespace HybridCLR.MonoHook
|
||||
{
|
||||
#if UNITY_2021_1_OR_NEWER
|
||||
#if UNITY_2021_1_OR_NEWER && UNITY_IOS
|
||||
[InitializeOnLoad]
|
||||
public class CopyStrippedAOTAssembliesHook
|
||||
{
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Reflection;
|
||||
using UnityEngine;
|
||||
using UnityEditor;
|
||||
using System.Runtime.CompilerServices;
|
||||
using MonoHook;
|
||||
using HybridCLR.Editor.BuildProcessors;
|
||||
using System.IO;
|
||||
|
||||
namespace HybridCLR.MonoHook
|
||||
{
|
||||
#if UNITY_2022
|
||||
[InitializeOnLoad]
|
||||
public class GetIl2CppFolderHook
|
||||
{
|
||||
private static MethodHook _hook;
|
||||
|
||||
static GetIl2CppFolderHook()
|
||||
{
|
||||
if (_hook == null)
|
||||
{
|
||||
Type type = typeof(UnityEditor.EditorApplication).Assembly.GetType("UnityEditorInternal.IL2CPPUtils");
|
||||
MethodInfo miTarget = type.GetMethod("GetIl2CppFolder", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public, null,
|
||||
new Type[] { typeof(bool).MakeByRefType() }, null);
|
||||
|
||||
MethodInfo miReplacement = new StripAssembliesDel(OverrideMethod).Method;
|
||||
MethodInfo miProxy = new StripAssembliesDel(PlaceHolderMethod).Method;
|
||||
|
||||
_hook = new MethodHook(miTarget, miReplacement, miProxy);
|
||||
_hook.Install();
|
||||
}
|
||||
}
|
||||
|
||||
private delegate string StripAssembliesDel(out bool isDevelopmentLocation);
|
||||
|
||||
private static string OverrideMethod(out bool isDevelopmentLocation)
|
||||
{
|
||||
//Debug.Log("[GetIl2CppFolderHook] OverrideMethod");
|
||||
string result = PlaceHolderMethod(out isDevelopmentLocation);
|
||||
isDevelopmentLocation = false;
|
||||
return result;
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.NoOptimization)]
|
||||
private static string PlaceHolderMethod(out bool isDevelopmentLocation)
|
||||
{
|
||||
Debug.LogError("[GetIl2CppFolderHook] PlaceHolderMethod");
|
||||
isDevelopmentLocation = false;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -12,7 +12,7 @@ using System.IO;
|
||||
|
||||
namespace HybridCLR.MonoHook
|
||||
{
|
||||
#if (UNITY_2021_1_OR_NEWER && UNITY_WEBGL) || TUANJIE_2022_3_OR_NEWER
|
||||
#if UNITY_2021_1_OR_NEWER && UNITY_WEBGL
|
||||
[InitializeOnLoad]
|
||||
public class PatchScriptingAssembliesJsonHook
|
||||
{
|
||||
@@ -36,12 +36,6 @@ namespace HybridCLR.MonoHook
|
||||
private static string BuildMainWindowTitle()
|
||||
{
|
||||
string tempJsonPath = $"{Application.dataPath}/../Library/PlayerDataCache/WebGL/Data/ScriptingAssemblies.json";
|
||||
#if TUANJIE_2022_3_OR_NEWER
|
||||
if (EditorUserBuildSettings.activeBuildTarget == BuildTarget.WeixinMiniGame)
|
||||
{
|
||||
tempJsonPath = $"{Application.dataPath}/../Library/PlayerDataCache/WeixinMiniGame/Data/ScriptingAssemblies.json";
|
||||
}
|
||||
#endif
|
||||
if (File.Exists(tempJsonPath))
|
||||
{
|
||||
var patcher = new PatchScriptingAssemblyList();
|
||||
|
||||
@@ -14,6 +14,20 @@ namespace HybridCLR.Editor.ABI
|
||||
|
||||
public int Index { get; set; }
|
||||
|
||||
//public bool IsNative2ManagedByAddress => Type.PorType >= ParamOrReturnType.STRUCT_NOT_PASS_AS_VALUE;
|
||||
public bool IsPassToManagedByAddress => Type.GetParamSlotNum() > 1;
|
||||
|
||||
public bool IsPassToNativeByAddress => Type.PorType == ParamOrReturnType.STRUCTURE_AS_REF_PARAM;
|
||||
|
||||
public string Native2ManagedParamValue(PlatformABI canv)
|
||||
{
|
||||
return IsPassToManagedByAddress ? $"(uint64_t)&__arg{Index}" : $"*(uint64_t*)&__arg{Index}";
|
||||
}
|
||||
|
||||
public string Managed2NativeParamValue(PlatformABI canv)
|
||||
{
|
||||
return IsPassToNativeByAddress ? $"(uint64_t)(localVarBase+argVarIndexs[{Index}])" : $"*({Type.GetTypeName()}*)(localVarBase+argVarIndexs[{Index}])";
|
||||
}
|
||||
}
|
||||
|
||||
public class ReturnInfo
|
||||
@@ -22,6 +36,11 @@ namespace HybridCLR.Editor.ABI
|
||||
|
||||
public bool IsVoid => Type.PorType == ParamOrReturnType.VOID;
|
||||
|
||||
public int GetParamSlotNum(PlatformABI canv)
|
||||
{
|
||||
return Type.GetParamSlotNum();
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return Type.GetTypeName();
|
||||
|
||||
@@ -19,9 +19,25 @@ namespace HybridCLR.Editor.ABI
|
||||
U8,
|
||||
R4,
|
||||
R8,
|
||||
I,
|
||||
U,
|
||||
TYPEDBYREF,
|
||||
STRUCT,
|
||||
ARM64_HFA_FLOAT_2,
|
||||
VALUE_TYPE_SIZE_LESS_EQUAL_8,
|
||||
I16, // 8 < size <= 16
|
||||
STRUCT_NOT_PASS_AS_VALUE, // struct pass not as value
|
||||
STRUCTURE_AS_REF_PARAM, // size > 16
|
||||
ARM64_HFA_FLOAT_3,
|
||||
ARM64_HFA_FLOAT_4,
|
||||
ARM64_HFA_DOUBLE_2,
|
||||
ARM64_HFA_DOUBLE_3,
|
||||
ARM64_HFA_DOUBLE_4,
|
||||
ARM64_HVA_8,
|
||||
ARM64_HVA_16,
|
||||
STRUCTURE_ALIGN1, // size > 16
|
||||
STRUCTURE_ALIGN2,
|
||||
STRUCTURE_ALIGN4,
|
||||
STRUCTURE_ALIGN8,
|
||||
SPECIAL_STRUCTURE_ALIGN1,
|
||||
SPECIAL_STRUCTURE_ALIGN2,
|
||||
SPECIAL_STRUCTURE_ALIGN4,
|
||||
SPECIAL_STRUCTURE_ALIGN8,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
using dnlib.DotNet;
|
||||
using HybridCLR.Editor.Meta;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace HybridCLR.Editor.ABI
|
||||
{
|
||||
public class HFATypeInfo
|
||||
{
|
||||
public TypeSig Type { get; set; }
|
||||
|
||||
public int Count { get; set; }
|
||||
}
|
||||
|
||||
public class TypeCreatorArm64 : TypeCreatorBase
|
||||
{
|
||||
public override bool IsArch32 => false;
|
||||
|
||||
protected override TypeInfo OptimizeSigType(TypeInfo type, bool returnType)
|
||||
{
|
||||
if (!type.IsGeneralValueType)
|
||||
{
|
||||
return type;
|
||||
}
|
||||
int typeSize = type.Size;
|
||||
if (typeSize <= 8)
|
||||
{
|
||||
return TypeInfo.s_i8;
|
||||
}
|
||||
if (typeSize <= 16)
|
||||
{
|
||||
return TypeInfo.s_i16;
|
||||
}
|
||||
if (returnType)
|
||||
{
|
||||
return type.PorType != ParamOrReturnType.STRUCTURE_ALIGN1 ? new TypeInfo(ParamOrReturnType.STRUCTURE_ALIGN1, typeSize) : type;
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 0b1df5760b488fa43a68843c46fda63a
|
||||
guid: a22846b73022cb2458d1c40549ab6877
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
@@ -9,21 +9,39 @@ using UnityEngine;
|
||||
|
||||
namespace HybridCLR.Editor.ABI
|
||||
{
|
||||
public class TypeCreator
|
||||
public abstract class TypeCreatorBase
|
||||
{
|
||||
public abstract bool IsArch32 { get; }
|
||||
|
||||
public TypeInfo GetNativeIntTypeInfo() => IsArch32 ? TypeInfo.s_i4 : TypeInfo.s_i8;
|
||||
|
||||
public ValueTypeSizeAligmentCalculator Calculator => IsArch32 ? ValueTypeSizeAligmentCalculator.Caculator32 : ValueTypeSizeAligmentCalculator.Caculator64;
|
||||
|
||||
|
||||
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);
|
||||
|
||||
private int _nextStructId = 0;
|
||||
public (int Size, int Aligment) ComputeSizeAndAligment(TypeSig t)
|
||||
{
|
||||
if (_typeSizeCache.TryGetValue(t, out var sizeAndAligment))
|
||||
{
|
||||
return sizeAndAligment;
|
||||
}
|
||||
sizeAndAligment = Calculator.SizeAndAligmentOf(t);
|
||||
_typeSizeCache.Add(t, sizeAndAligment);
|
||||
return sizeAndAligment;
|
||||
}
|
||||
|
||||
public TypeInfo CreateTypeInfo(TypeSig type)
|
||||
{
|
||||
type = type.RemovePinnedAndModifiers();
|
||||
if (!_typeInfoCache.TryGetValue(type, out var typeInfo))
|
||||
{
|
||||
typeInfo = CreateTypeInfo0(type);
|
||||
_typeInfoCache.Add(type, typeInfo);
|
||||
}
|
||||
return typeInfo;
|
||||
return new TypeInfo(typeInfo.PorType, typeInfo.Size);
|
||||
}
|
||||
|
||||
TypeInfo CreateTypeInfo0(TypeSig type)
|
||||
@@ -31,7 +49,7 @@ namespace HybridCLR.Editor.ABI
|
||||
type = type.RemovePinnedAndModifiers();
|
||||
if (type.IsByRef)
|
||||
{
|
||||
return TypeInfo.s_u;
|
||||
return GetNativeIntTypeInfo();
|
||||
}
|
||||
switch (type.ElementType)
|
||||
{
|
||||
@@ -48,8 +66,8 @@ namespace HybridCLR.Editor.ABI
|
||||
case ElementType.U8: return TypeInfo.s_u8;
|
||||
case ElementType.R4: return TypeInfo.s_r4;
|
||||
case ElementType.R8: return TypeInfo.s_r8;
|
||||
case ElementType.I: return TypeInfo.s_i;
|
||||
case ElementType.U:
|
||||
case ElementType.U: return IsArch32 ? TypeInfo.s_u4 : TypeInfo.s_u8;
|
||||
case ElementType.I:
|
||||
case ElementType.String:
|
||||
case ElementType.Ptr:
|
||||
case ElementType.ByRef:
|
||||
@@ -61,14 +79,14 @@ namespace HybridCLR.Editor.ABI
|
||||
case ElementType.Module:
|
||||
case ElementType.Var:
|
||||
case ElementType.MVar:
|
||||
return TypeInfo.s_u;
|
||||
case ElementType.TypedByRef: return TypeInfo.s_typedByRef;
|
||||
return GetNativeIntTypeInfo();
|
||||
case ElementType.TypedByRef: return CreateValueType(type);
|
||||
case ElementType.ValueType:
|
||||
{
|
||||
TypeDef typeDef = type.ToTypeDefOrRef().ResolveTypeDef();
|
||||
if (typeDef == null)
|
||||
{
|
||||
throw new Exception($"type:{type} definition could not be found. Please try `HybridCLR/Genergate/LinkXml`, then Build once to generate the AOT dll, and then regenerate the bridge function");
|
||||
throw new Exception($"type:{type} 未能找到定义。请尝试 `HybridCLR/Genergate/LinkXml`,然后Build一次生成AOT dll,再重新生成桥接函数");
|
||||
}
|
||||
if (typeDef.IsEnum)
|
||||
{
|
||||
@@ -81,7 +99,7 @@ namespace HybridCLR.Editor.ABI
|
||||
GenericInstSig gis = (GenericInstSig)type;
|
||||
if (!gis.GenericType.IsValueType)
|
||||
{
|
||||
return TypeInfo.s_u;
|
||||
return GetNativeIntTypeInfo();
|
||||
}
|
||||
TypeDef typeDef = gis.GenericType.ToTypeDefOrRef().ResolveTypeDef();
|
||||
if (typeDef.IsEnum)
|
||||
@@ -94,9 +112,46 @@ namespace HybridCLR.Editor.ABI
|
||||
}
|
||||
}
|
||||
|
||||
protected static TypeInfo CreateGeneralValueType(TypeSig type, int size, int aligment)
|
||||
{
|
||||
System.Diagnostics.Debug.Assert(size % aligment == 0);
|
||||
switch (aligment)
|
||||
{
|
||||
case 1: return new TypeInfo(ParamOrReturnType.STRUCTURE_ALIGN1, size);
|
||||
case 2: return new TypeInfo(ParamOrReturnType.STRUCTURE_ALIGN2, size);
|
||||
case 4: return new TypeInfo(ParamOrReturnType.STRUCTURE_ALIGN4, size);
|
||||
case 8: return new TypeInfo(ParamOrReturnType.STRUCTURE_ALIGN8, size);
|
||||
default: throw new NotSupportedException($"type:{type} not support aligment:{aligment}");
|
||||
}
|
||||
}
|
||||
|
||||
protected virtual bool TryCreateCustomValueTypeInfo(TypeSig type, int typeSize, int typeAligment, out TypeInfo typeInfo)
|
||||
{
|
||||
typeInfo = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
protected TypeInfo CreateValueType(TypeSig type)
|
||||
{
|
||||
return new TypeInfo(ParamOrReturnType.STRUCT, type, _nextStructId++);
|
||||
(int typeSize, int typeAligment) = ComputeSizeAndAligment(type);
|
||||
if (TryCreateCustomValueTypeInfo(type, typeSize, typeAligment, out var typeInfo))
|
||||
{
|
||||
Debug.Log($"[{GetType().Name}] CustomeValueType:{type} => {typeInfo.CreateSigName()}");
|
||||
return typeInfo;
|
||||
}
|
||||
else
|
||||
{
|
||||
// 64位下结构体内存对齐规则是一样的
|
||||
return CreateGeneralValueType(type, typeSize, typeAligment);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
protected abstract TypeInfo OptimizeSigType(TypeInfo type, bool returnType);
|
||||
|
||||
public virtual void OptimizeMethod(MethodDesc method)
|
||||
{
|
||||
method.TransfromSigTypes(OptimizeSigType);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 7e9e6a048682dcb4fab806251411f29f
|
||||
guid: b63c5bf995a6d624dbd10d9df6cb6a7a
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
@@ -0,0 +1,23 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace HybridCLR.Editor.ABI
|
||||
{
|
||||
public static class TypeCreatorFactory
|
||||
{
|
||||
public static TypeCreatorBase CreateTypeCreator(PlatformABI abi)
|
||||
{
|
||||
switch(abi)
|
||||
{
|
||||
case PlatformABI.Arm64: return new TypeCreatorArm64();
|
||||
case PlatformABI.Universal32: return new TypeCreatorUniversal32();
|
||||
case PlatformABI.Universal64: return new TypeCreatorUniversal64();
|
||||
case PlatformABI.WebGL32: return new TypeCreatorWebGL32();
|
||||
default: throw new NotSupportedException(abi.ToString());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
fileFormatVersion: 2
|
||||
guid: d2f62ca12f2eb4f2fba8e9cb51279421
|
||||
guid: fe1634f74b7ca2e42bd07233b451cd94
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
@@ -0,0 +1,22 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace HybridCLR.Editor.ABI
|
||||
{
|
||||
public class TypeCreatorUniversal32 : TypeCreatorBase
|
||||
{
|
||||
public override bool IsArch32 => true;
|
||||
|
||||
protected override TypeInfo OptimizeSigType(TypeInfo type, bool returnType)
|
||||
{
|
||||
if (type.PorType > ParamOrReturnType.STRUCTURE_ALIGN1 && type.PorType <= ParamOrReturnType.STRUCTURE_ALIGN4)
|
||||
{
|
||||
return new TypeInfo(ParamOrReturnType.STRUCTURE_ALIGN1, type.Size);
|
||||
}
|
||||
return type;
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 96c2bc28db69e1644892219abef3d4b5
|
||||
guid: 1eb9e19189731a344aad024a43e795bc
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
@@ -0,0 +1,23 @@
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace HybridCLR.Editor.ABI
|
||||
{
|
||||
public class TypeCreatorUniversal64 : TypeCreatorBase
|
||||
{
|
||||
public override bool IsArch32 => false;
|
||||
|
||||
protected override TypeInfo OptimizeSigType(TypeInfo type, bool returnType)
|
||||
{
|
||||
if (type.PorType > ParamOrReturnType.STRUCTURE_ALIGN1 && type.PorType <= ParamOrReturnType.STRUCTURE_ALIGN8)
|
||||
{
|
||||
return new TypeInfo(ParamOrReturnType.STRUCTURE_ALIGN1, type.Size);
|
||||
}
|
||||
return type;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 7867dfe20d27e324e90bc13b9d4f05bb
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,220 @@
|
||||
using dnlib.DotNet;
|
||||
using HybridCLR.Editor.Meta;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace HybridCLR.Editor.ABI
|
||||
{
|
||||
public class SingletonStruct
|
||||
{
|
||||
public TypeSig Type { get; set; }
|
||||
}
|
||||
|
||||
public class TypeCreatorWebGL32 : TypeCreatorBase
|
||||
{
|
||||
public override bool IsArch32 => true;
|
||||
|
||||
protected override TypeInfo OptimizeSigType(TypeInfo type, bool returnType)
|
||||
{
|
||||
//if (type.PorType > ParamOrReturnType.STRUCTURE_ALIGN1 && type.PorType <= ParamOrReturnType.STRUCTURE_ALIGN4)
|
||||
//{
|
||||
// return new TypeInfo(ParamOrReturnType.STRUCTURE_ALIGN1, type.Size);
|
||||
//}
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 4790a87aacda1a14d813570e9e0f35ca
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+83
-32
@@ -1,5 +1,4 @@
|
||||
using dnlib.DotNet;
|
||||
using HybridCLR.Editor.Meta;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Reflection;
|
||||
@@ -21,34 +20,37 @@ namespace HybridCLR.Editor.ABI
|
||||
public static readonly TypeInfo s_u8 = new TypeInfo(ParamOrReturnType.U8);
|
||||
public static readonly TypeInfo s_r4 = new TypeInfo(ParamOrReturnType.R4);
|
||||
public static readonly TypeInfo s_r8 = new TypeInfo(ParamOrReturnType.R8);
|
||||
public static readonly TypeInfo s_i = new TypeInfo(ParamOrReturnType.I);
|
||||
public static readonly TypeInfo s_u = new TypeInfo(ParamOrReturnType.U);
|
||||
public static readonly TypeInfo s_typedByRef = new TypeInfo(ParamOrReturnType.TYPEDBYREF);
|
||||
public static readonly TypeInfo s_i16 = new TypeInfo(ParamOrReturnType.I16);
|
||||
public static readonly TypeInfo s_ref = new TypeInfo(ParamOrReturnType.STRUCTURE_AS_REF_PARAM);
|
||||
|
||||
public const string strTypedByRef = "typedbyref";
|
||||
public static readonly TypeInfo s_vf2 = new TypeInfo(ParamOrReturnType.ARM64_HFA_FLOAT_2);
|
||||
public static readonly TypeInfo s_vf3 = new TypeInfo(ParamOrReturnType.ARM64_HFA_FLOAT_3);
|
||||
public static readonly TypeInfo s_vf4 = new TypeInfo(ParamOrReturnType.ARM64_HFA_FLOAT_4);
|
||||
public static readonly TypeInfo s_vd2 = new TypeInfo(ParamOrReturnType.ARM64_HFA_DOUBLE_2);
|
||||
public static readonly TypeInfo s_vd3 = new TypeInfo(ParamOrReturnType.ARM64_HFA_DOUBLE_3);
|
||||
public static readonly TypeInfo s_vd4 = new TypeInfo(ParamOrReturnType.ARM64_HFA_DOUBLE_4);
|
||||
|
||||
public TypeInfo(ParamOrReturnType portype, TypeSig klass = null, int typeId = 0)
|
||||
public TypeInfo(ParamOrReturnType portype)
|
||||
{
|
||||
PorType = portype;
|
||||
Klass = klass;
|
||||
_typeId = typeId;
|
||||
Size = 0;
|
||||
}
|
||||
|
||||
public TypeInfo(ParamOrReturnType portype, int size)
|
||||
{
|
||||
PorType = portype;
|
||||
Size = size;
|
||||
}
|
||||
|
||||
public ParamOrReturnType PorType { get; }
|
||||
|
||||
public TypeSig Klass { get; }
|
||||
public bool IsGeneralValueType => PorType >= ParamOrReturnType.STRUCTURE_ALIGN1 && PorType <= ParamOrReturnType.STRUCTURE_ALIGN8;
|
||||
|
||||
public bool IsStruct => PorType == ParamOrReturnType.STRUCT;
|
||||
|
||||
public bool IsPrimitiveType => PorType <= ParamOrReturnType.U;
|
||||
|
||||
private readonly int _typeId;
|
||||
|
||||
public int TypeId => _typeId;
|
||||
public int Size { get; }
|
||||
|
||||
public bool Equals(TypeInfo other)
|
||||
{
|
||||
return PorType == other.PorType && TypeEqualityComparer.Instance.Equals(Klass, other.Klass);
|
||||
return PorType == other.PorType && Size == other.Size;
|
||||
}
|
||||
|
||||
public override bool Equals(object obj)
|
||||
@@ -58,12 +60,7 @@ namespace HybridCLR.Editor.ABI
|
||||
|
||||
public override int GetHashCode()
|
||||
{
|
||||
return (int)PorType * 23 + (Klass != null ? TypeEqualityComparer.Instance.GetHashCode(Klass) : 0);
|
||||
}
|
||||
|
||||
public bool NeedExpandValue()
|
||||
{
|
||||
return PorType >= ParamOrReturnType.I1 && PorType <= ParamOrReturnType.U2;
|
||||
return (int)PorType * 23 + Size;
|
||||
}
|
||||
|
||||
public string CreateSigName()
|
||||
@@ -81,10 +78,22 @@ namespace HybridCLR.Editor.ABI
|
||||
case ParamOrReturnType.U8: return "u8";
|
||||
case ParamOrReturnType.R4: return "r4";
|
||||
case ParamOrReturnType.R8: return "r8";
|
||||
case ParamOrReturnType.I: return "i";
|
||||
case ParamOrReturnType.U: return "u";
|
||||
case ParamOrReturnType.TYPEDBYREF: return strTypedByRef;
|
||||
case ParamOrReturnType.STRUCT: return $"s{_typeId}";
|
||||
case ParamOrReturnType.I16: return "i16";
|
||||
case ParamOrReturnType.STRUCTURE_AS_REF_PARAM: return "sr";
|
||||
case ParamOrReturnType.ARM64_HFA_FLOAT_2: return "vf2";
|
||||
case ParamOrReturnType.ARM64_HFA_FLOAT_3: return "vf3";
|
||||
case ParamOrReturnType.ARM64_HFA_FLOAT_4: return "vf4";
|
||||
case ParamOrReturnType.ARM64_HFA_DOUBLE_2: return "vd2";
|
||||
case ParamOrReturnType.ARM64_HFA_DOUBLE_3: return "vd3";
|
||||
case ParamOrReturnType.ARM64_HFA_DOUBLE_4: return "vd4";
|
||||
case ParamOrReturnType.STRUCTURE_ALIGN1: return "S" + Size;
|
||||
case ParamOrReturnType.STRUCTURE_ALIGN2: return "A" + Size;
|
||||
case ParamOrReturnType.STRUCTURE_ALIGN4: return "B" + Size;
|
||||
case ParamOrReturnType.STRUCTURE_ALIGN8: return "C" + Size;
|
||||
case ParamOrReturnType.SPECIAL_STRUCTURE_ALIGN1: return "X" + Size;
|
||||
case ParamOrReturnType.SPECIAL_STRUCTURE_ALIGN2: return "Y" + Size;
|
||||
case ParamOrReturnType.SPECIAL_STRUCTURE_ALIGN4: return "Z" + Size;
|
||||
case ParamOrReturnType.SPECIAL_STRUCTURE_ALIGN8: return "W" + Size;
|
||||
default: throw new NotSupportedException(PorType.ToString());
|
||||
};
|
||||
}
|
||||
@@ -104,13 +113,55 @@ namespace HybridCLR.Editor.ABI
|
||||
case ParamOrReturnType.U8: return "uint64_t";
|
||||
case ParamOrReturnType.R4: return "float";
|
||||
case ParamOrReturnType.R8: return "double";
|
||||
case ParamOrReturnType.I: return "intptr_t";
|
||||
case ParamOrReturnType.U: return "uintptr_t";
|
||||
case ParamOrReturnType.TYPEDBYREF: return "Il2CppTypedRef";
|
||||
case ParamOrReturnType.STRUCT: return $"__struct_{_typeId}__";
|
||||
case ParamOrReturnType.I16: return "ValueTypeSize16";
|
||||
case ParamOrReturnType.STRUCTURE_AS_REF_PARAM: return "uint64_t";
|
||||
case ParamOrReturnType.ARM64_HFA_FLOAT_2: return "HtVector2f";
|
||||
case ParamOrReturnType.ARM64_HFA_FLOAT_3: return "HtVector3f";
|
||||
case ParamOrReturnType.ARM64_HFA_FLOAT_4: return "HtVector4f";
|
||||
case ParamOrReturnType.ARM64_HFA_DOUBLE_2: return "HtVector2d";
|
||||
case ParamOrReturnType.ARM64_HFA_DOUBLE_3: return "HtVector3d";
|
||||
case ParamOrReturnType.ARM64_HFA_DOUBLE_4: return "HtVector4d";
|
||||
case ParamOrReturnType.STRUCTURE_ALIGN1: return $"ValueTypeSize<{Size}>";
|
||||
case ParamOrReturnType.STRUCTURE_ALIGN2: return $"ValueTypeSizeAlign2<{Size}>";
|
||||
case ParamOrReturnType.STRUCTURE_ALIGN4: return $"ValueTypeSizeAlign4<{Size}>";
|
||||
case ParamOrReturnType.STRUCTURE_ALIGN8: return $"ValueTypeSizeAlign8<{Size}>";
|
||||
case ParamOrReturnType.SPECIAL_STRUCTURE_ALIGN1: return $"WebGLSpeicalValueType<{Size}>";
|
||||
case ParamOrReturnType.SPECIAL_STRUCTURE_ALIGN2: return $"WebGLSpeicalValueTypeAlign2<{Size}>";
|
||||
case ParamOrReturnType.SPECIAL_STRUCTURE_ALIGN4: return $"WebGLSpeicalValueTypeAlign4<{Size}>";
|
||||
case ParamOrReturnType.SPECIAL_STRUCTURE_ALIGN8: return $"WebGLSpeicalValueTypeAlign8<{Size}>";
|
||||
default: throw new NotImplementedException(PorType.ToString());
|
||||
};
|
||||
}
|
||||
|
||||
public int GetParamSlotNum()
|
||||
{
|
||||
switch (PorType)
|
||||
{
|
||||
case ParamOrReturnType.VOID: return 0;
|
||||
case ParamOrReturnType.I16: return 2;
|
||||
case ParamOrReturnType.STRUCTURE_AS_REF_PARAM: return 1;
|
||||
case ParamOrReturnType.ARM64_HFA_FLOAT_3: return 2;
|
||||
case ParamOrReturnType.ARM64_HFA_FLOAT_4: return 2;
|
||||
case ParamOrReturnType.ARM64_HFA_DOUBLE_2: return 2;
|
||||
case ParamOrReturnType.ARM64_HFA_DOUBLE_3: return 3;
|
||||
case ParamOrReturnType.ARM64_HFA_DOUBLE_4: return 4;
|
||||
case ParamOrReturnType.ARM64_HVA_8:
|
||||
case ParamOrReturnType.ARM64_HVA_16: throw new NotSupportedException();
|
||||
case ParamOrReturnType.STRUCTURE_ALIGN1:
|
||||
case ParamOrReturnType.STRUCTURE_ALIGN2:
|
||||
case ParamOrReturnType.STRUCTURE_ALIGN4:
|
||||
case ParamOrReturnType.STRUCTURE_ALIGN8:
|
||||
case ParamOrReturnType.SPECIAL_STRUCTURE_ALIGN1:
|
||||
case ParamOrReturnType.SPECIAL_STRUCTURE_ALIGN2:
|
||||
case ParamOrReturnType.SPECIAL_STRUCTURE_ALIGN4:
|
||||
case ParamOrReturnType.SPECIAL_STRUCTURE_ALIGN8:
|
||||
return (Size + 7) / 8;
|
||||
default:
|
||||
{
|
||||
Debug.Assert(PorType < ParamOrReturnType.STRUCT_NOT_PASS_AS_VALUE);
|
||||
Debug.Assert(Size <= 8);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
using dnlib.DotNet;
|
||||
using dnlib.DotNet.Writer;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace HybridCLR.Editor.AOT
|
||||
{
|
||||
public class AOTAssemblyMetadataStripper
|
||||
{
|
||||
public static byte[] Strip(byte[] assemblyBytes)
|
||||
{
|
||||
var mod = ModuleDefMD.Load(assemblyBytes);
|
||||
foreach (var type in mod.GetTypes())
|
||||
{
|
||||
if (type.HasGenericParameters)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
foreach (var method in type.Methods)
|
||||
{
|
||||
if (!method.HasBody || method.HasGenericParameters)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
method.Body = null;
|
||||
}
|
||||
}
|
||||
var writer = new System.IO.MemoryStream();
|
||||
var options = new ModuleWriterOptions(mod);
|
||||
options.MetadataOptions.Flags |= MetadataFlags.PreserveAll;
|
||||
mod.Write(writer);
|
||||
writer.Flush();
|
||||
return writer.ToArray();
|
||||
}
|
||||
|
||||
public static void Strip(string originalAssemblyPath, string strippedAssemblyPath)
|
||||
{
|
||||
byte[] originDllBytes = System.IO.File.ReadAllBytes(originalAssemblyPath);
|
||||
byte[] strippedDllBytes = Strip(originDllBytes);
|
||||
UnityEngine.Debug.Log($"aot dll:{originalAssemblyPath}, length: {originDllBytes.Length} -> {strippedDllBytes.Length}, stripping rate:{(originDllBytes.Length - strippedDllBytes.Length)/(double)originDllBytes.Length} ");
|
||||
Directory.CreateDirectory(System.IO.Path.GetDirectoryName(strippedAssemblyPath));
|
||||
System.IO.File.WriteAllBytes(strippedAssemblyPath, strippedDllBytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
+14
-28
@@ -58,15 +58,15 @@ namespace HybridCLR.Editor.AOT
|
||||
return;
|
||||
}
|
||||
gc = gc.ToGenericShare();
|
||||
if (_genericTypes.Add(gc) && NeedWalk(null, gc.Type))
|
||||
if (_genericTypes.Add(gc) && NeedWalk(gc.Type))
|
||||
{
|
||||
WalkType(gc);
|
||||
}
|
||||
}
|
||||
|
||||
private bool NeedWalk(MethodDef callFrom, TypeDef type)
|
||||
private bool NeedWalk(TypeDef type)
|
||||
{
|
||||
return _hotUpdateAssemblyFiles.Contains(type.Module.Name) || callFrom == null || callFrom.HasGenericParameters;
|
||||
return _hotUpdateAssemblyFiles.Contains(type.Module.Name);
|
||||
}
|
||||
|
||||
private bool IsAotType(TypeDef type)
|
||||
@@ -79,13 +79,13 @@ namespace HybridCLR.Editor.AOT
|
||||
return IsAotType(method.DeclaringType) && method.HasGenericParameters;
|
||||
}
|
||||
|
||||
private void OnNewMethod(MethodDef methodDef, List<TypeSig> klassGenericInst, List<TypeSig> methodGenericInst, GenericMethod method)
|
||||
private void OnNewMethod(GenericMethod method)
|
||||
{
|
||||
if(method == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (NeedWalk(methodDef, method.Method.DeclaringType) && _genericMethods.Add(method))
|
||||
if (_genericMethods.Add(method) && NeedWalk(method.Method.DeclaringType))
|
||||
{
|
||||
_newMethods.Add(method);
|
||||
}
|
||||
@@ -101,7 +101,7 @@ namespace HybridCLR.Editor.AOT
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (NeedWalk(null, method.Method.DeclaringType) && _genericMethods.Add(method))
|
||||
if (_genericMethods.Add(method) && NeedWalk(method.Method.DeclaringType))
|
||||
{
|
||||
_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);
|
||||
var cs = GenericClass.ResolveClass(ts, null)?.ToGenericShare();
|
||||
if (cs != null)
|
||||
if (!ts.ContainsGenericParameter)
|
||||
{
|
||||
var cs = GenericClass.ResolveClass(ts, null)?.ToGenericShare();
|
||||
TryAddAndWalkGenericType(cs);
|
||||
}
|
||||
}
|
||||
@@ -167,6 +167,10 @@ 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);
|
||||
}
|
||||
@@ -191,29 +195,11 @@ namespace HybridCLR.Editor.AOT
|
||||
}
|
||||
}
|
||||
|
||||
private bool IsNotShareableAOTGenericType(TypeDef typeDef)
|
||||
{
|
||||
if (!IsAotType(typeDef))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return typeDef.GenericParameters.Any(c => !c.HasReferenceTypeConstraint);
|
||||
}
|
||||
|
||||
private bool IsNotShareableAOTGenericMethod(MethodDef method)
|
||||
{
|
||||
if (!IsAotGenericMethod(method))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return method.GenericParameters.Concat(method.DeclaringType.GenericParameters).Any(c => !c.HasReferenceTypeConstraint);
|
||||
}
|
||||
|
||||
private void FilterAOTGenericTypeAndMethods()
|
||||
{
|
||||
ConstraintContext cc = this.ConstraintContext;
|
||||
AotGenericTypes.AddRange(_genericTypes.Where(type => IsNotShareableAOTGenericType(type.Type)).Select(gc => cc.ApplyConstraints(gc)));
|
||||
AotGenericMethods.AddRange(_genericMethods.Where(method => IsNotShareableAOTGenericMethod(method.Method)).Select(gm => cc.ApplyConstraints(gm)));
|
||||
AotGenericTypes.AddRange(_genericTypes.Where(type => IsAotType(type.Type)).Select(gc => cc.ApplyConstraints(gc)));
|
||||
AotGenericMethods.AddRange(_genericMethods.Where(method => IsAotGenericMethod(method.Method)).Select(gm => cc.ApplyConstraints(gm)));
|
||||
}
|
||||
|
||||
public void Run()
|
||||
|
||||
@@ -64,22 +64,18 @@ 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\t\"{module.Name}\",");
|
||||
codes.Add($"\t// {module.Name}");
|
||||
}
|
||||
codes.Add("\t};");
|
||||
codes.Add("\t// }}");
|
||||
|
||||
|
||||
@@ -90,12 +86,11 @@ namespace HybridCLR.Editor.AOT
|
||||
|
||||
codes.Add("");
|
||||
codes.Add("\t// {{ AOT generic types");
|
||||
|
||||
List<string> typeNames = types.Select(t => PrettifyTypeSig(t.ToTypeSig().ToString())).ToList();
|
||||
typeNames.Sort(string.CompareOrdinal);
|
||||
foreach(var typeName in typeNames)
|
||||
|
||||
types.Sort((a, b) => a.Type.FullName.CompareTo(b.Type.FullName));
|
||||
foreach(var type in types)
|
||||
{
|
||||
codes.Add($"\t// {typeName}");
|
||||
codes.Add($"\t// {PrettifyTypeSig(type.ToTypeSig().ToString())}");
|
||||
}
|
||||
|
||||
codes.Add("\t// }}");
|
||||
@@ -103,36 +98,27 @@ namespace HybridCLR.Editor.AOT
|
||||
codes.Add("");
|
||||
codes.Add("\tpublic void RefMethods()");
|
||||
codes.Add("\t{");
|
||||
|
||||
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) =>
|
||||
methods.Sort((a, b) =>
|
||||
{
|
||||
int c = String.Compare(a.Item1, b.Item1, StringComparison.Ordinal);
|
||||
int c = a.Method.DeclaringType.FullName.CompareTo(b.Method.DeclaringType.FullName);
|
||||
if (c != 0)
|
||||
{
|
||||
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);
|
||||
c = a.Method.Name.CompareTo(b.Method.Name);
|
||||
return c;
|
||||
});
|
||||
foreach(var method in methodTypeAndNames)
|
||||
foreach(var method in methods)
|
||||
{
|
||||
codes.Add($"\t\t// {PrettifyMethodSig(method.Item3)}");
|
||||
codes.Add($"\t\t// {PrettifyMethodSig(method.ToMethodSpec().ToString())}");
|
||||
}
|
||||
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}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,270 +0,0 @@
|
||||
using System;
|
||||
using HybridCLR.Editor.Installer;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using UnityEditor;
|
||||
using System.Reflection;
|
||||
using HybridCLR.Editor.Settings;
|
||||
#if UNITY_2019 && (UNITY_IOS || UNITY_TVOS)
|
||||
using UnityEditor.Build;
|
||||
using UnityEditor.Callbacks;
|
||||
using UnityEditor.iOS.Xcode;
|
||||
using UnityEngine;
|
||||
|
||||
namespace HybridCLR.Editor.BuildProcessors
|
||||
{
|
||||
public static class AddLil2cppSourceCodeToXcodeproj2019
|
||||
{
|
||||
//[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 (!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
|
||||
10. add "#include <stdio.h>" to Classes/Prefix.pch
|
||||
*/
|
||||
|
||||
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);
|
||||
AddSystemHeaderToPrefixPch(pathToBuiltProject);
|
||||
}
|
||||
|
||||
private static void AddSystemHeaderToPrefixPch(string pathToBuiltProject)
|
||||
{
|
||||
// 如果不将 stdio.h 添加到 Prefix.pch, zutil.c会有编译错误
|
||||
string prefixPchFile = $"{pathToBuiltProject}/Classes/Prefix.pch";
|
||||
string fileContent = File.ReadAllText(prefixPchFile, Encoding.UTF8);
|
||||
if (!fileContent.Contains("stdio.h"))
|
||||
{
|
||||
string newFileContent = fileContent + "\n#include <stdio.h>\n";
|
||||
File.WriteAllText(prefixPchFile, newFileContent, Encoding.UTF8);
|
||||
UnityEngine.Debug.Log($"append header to {prefixPchFile}");
|
||||
}
|
||||
}
|
||||
|
||||
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";
|
||||
}
|
||||
newPro += " $(SRCR00T)/Libraries/external/mono";
|
||||
//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);
|
||||
|
||||
string il2cppConfigFile = $"{libil2cppDir}/il2cpp-config.h";
|
||||
var lumpFiles = new List<LumpFile>();
|
||||
int lumpFileIndex = 0;
|
||||
foreach (var cppDir in Directory.GetDirectories(libil2cppDir, "*", SearchOption.AllDirectories).Concat(new string[] {libil2cppDir}))
|
||||
{
|
||||
var lumpFile = new LumpFile($"{outputDir}/lump_{Path.GetFileName(cppDir)}_{lumpFileIndex}.cpp", il2cppConfigFile);
|
||||
foreach (var file in Directory.GetFiles(cppDir, "*.cpp", SearchOption.TopDirectoryOnly))
|
||||
{
|
||||
lumpFile.cppFiles.Add(file);
|
||||
}
|
||||
lumpFile.SaveFile();
|
||||
lumpFiles.Add(lumpFile);
|
||||
++lumpFileIndex;
|
||||
}
|
||||
|
||||
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
|
||||
@@ -1,255 +0,0 @@
|
||||
using System;
|
||||
using HybridCLR.Editor.Installer;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using UnityEditor;
|
||||
using System.Reflection;
|
||||
using HybridCLR.Editor.Settings;
|
||||
#if (UNITY_2020 || UNITY_2021) && (UNITY_IOS || UNITY_TVOS)
|
||||
using UnityEditor.Build;
|
||||
using UnityEditor.Callbacks;
|
||||
using UnityEditor.iOS.Xcode;
|
||||
using UnityEngine;
|
||||
|
||||
namespace HybridCLR.Editor.BuildProcessors
|
||||
{
|
||||
public static class AddLil2cppSourceCodeToXcodeproj2020Or2021
|
||||
{
|
||||
//[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 (!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";
|
||||
}
|
||||
newPro += " $(SRCR00T)/Libraries/external/mono";
|
||||
//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);
|
||||
|
||||
string il2cppConfigFile = $"{libil2cppDir}/il2cpp-config.h";
|
||||
var lumpFiles = new List<LumpFile>();
|
||||
int lumpFileIndex = 0;
|
||||
foreach (var cppDir in Directory.GetDirectories(libil2cppDir, "*", SearchOption.AllDirectories).Concat(new string[] {libil2cppDir}))
|
||||
{
|
||||
var lumpFile = new LumpFile($"{outputDir}/lump_{Path.GetFileName(cppDir)}_{lumpFileIndex}.cpp", il2cppConfigFile);
|
||||
foreach (var file in Directory.GetFiles(cppDir, "*.cpp", SearchOption.TopDirectoryOnly))
|
||||
{
|
||||
lumpFile.cppFiles.Add(file);
|
||||
}
|
||||
lumpFile.SaveFile();
|
||||
lumpFiles.Add(lumpFile);
|
||||
++lumpFileIndex;
|
||||
}
|
||||
|
||||
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
|
||||
@@ -1,11 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 61948fcb1bc40ba47b8c10b0ae801ebb
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -1,60 +0,0 @@
|
||||
using HybridCLR.Editor.Installer;
|
||||
using HybridCLR.Editor.Settings;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using UnityEditor;
|
||||
using UnityEditor.Build;
|
||||
using UnityEditor.Callbacks;
|
||||
using UnityEngine;
|
||||
|
||||
#if UNITY_2022_2_OR_NEWER && (UNITY_IOS || UNITY_TVOS)
|
||||
|
||||
namespace HybridCLR.Editor.BuildProcessors
|
||||
{
|
||||
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 (!HybridCLRSettings.Instance.enable)
|
||||
return;
|
||||
#if TUANJIE_2022_3_OR_NEWER
|
||||
string pbxprojFile = $"{pathToBuiltProject}/Tuanjie-iPhone.xcodeproj/project.pbxproj";
|
||||
#else
|
||||
string pbxprojFile = $"{pathToBuiltProject}/Unity-iPhone.xcodeproj/project.pbxproj";
|
||||
#endif
|
||||
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
|
||||
@@ -1,11 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: a4ce072f7e4a17248a3d9ebfd011356b
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -1,5 +1,4 @@
|
||||
using HybridCLR.Editor.Settings;
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
@@ -8,7 +7,6 @@ using UnityEditor;
|
||||
using UnityEditor.Build;
|
||||
using UnityEditor.Build.Reporting;
|
||||
using UnityEngine;
|
||||
using static UnityEngine.GraphicsBuffer;
|
||||
|
||||
namespace HybridCLR.Editor.BuildProcessors
|
||||
{
|
||||
@@ -19,13 +17,14 @@ 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");
|
||||
if (!string.IsNullOrEmpty(oldIl2cppPath))
|
||||
{
|
||||
Environment.SetEnvironmentVariable("UNITY_IL2CPP_PATH", "");
|
||||
Debug.Log($"[CheckSettings] clean process environment variable: UNITY_IL2CPP_PATH, old vlaue:'{oldIl2cppPath}'");
|
||||
Debug.Log($"[CheckSettings] 清除 UNITY_IL2CPP_PATH, 旧值为:'{oldIl2cppPath}'");
|
||||
}
|
||||
}
|
||||
else
|
||||
@@ -34,37 +33,52 @@ namespace HybridCLR.Editor.BuildProcessors
|
||||
if (curIl2cppPath != SettingsUtil.LocalIl2CppDir)
|
||||
{
|
||||
Environment.SetEnvironmentVariable("UNITY_IL2CPP_PATH", SettingsUtil.LocalIl2CppDir);
|
||||
Debug.Log($"[CheckSettings] UNITY_IL2CPP_PATH old value:'{curIl2cppPath}', new value:'{SettingsUtil.LocalIl2CppDir}'");
|
||||
Debug.Log($"[CheckSettings] UNITY_IL2CPP_PATH 当前值为:'{curIl2cppPath}',更新为:'{SettingsUtil.LocalIl2CppDir}'");
|
||||
}
|
||||
}
|
||||
#endif
|
||||
if (!globalSettings.enable)
|
||||
{
|
||||
return;
|
||||
}
|
||||
BuildTargetGroup buildTargetGroup = BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget);
|
||||
if (PlayerSettings.gcIncremental)
|
||||
{
|
||||
Debug.LogError($"[CheckSettings] HybridCLR不支持增量式GC,已经自动将该选项关闭");
|
||||
PlayerSettings.gcIncremental = false;
|
||||
}
|
||||
BuildTargetGroup buildTargetGroup = EditorUserBuildSettings.selectedBuildTargetGroup;
|
||||
ScriptingImplementation curScriptingImplementation = PlayerSettings.GetScriptingBackend(buildTargetGroup);
|
||||
ScriptingImplementation targetScriptingImplementation = ScriptingImplementation.IL2CPP;
|
||||
if (curScriptingImplementation != targetScriptingImplementation)
|
||||
{
|
||||
Debug.LogError($"[CheckSettings] current ScriptingBackend:{curScriptingImplementation},have been switched to:{targetScriptingImplementation} automatically");
|
||||
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 BuildFailedException($"You have not initialized HybridCLR, please install it via menu 'HybridCLR/Installer'");
|
||||
}
|
||||
|
||||
if (installer.PackageVersion != installer.InstalledLibil2cppVersion)
|
||||
{
|
||||
throw new BuildFailedException($"You must run `HybridCLR/Installer` after upgrading package");
|
||||
throw new Exception($"你没有初始化HybridCLR,请通过菜单'HybridCLR/Installer'安装");
|
||||
}
|
||||
|
||||
HybridCLRSettings gs = SettingsUtil.HybridCLRSettings;
|
||||
if (((gs.hotUpdateAssemblies?.Length + gs.hotUpdateAssemblyDefinitions?.Length) ?? 0) == 0)
|
||||
{
|
||||
Debug.LogWarning("[CheckSettings] No hot update modules configured in HybridCLRSettings");
|
||||
Debug.LogWarning("[CheckSettings] HybridCLRSettings中未配置任何热更新模块");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
using HybridCLR.Editor.Installer;
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
@@ -14,7 +13,7 @@ using UnityEngine;
|
||||
|
||||
namespace HybridCLR.Editor.BuildProcessors
|
||||
{
|
||||
internal class CopyStrippedAOTAssemblies : IPostprocessBuildWithReport, IPreprocessBuildWithReport
|
||||
internal class CopyStrippedAOTAssemblies : IPostprocessBuildWithReport
|
||||
#if !UNITY_2021_1_OR_NEWER
|
||||
, IIl2CppProcessor
|
||||
#endif
|
||||
@@ -26,35 +25,19 @@ namespace HybridCLR.Editor.BuildProcessors
|
||||
public static string GetStripAssembliesDir2021(BuildTarget target)
|
||||
{
|
||||
string projectDir = SettingsUtil.ProjectDir;
|
||||
switch (target)
|
||||
{
|
||||
case BuildTarget.StandaloneWindows:
|
||||
case BuildTarget.StandaloneWindows64:
|
||||
return $"{projectDir}/Library/Bee/artifacts/WinPlayerBuildProgram/ManagedStripped";
|
||||
case BuildTarget.StandaloneLinux64:
|
||||
return $"{projectDir}/Library/Bee/artifacts/LinuxPlayerBuildProgram/ManagedStripped";
|
||||
case BuildTarget.Android:
|
||||
return $"{projectDir}/Library/Bee/artifacts/Android/ManagedStripped";
|
||||
case BuildTarget.iOS:
|
||||
return $"{projectDir}/Library/Bee/artifacts/iOS/ManagedStripped";
|
||||
case BuildTarget.WebGL:
|
||||
return $"{projectDir}/Library/Bee/artifacts/WebGL/ManagedStripped";
|
||||
case BuildTarget.StandaloneOSX:
|
||||
return $"{projectDir}/Library/Bee/artifacts/MacStandalonePlayerBuildProgram/ManagedStripped";
|
||||
case BuildTarget.PS4:
|
||||
return $"{projectDir}/Library/Bee/artifacts/PS4PlayerBuildProgram/ManagedStripped";
|
||||
case BuildTarget.PS5:
|
||||
return $"{projectDir}/Library/Bee/artifacts/PS5PlayerBuildProgram/ManagedStripped";
|
||||
case BuildTarget.tvOS:
|
||||
return $"{projectDir}/Library/Bee/artifacts/iOS/ManagedStripped";
|
||||
#if TUANJIE_2022_3_OR_NEWER
|
||||
case BuildTarget.WeixinMiniGame:
|
||||
return $"{projectDir}/Library/Bee/artifacts/WeixinMiniGame/ManagedStripped";
|
||||
case BuildTarget.OpenHarmony:
|
||||
return $"{projectDir}/Library/Bee/artifacts/OpenHarmonyPlayerBuildProgram/ManagedStripped";
|
||||
#if UNITY_STANDALONE_WIN
|
||||
return $"{projectDir}/Library/Bee/artifacts/WinPlayerBuildProgram/ManagedStripped";
|
||||
#elif UNITY_ANDROID
|
||||
return $"{projectDir}/Library/Bee/artifacts/Android/ManagedStripped";
|
||||
#elif UNITY_IOS
|
||||
return $"{projectDir}/Temp/StagingArea/Data/Managed/tempStrip";
|
||||
#elif UNITY_WEBGL
|
||||
return $"{projectDir}/Library/Bee/artifacts/WebGL/ManagedStripped";
|
||||
#elif UNITY_EDITOR_OSX
|
||||
return $"{projectDir}/Library/Bee/artifacts/MacStandalonePlayerBuildProgram/ManagedStripped";
|
||||
#else
|
||||
throw new NotSupportedException("GetOriginBuildStripAssembliesDir");
|
||||
#endif
|
||||
default: return "";
|
||||
}
|
||||
}
|
||||
#else
|
||||
private string GetStripAssembliesDir2020(BuildTarget target)
|
||||
@@ -66,10 +49,9 @@ namespace HybridCLR.Editor.BuildProcessors
|
||||
}
|
||||
|
||||
public void OnBeforeConvertRun(BuildReport report, Il2CppBuildPipelineData data)
|
||||
{
|
||||
{
|
||||
// 此回调只在 2020中调用
|
||||
BuildTarget target = report.summary.platform;
|
||||
CopyStripDlls(GetStripAssembliesDir2020(target), target);
|
||||
CopyStripDlls(GetStripAssembliesDir2020(data.target), data.target);
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -96,21 +78,10 @@ namespace HybridCLR.Editor.BuildProcessors
|
||||
|
||||
public void OnPostprocessBuild(BuildReport report)
|
||||
{
|
||||
#if UNITY_2021_1_OR_NEWER
|
||||
BuildTarget target = report.summary.platform;
|
||||
string srcStripDllPath = GetStripAssembliesDir2021(target);
|
||||
if (!string.IsNullOrEmpty(srcStripDllPath) && Directory.Exists(srcStripDllPath))
|
||||
{
|
||||
CopyStripDlls(srcStripDllPath, target);
|
||||
}
|
||||
#if UNITY_2021_1_OR_NEWER && !UNITY_IOS
|
||||
BuildTarget target = EditorUserBuildSettings.activeBuildTarget;
|
||||
CopyStripDlls(GetStripAssembliesDir2021(target), target);
|
||||
#endif
|
||||
}
|
||||
|
||||
public void OnPreprocessBuild(BuildReport report)
|
||||
{
|
||||
BuildTarget target = report.summary.platform;
|
||||
var dstPath = SettingsUtil.GetAssembliesPostIl2CppStripDir(target);
|
||||
BashUtil.RecreateDir(dstPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
using HybridCLR.Editor.Meta;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
@@ -26,18 +25,15 @@ 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($"hot update assembly name cann't be empty");
|
||||
}
|
||||
if (!hotUpdateDllSet.Add(hotUpdateDll))
|
||||
{
|
||||
throw new BuildFailedException($"hot update assembly:{hotUpdateDll} is duplicated");
|
||||
throw new Exception($"热更新 assembly:{hotUpdateDll} 在列表中重复,请除去重复条目");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,24 +41,16 @@ namespace HybridCLR.Editor.BuildProcessors
|
||||
// 检查是否填写了正确的dll名称
|
||||
foreach (var hotUpdateDllName in allHotUpdateDllNames)
|
||||
{
|
||||
if (assemblies.Select(Path.GetFileNameWithoutExtension).All(ass => ass != hotUpdateDllName)
|
||||
&& string.IsNullOrEmpty(assResolver.ResolveAssembly(hotUpdateDllName, false)))
|
||||
string hotUpdateDllFile = hotUpdateDllName + ".dll";
|
||||
if (assemblies.All(ass => !ass.EndsWith(hotUpdateDllFile)) && string.IsNullOrEmpty(assResolver.ResolveAssembly(hotUpdateDllName, false)))
|
||||
{
|
||||
throw new BuildFailedException($"hot update assembly:{hotUpdateDllName} doesn't exist");
|
||||
throw new Exception($"热更新 assembly:{hotUpdateDllFile} 不存在,请检查拼写错误");
|
||||
}
|
||||
Debug.Log($"[FilterHotFixAssemblies] 过滤热更新assembly:{hotUpdateDllFile}");
|
||||
}
|
||||
|
||||
|
||||
// 将热更dll从打包列表中移除
|
||||
return assemblies.Where(ass =>
|
||||
{
|
||||
string assName = Path.GetFileNameWithoutExtension(ass);
|
||||
bool reserved = allHotUpdateDllNames.All(dll => !assName.Equals(dll, StringComparison.Ordinal));
|
||||
if (!reserved)
|
||||
{
|
||||
Debug.Log($"[FilterHotFixAssemblies] filter assembly:{assName}");
|
||||
}
|
||||
return reserved;
|
||||
}).ToArray();
|
||||
return assemblies.Where(ass => allHotupdateDllFiles.All(dll => !ass.EndsWith(dll, StringComparison.OrdinalIgnoreCase))).ToArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,28 +3,24 @@ using System;
|
||||
using UnityEditor.Build;
|
||||
using UnityEditor.Build.Reporting;
|
||||
|
||||
namespace HybridCLR.Editor.BuildProcessors
|
||||
public class MsvcStdextWorkaround : IPreprocessBuildWithReport
|
||||
{
|
||||
const string kWorkaroundFlag = "/D_SILENCE_STDEXT_HASH_DEPRECATION_WARNINGS";
|
||||
|
||||
public class MsvcStdextWorkaround : IPreprocessBuildWithReport
|
||||
public int callbackOrder => 0;
|
||||
|
||||
public void OnPreprocessBuild(BuildReport report)
|
||||
{
|
||||
const string kWorkaroundFlag = "/D_SILENCE_STDEXT_HASH_DEPRECATION_WARNINGS";
|
||||
var clEnv = Environment.GetEnvironmentVariable("_CL_");
|
||||
|
||||
public int callbackOrder => 0;
|
||||
|
||||
public void OnPreprocessBuild(BuildReport report)
|
||||
if (string.IsNullOrEmpty(clEnv))
|
||||
{
|
||||
var clEnv = Environment.GetEnvironmentVariable("_CL_");
|
||||
|
||||
if (string.IsNullOrEmpty(clEnv))
|
||||
{
|
||||
Environment.SetEnvironmentVariable("_CL_", kWorkaroundFlag);
|
||||
}
|
||||
else if (!clEnv.Contains(kWorkaroundFlag))
|
||||
{
|
||||
clEnv += " " + kWorkaroundFlag;
|
||||
Environment.SetEnvironmentVariable("_CL_", clEnv);
|
||||
}
|
||||
Environment.SetEnvironmentVariable("_CL_", kWorkaroundFlag);
|
||||
}
|
||||
else if (!clEnv.Contains(kWorkaroundFlag))
|
||||
{
|
||||
clEnv += " " + kWorkaroundFlag;
|
||||
Environment.SetEnvironmentVariable("_CL_", clEnv);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,18 +19,11 @@ namespace HybridCLR.Editor.BuildProcessors
|
||||
public class PatchScriptingAssemblyList :
|
||||
#if UNITY_ANDROID
|
||||
IPostGenerateGradleAndroidProject,
|
||||
#elif UNITY_OPENHARMONY
|
||||
UnityEditor.OpenHarmony.IPostGenerateOpenHarmonyProject,
|
||||
#endif
|
||||
IPostprocessBuildWithReport
|
||||
#if !UNITY_2021_1_OR_NEWER && UNITY_WEBGL
|
||||
, IIl2CppProcessor
|
||||
, IIl2CppProcessor
|
||||
#endif
|
||||
|
||||
#if UNITY_PS5
|
||||
, IUnityLinkerProcessor
|
||||
#endif
|
||||
|
||||
{
|
||||
public int callbackOrder => 0;
|
||||
|
||||
@@ -49,36 +42,16 @@ namespace HybridCLR.Editor.BuildProcessors
|
||||
}
|
||||
}
|
||||
|
||||
#if UNITY_OPENHARMONY
|
||||
|
||||
public void OnPostGenerateOpenHarmonyProject(string path)
|
||||
{
|
||||
OnPostGenerateGradleAndroidProject(path);
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
public void OnPostprocessBuild(BuildReport report)
|
||||
{
|
||||
// 如果target为Android,由于已经在OnPostGenerateGradelAndroidProject中处理过,
|
||||
// 这里不再重复处理
|
||||
#if !UNITY_ANDROID && !UNITY_WEBGL && !UNITY_OPENHARMONY
|
||||
#if !UNITY_ANDROID && !UNITY_WEBGL
|
||||
|
||||
PathScriptingAssembilesFile(report.summary.outputPath);
|
||||
#endif
|
||||
}
|
||||
|
||||
#if UNITY_PS5
|
||||
/// <summary>
|
||||
/// 打包模式如果是 Package 需要在这个阶段提前处理 .json , PC Hosted 和 GP5 模式不受影响
|
||||
/// </summary>
|
||||
|
||||
public string GenerateAdditionalLinkXmlFile(UnityEditor.Build.Reporting.BuildReport report, UnityEditor.UnityLinker.UnityLinkerBuildPipelineData data)
|
||||
{
|
||||
string path = $"{SettingsUtil.ProjectDir}/Library/PlayerDataCache/PS5/Data";
|
||||
PathScriptingAssembilesFile(path);
|
||||
return null;
|
||||
}
|
||||
#endif
|
||||
public void PathScriptingAssembilesFile(string path)
|
||||
{
|
||||
if (!SettingsUtil.Enable)
|
||||
@@ -111,7 +84,7 @@ namespace HybridCLR.Editor.BuildProcessors
|
||||
|
||||
if (jsonFiles.Length == 0)
|
||||
{
|
||||
Debug.LogWarning($"can not find file {SettingsUtil.ScriptingAssembliesJsonFile}");
|
||||
//Debug.LogError($"can not find file {SettingsUtil.ScriptingAssembliesJsonFile}");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -123,11 +96,9 @@ namespace HybridCLR.Editor.BuildProcessors
|
||||
patcher.Save(file);
|
||||
}
|
||||
}
|
||||
|
||||
private void AddHotFixAssembliesToBinFile(string path)
|
||||
{
|
||||
#if UNITY_STANDALONE_OSX
|
||||
path = Path.GetDirectoryName(path);
|
||||
#endif
|
||||
if (AddHotFixAssembliesToGlobalgamemanagers(path))
|
||||
{
|
||||
return;
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using UnityEngine;
|
||||
|
||||
namespace HybridCLR.Editor.BuildProcessors
|
||||
{
|
||||
public class ScriptingAssembliesJsonPatcher
|
||||
{
|
||||
[Serializable]
|
||||
private class ScriptingAssemblies
|
||||
{
|
||||
public List<string> names;
|
||||
public List<int> types;
|
||||
}
|
||||
|
||||
private string _file;
|
||||
ScriptingAssemblies _scriptingAssemblies;
|
||||
|
||||
public void Load(string file)
|
||||
{
|
||||
_file = file;
|
||||
string content = File.ReadAllText(file);
|
||||
_scriptingAssemblies = JsonUtility.FromJson<ScriptingAssemblies>(content);
|
||||
}
|
||||
|
||||
public void AddScriptingAssemblies(List<string> assemblies)
|
||||
{
|
||||
foreach (string name in assemblies)
|
||||
{
|
||||
if (!_scriptingAssemblies.names.Contains(name))
|
||||
{
|
||||
_scriptingAssemblies.names.Add(name);
|
||||
_scriptingAssemblies.types.Add(16); // user dll type
|
||||
Debug.Log($"[PatchScriptAssembliesJson] add hotfix assembly:{name} to {_file}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Save(string jsonFile)
|
||||
{
|
||||
string content = JsonUtility.ToJson(_scriptingAssemblies);
|
||||
|
||||
File.WriteAllText(jsonFile, content);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 4455f7304f8678f408dd6cf21734f55e
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -10,7 +10,6 @@ using UnityEngine;
|
||||
|
||||
namespace HybridCLR.Editor.Commands
|
||||
{
|
||||
using Analyzer = HybridCLR.Editor.AOT.Analyzer;
|
||||
public static class AOTReferenceGeneratorCommand
|
||||
{
|
||||
|
||||
|
||||
@@ -12,25 +12,25 @@ namespace HybridCLR.Editor.Commands
|
||||
{
|
||||
public class CompileDllCommand
|
||||
{
|
||||
public static void CompileDll(string buildDir, BuildTarget target, bool developmentBuild)
|
||||
public static void CompileDll(string buildDir, BuildTarget target)
|
||||
{
|
||||
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);
|
||||
#if UNITY_2022
|
||||
UnityEditor.EditorUtility.ClearProgressBar();
|
||||
#endif
|
||||
foreach (var ass in scriptCompilationResult.assemblies)
|
||||
{
|
||||
//Debug.LogFormat("compile assemblies:{1}/{0}", ass, buildDir);
|
||||
}
|
||||
Debug.Log("compile finish!!!");
|
||||
}
|
||||
|
||||
public static void CompileDll(BuildTarget target, bool developmentBuild = false)
|
||||
public static void CompileDll(BuildTarget target)
|
||||
{
|
||||
CompileDll(SettingsUtil.GetHotUpdateDllsOutputDirByTarget(target), target, developmentBuild);
|
||||
CompileDll(SettingsUtil.GetHotUpdateDllsOutputDirByTarget(target), target);
|
||||
}
|
||||
|
||||
[MenuItem("HybridCLR/CompileDll/ActiveBuildTarget", priority = 100)]
|
||||
@@ -39,12 +39,6 @@ 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()
|
||||
{
|
||||
@@ -57,34 +51,16 @@ namespace HybridCLR.Editor.Commands
|
||||
CompileDll(BuildTarget.StandaloneWindows64);
|
||||
}
|
||||
|
||||
[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)]
|
||||
[MenuItem("HybridCLR/CompileDll/Android", priority = 202)]
|
||||
public static void CompileDllAndroid()
|
||||
{
|
||||
CompileDll(BuildTarget.Android);
|
||||
}
|
||||
|
||||
[MenuItem("HybridCLR/CompileDll/IOS", priority = 220)]
|
||||
[MenuItem("HybridCLR/CompileDll/IOS", priority = 203)]
|
||||
public static void CompileDllIOS()
|
||||
{
|
||||
CompileDll(BuildTarget.iOS);
|
||||
}
|
||||
|
||||
[MenuItem("HybridCLR/CompileDll/WebGL", priority = 230)]
|
||||
public static void CompileDllWebGL()
|
||||
{
|
||||
CompileDll(BuildTarget.WebGL);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
using HybridCLR.Editor.Installer;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
|
||||
namespace HybridCLR.Editor.Commands
|
||||
{
|
||||
public static class InstallerCommand
|
||||
{
|
||||
|
||||
[MenuItem("HybridCLR/Installer...", false, 0)]
|
||||
private static void Open()
|
||||
{
|
||||
InstallerWindow window = EditorWindow.GetWindow<InstallerWindow>("HybridCLR Installer", true);
|
||||
window.minSize = new Vector2(800f, 500f);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b91d62dfcf14d1241b7654d79d5b98a0
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -8,7 +8,6 @@ using UnityEngine;
|
||||
|
||||
namespace HybridCLR.Editor.Commands
|
||||
{
|
||||
using Analyzer = HybridCLR.Editor.Link.Analyzer;
|
||||
|
||||
public static class LinkGeneratorCommand
|
||||
{
|
||||
|
||||
@@ -10,12 +10,10 @@ using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using UnityEditor;
|
||||
using UnityEditor.Build;
|
||||
using UnityEngine;
|
||||
|
||||
namespace HybridCLR.Editor.Commands
|
||||
{
|
||||
using Analyzer = HybridCLR.Editor.MethodBridge.Analyzer;
|
||||
public class MethodBridgeGeneratorCommand
|
||||
{
|
||||
|
||||
@@ -30,39 +28,34 @@ namespace HybridCLR.Editor.Commands
|
||||
Directory.Delete(il2cppBuildCachePath, true);
|
||||
}
|
||||
|
||||
private static void GenerateMethodBridgeCppFile(Analyzer analyzer, string outputFile)
|
||||
private static void GenerateMethodBridgeCppFile(Analyzer analyzer, PlatformABI platform, string templateCode, string outputFile)
|
||||
{
|
||||
string templateCode = File.ReadAllText(outputFile, Encoding.UTF8);
|
||||
var g = new Generator(new Generator.Options()
|
||||
{
|
||||
PlatformABI = platform,
|
||||
TemplateCode = templateCode,
|
||||
OutputFile = outputFile,
|
||||
GenericMethods = analyzer.GenericMethods,
|
||||
NotGenericMethods = analyzer.NotGenericMethods,
|
||||
});
|
||||
|
||||
g.PrepareMethods();
|
||||
g.Generate();
|
||||
Debug.LogFormat("[MethodBridgeGeneratorCommand] output:{0}", outputFile);
|
||||
Debug.LogFormat("== output:{0} ==", outputFile);
|
||||
}
|
||||
|
||||
[MenuItem("HybridCLR/Generate/MethodBridge", priority = 101)]
|
||||
public static void CompileAndGenerateMethodBridge()
|
||||
{
|
||||
BuildTarget target = EditorUserBuildSettings.activeBuildTarget;
|
||||
CompileDllCommand.CompileDll(target);
|
||||
GenerateMethodBridge(target);
|
||||
}
|
||||
|
||||
public static void GenerateMethodBridge(BuildTarget target)
|
||||
{
|
||||
string aotDllDir = SettingsUtil.GetAssembliesPostIl2CppStripDir(target);
|
||||
List<string> aotAssemblyNames = Directory.Exists(aotDllDir) ?
|
||||
Directory.GetFiles(aotDllDir, "*.dll", SearchOption.TopDirectoryOnly).Select(Path.GetFileNameWithoutExtension).ToList()
|
||||
: new List<string>();
|
||||
if (aotAssemblyNames.Count == 0)
|
||||
{
|
||||
throw new Exception($"no aot assembly found. please run `HybridCLR/Generate/All` or `HybridCLR/Generate/AotDlls` to generate aot dlls before runing `HybridCLR/Generate/MethodBridge`");
|
||||
}
|
||||
using (AssemblyReferenceDeepCollector collector = new AssemblyReferenceDeepCollector(MetaUtil.CreateAOTAssemblyResolver(target), aotAssemblyNames))
|
||||
List<string> hotUpdateDllNames = SettingsUtil.HotUpdateAssemblyNamesExcludePreserved;
|
||||
using (AssemblyReferenceDeepCollector collector = new AssemblyReferenceDeepCollector(MetaUtil.CreateHotUpdateAndAOTAssemblyResolver(target, hotUpdateDllNames), hotUpdateDllNames))
|
||||
{
|
||||
var analyzer = new Analyzer(new Analyzer.Options
|
||||
{
|
||||
@@ -71,8 +64,18 @@ namespace HybridCLR.Editor.Commands
|
||||
});
|
||||
|
||||
analyzer.Run();
|
||||
string outputFile = $"{SettingsUtil.GeneratedCppDir}/MethodBridge.cpp";
|
||||
GenerateMethodBridgeCppFile(analyzer, outputFile);
|
||||
|
||||
var tasks = new List<Task>();
|
||||
string templateCode = File.ReadAllText($"{SettingsUtil.TemplatePathInPackage}/MethodBridgeStub.cpp");
|
||||
foreach (PlatformABI platform in Enum.GetValues(typeof(PlatformABI)))
|
||||
{
|
||||
string outputFile = $"{SettingsUtil.GeneratedCppDir}/MethodBridge_{platform}.cpp";
|
||||
tasks.Add(Task.Run(() =>
|
||||
{
|
||||
GenerateMethodBridgeCppFile(analyzer, platform, templateCode, outputFile);
|
||||
}));
|
||||
}
|
||||
Task.WaitAll(tasks.ToArray());
|
||||
}
|
||||
|
||||
CleanIl2CppBuildCache();
|
||||
|
||||
@@ -23,7 +23,7 @@ namespace HybridCLR.Editor.Commands
|
||||
LinkGeneratorCommand.GenerateLinkXml(target);
|
||||
|
||||
// 生成裁剪后的aot dll
|
||||
StripAOTDllCommand.GenerateStripedAOTDlls(target);
|
||||
StripAOTDllCommand.GenerateStripedAOTDlls(target, EditorUserBuildSettings.selectedBuildTargetGroup);
|
||||
|
||||
// 桥接函数生成依赖于AOT dll,必须保证已经build过,生成AOT dll
|
||||
MethodBridgeGeneratorCommand.GenerateMethodBridge(target);
|
||||
|
||||
@@ -35,13 +35,17 @@ namespace HybridCLR.Editor.Commands
|
||||
var analyzer = new ReversePInvokeWrap.Analyzer(cache, hotUpdateDlls);
|
||||
analyzer.Run();
|
||||
|
||||
string outputFile = $"{SettingsUtil.GeneratedCppDir}/ReversePInvokeMethodStub.cpp";
|
||||
|
||||
List<ABIReversePInvokeMethodInfo> methods = analyzer.BuildABIMethods();
|
||||
Debug.Log($"GenerateReversePInvokeWrapper. wraperCount:{methods.Sum(m => m.Count)} output:{outputFile}");
|
||||
var generator = new Generator();
|
||||
generator.Generate(methods, outputFile);
|
||||
Debug.LogFormat("[ReversePInvokeWrapperGeneratorCommand] output:{0}", outputFile);
|
||||
string templateCode = File.ReadAllText($"{SettingsUtil.TemplatePathInPackage}/ReversePInvokeMethodStub.cpp");
|
||||
foreach (PlatformABI abi in Enum.GetValues(typeof(PlatformABI)))
|
||||
{
|
||||
string outputFile = $"{SettingsUtil.GeneratedCppDir}/ReversePInvokeMethodStub_{abi}.cpp";
|
||||
|
||||
List<ABIReversePInvokeMethodInfo> methods = analyzer.BuildABIMethods(abi);
|
||||
Debug.Log($"GenerateReversePInvokeWrapper. abi:{abi} wraperCount:{methods.Sum(m => m.Count)} output:{outputFile}");
|
||||
var generator = new Generator();
|
||||
generator.Generate(templateCode, abi, methods, outputFile);
|
||||
}
|
||||
}
|
||||
MethodBridgeGeneratorCommand.CleanIl2CppBuildCache();
|
||||
}
|
||||
|
||||
@@ -3,12 +3,10 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
using static UnityEngine.Networking.UnityWebRequest;
|
||||
|
||||
namespace HybridCLR.Editor.Commands
|
||||
{
|
||||
@@ -17,38 +15,7 @@ namespace HybridCLR.Editor.Commands
|
||||
[MenuItem("HybridCLR/Generate/AOTDlls", priority = 105)]
|
||||
public static void GenerateStripedAOTDlls()
|
||||
{
|
||||
GenerateStripedAOTDlls(EditorUserBuildSettings.activeBuildTarget);
|
||||
}
|
||||
|
||||
static BuildOptions GetBuildPlayerOptions(BuildTarget buildTarget)
|
||||
{
|
||||
BuildOptions options = BuildOptions.None;
|
||||
bool development = EditorUserBuildSettings.development;
|
||||
if (development)
|
||||
{
|
||||
options |= BuildOptions.Development;
|
||||
}
|
||||
|
||||
if (EditorUserBuildSettings.allowDebugging && development)
|
||||
{
|
||||
options |= BuildOptions.AllowDebugging;
|
||||
}
|
||||
|
||||
if (EditorUserBuildSettings.connectProfiler && (development || buildTarget == BuildTarget.WSAPlayer))
|
||||
{
|
||||
options |= BuildOptions.ConnectWithProfiler;
|
||||
}
|
||||
|
||||
if (EditorUserBuildSettings.buildWithDeepProfilingSupport && development)
|
||||
{
|
||||
options |= BuildOptions.EnableDeepProfilingSupport;
|
||||
}
|
||||
|
||||
#if UNITY_2021_2_OR_NEWER
|
||||
options |= BuildOptions.CleanBuildCache;
|
||||
#endif
|
||||
|
||||
return options;
|
||||
GenerateStripedAOTDlls(EditorUserBuildSettings.activeBuildTarget, EditorUserBuildSettings.selectedBuildTargetGroup);
|
||||
}
|
||||
|
||||
private static string GetLocationPathName(string buildDir, BuildTarget target)
|
||||
@@ -56,21 +23,21 @@ namespace HybridCLR.Editor.Commands
|
||||
switch(target)
|
||||
{
|
||||
case BuildTarget.StandaloneWindows:
|
||||
case BuildTarget.StandaloneWindows64: return $"{buildDir}/{PlayerSettings.productName}.exe";
|
||||
case BuildTarget.StandaloneWindows64: return $"{buildDir}/{target}";
|
||||
case BuildTarget.StandaloneOSX: return buildDir;
|
||||
case BuildTarget.iOS: return buildDir;
|
||||
case BuildTarget.Android: return buildDir;
|
||||
case BuildTarget.StandaloneLinux64: return $"{buildDir}/{PlayerSettings.productName}";
|
||||
case BuildTarget.StandaloneLinux64: return buildDir;
|
||||
default: return buildDir;
|
||||
}
|
||||
}
|
||||
|
||||
public static void GenerateStripedAOTDlls(BuildTarget target)
|
||||
public static void GenerateStripedAOTDlls(BuildTarget target, BuildTargetGroup group)
|
||||
{
|
||||
string outputPath = $"{SettingsUtil.HybridCLRDataDir}/StrippedAOTDllsTempProj/{target}";
|
||||
BashUtil.RemoveDir(outputPath);
|
||||
|
||||
var buildOptions = GetBuildPlayerOptions(target);
|
||||
var buildOptions = BuildOptions.BuildScriptsOnly;
|
||||
#if UNITY_2021_2_OR_NEWER
|
||||
buildOptions |= BuildOptions.CleanBuildCache;
|
||||
#endif
|
||||
@@ -80,17 +47,10 @@ namespace HybridCLR.Editor.Commands
|
||||
bool oldCreateSolution = UnityEditor.OSXStandalone.UserBuildSettings.createXcodeProject;
|
||||
#elif UNITY_EDITOR_WIN
|
||||
bool oldCreateSolution = UnityEditor.WindowsStandalone.UserBuildSettings.createSolution;
|
||||
#endif
|
||||
#if TUANJIE_2022_3_OR_NEWER
|
||||
bool oldOpenHarmonyProj = EditorUserBuildSettings.exportAsOpenHarmonyProject;
|
||||
#endif
|
||||
bool oldBuildScriptsOnly = EditorUserBuildSettings.buildScriptsOnly;
|
||||
EditorUserBuildSettings.buildScriptsOnly = true;
|
||||
|
||||
string location = GetLocationPathName(outputPath, target);
|
||||
string oldBuildLocation = EditorUserBuildSettings.GetBuildLocation(target);
|
||||
EditorUserBuildSettings.SetBuildLocation(target, location);
|
||||
|
||||
switch (target)
|
||||
{
|
||||
case BuildTarget.StandaloneWindows:
|
||||
@@ -108,39 +68,25 @@ namespace HybridCLR.Editor.Commands
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
#if TUANJIE_2022_3_OR_NEWER
|
||||
case BuildTarget.HMIAndroid:
|
||||
#endif
|
||||
case BuildTarget.Android:
|
||||
{
|
||||
EditorUserBuildSettings.exportAsGoogleAndroidProject = true;
|
||||
break;
|
||||
}
|
||||
#if TUANJIE_2022_3_OR_NEWER
|
||||
case BuildTarget.OpenHarmony:
|
||||
{
|
||||
EditorUserBuildSettings.exportAsOpenHarmonyProject = true;
|
||||
break;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
Debug.Log($"GenerateStripedAOTDlls build option:{buildOptions}");
|
||||
|
||||
BuildPlayerOptions buildPlayerOptions = new BuildPlayerOptions()
|
||||
{
|
||||
scenes = EditorBuildSettings.scenes.Where(s => s.enabled).Select(s => s.path).ToArray(),
|
||||
locationPathName = location,
|
||||
locationPathName = GetLocationPathName(outputPath, target),
|
||||
options = buildOptions,
|
||||
target = target,
|
||||
targetGroup = BuildPipeline.GetBuildTargetGroup(target),
|
||||
targetGroup = group,
|
||||
};
|
||||
|
||||
var report = BuildPipeline.BuildPlayer(buildPlayerOptions);
|
||||
|
||||
EditorUserBuildSettings.buildScriptsOnly = oldBuildScriptsOnly;
|
||||
EditorUserBuildSettings.SetBuildLocation(target, oldBuildLocation);
|
||||
|
||||
switch (target)
|
||||
{
|
||||
case BuildTarget.StandaloneWindows:
|
||||
@@ -158,28 +104,18 @@ namespace HybridCLR.Editor.Commands
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
#if TUANJIE_2022_3_OR_NEWER
|
||||
case BuildTarget.HMIAndroid:
|
||||
#endif
|
||||
case BuildTarget.Android:
|
||||
{
|
||||
EditorUserBuildSettings.exportAsGoogleAndroidProject = oldExportAndroidProj;
|
||||
break;
|
||||
}
|
||||
#if TUANJIE_2022_3_OR_NEWER
|
||||
case BuildTarget.OpenHarmony:
|
||||
{
|
||||
EditorUserBuildSettings.exportAsOpenHarmonyProject = oldOpenHarmonyProj;
|
||||
break;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
if (report.summary.result != UnityEditor.Build.Reporting.BuildResult.Succeeded)
|
||||
{
|
||||
throw new Exception("GenerateStripedAOTDlls failed");
|
||||
throw new Exception("GenerateStripedAOTDlls 失败");
|
||||
}
|
||||
Debug.Log($"GenerateStripedAOTDlls target:{target} path:{outputPath}");
|
||||
Debug.Log($"GenerateStripedAOTDlls target:{target} group:{group} path:{outputPath}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,96 +0,0 @@
|
||||
using dnlib.DotNet;
|
||||
using HybridCLR.Editor.Meta;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace HybridCLR.Editor.HotUpdate
|
||||
{
|
||||
public class MissingMetadataChecker
|
||||
{
|
||||
private readonly HashSet<string> _aotAssNames;
|
||||
|
||||
private readonly AssemblyCache _assCache;
|
||||
|
||||
public MissingMetadataChecker(string aotDllDir, IEnumerable<string> excludeDllNames)
|
||||
{
|
||||
|
||||
var excludeDllNameSet = new HashSet<string>(excludeDllNames ?? new List<string>());
|
||||
_aotAssNames = new HashSet<string>();
|
||||
foreach (var aotFile in Directory.GetFiles(aotDllDir, "*.dll"))
|
||||
{
|
||||
string aotAssName = Path.GetFileNameWithoutExtension(aotFile);
|
||||
if (excludeDllNameSet.Contains(aotAssName))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
_aotAssNames.Add(aotAssName);
|
||||
}
|
||||
_assCache = new AssemblyCache(new PathAssemblyResolver(aotDllDir));
|
||||
}
|
||||
|
||||
public bool Check(string hotUpdateDllPath)
|
||||
{
|
||||
ModuleDef mod = ModuleDefMD.Load(File.ReadAllBytes(hotUpdateDllPath), _assCache.ModCtx);
|
||||
|
||||
foreach (var refass in mod.GetAssemblyRefs())
|
||||
{
|
||||
string refAssName = refass.Name;
|
||||
if (_aotAssNames.Contains(refAssName))
|
||||
{
|
||||
_assCache.LoadModule(refass.Name, true);
|
||||
}
|
||||
}
|
||||
|
||||
bool anyMissing = false;
|
||||
|
||||
foreach (TypeRef typeRef in mod.GetTypeRefs())
|
||||
{
|
||||
string defAssName = typeRef.DefinitionAssembly.Name;
|
||||
if (!_aotAssNames.Contains(defAssName))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if (typeRef.ResolveTypeDef() == null)
|
||||
{
|
||||
UnityEngine.Debug.LogError($"Missing Type: {typeRef.FullName}");
|
||||
anyMissing = true;
|
||||
}
|
||||
}
|
||||
|
||||
foreach (IMethodDefOrRef methodRef in mod.GetMemberRefs())
|
||||
{
|
||||
if (methodRef.DeclaringType.DefinitionAssembly == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
string defAssName = methodRef.DeclaringType.DefinitionAssembly.Name;
|
||||
if (!_aotAssNames.Contains(defAssName))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if (methodRef.IsField)
|
||||
{
|
||||
|
||||
}
|
||||
else if (methodRef.IsMethod)
|
||||
{
|
||||
TypeSig declaringTypeSig = methodRef.DeclaringType.ToTypeSig();
|
||||
if (methodRef.ResolveMethodDef() == null)
|
||||
{
|
||||
if (declaringTypeSig.ElementType == ElementType.Array || declaringTypeSig.ElementType == ElementType.SZArray)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
UnityEngine.Debug.LogError($"Missing Method: {methodRef.FullName}");
|
||||
anyMissing = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return !anyMissing;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: bdd260aca2a6deb44b20210f01faa86b
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -60,16 +60,6 @@ namespace HybridCLR.Editor.Il2CppDef
|
||||
}
|
||||
}
|
||||
|
||||
#if TUANJIE_1_1_OR_NEWER
|
||||
var tuanjieMatch = Regex.Matches(Application.tuanjieVersion, @"(\d+)\.(\d+)\.(\d+)");
|
||||
int tuanjieMajorVer = int.Parse(tuanjieMatch[0].Groups[1].Value);
|
||||
int tuanjieMinorVer1 = int.Parse(tuanjieMatch[0].Groups[2].Value);
|
||||
int tuanjieMinorVer2 = int.Parse(tuanjieMatch[0].Groups[3].Value);
|
||||
lines.Add($"#define HYBRIDCLR_TUANJIE_VERSION {tuanjieMajorVer}{tuanjieMinorVer1.ToString("D2")}{tuanjieMinorVer2.ToString("D2")}");
|
||||
#elif TUANJIE_2022_3_OR_NEWER
|
||||
lines.Add($"#define HYBRIDCLR_TUANJIE_VERSION 10000");
|
||||
#endif
|
||||
|
||||
frr.Replace("UNITY_VERSION", string.Join("\n", lines));
|
||||
|
||||
frr.Commit(_options.OutputFile);
|
||||
|
||||
@@ -4,7 +4,6 @@ using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace HybridCLR.Editor.Installer
|
||||
@@ -64,34 +63,20 @@ namespace HybridCLR.Editor.Installer
|
||||
{
|
||||
UnityEngine.Debug.Log($"[BashUtil] RemoveDir dir:{dir}");
|
||||
}
|
||||
|
||||
int maxTryCount = 5;
|
||||
for (int i = 0; i < maxTryCount; ++i)
|
||||
if (!Directory.Exists(dir))
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!Directory.Exists(dir))
|
||||
{
|
||||
return;
|
||||
}
|
||||
foreach (var file in Directory.GetFiles(dir))
|
||||
{
|
||||
File.SetAttributes(file, FileAttributes.Normal);
|
||||
File.Delete(file);
|
||||
}
|
||||
foreach (var subDir in Directory.GetDirectories(dir))
|
||||
{
|
||||
RemoveDir(subDir);
|
||||
}
|
||||
Directory.Delete(dir);
|
||||
break;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
UnityEngine.Debug.LogError($"[BashUtil] RemoveDir:{dir} with exception:{e}. try count:{i}");
|
||||
Thread.Sleep(100);
|
||||
}
|
||||
return;
|
||||
}
|
||||
foreach (var file in Directory.GetFiles(dir))
|
||||
{
|
||||
File.SetAttributes(file, FileAttributes.Normal);
|
||||
File.Delete(file);
|
||||
}
|
||||
foreach (var subDir in Directory.GetDirectories(dir))
|
||||
{
|
||||
RemoveDir(subDir);
|
||||
}
|
||||
Directory.Delete(dir);
|
||||
}
|
||||
|
||||
public static void RecreateDir(string dir)
|
||||
@@ -105,16 +90,12 @@ namespace HybridCLR.Editor.Installer
|
||||
|
||||
private static void CopyWithCheckLongFile(string srcFile, string dstFile)
|
||||
{
|
||||
var maxPathLength = 255;
|
||||
#if UNITY_EDITOR_OSX
|
||||
maxPathLength = 1024;
|
||||
#endif
|
||||
if (srcFile.Length > maxPathLength)
|
||||
if (srcFile.Length > 255)
|
||||
{
|
||||
UnityEngine.Debug.LogError($"srcFile:{srcFile} path is too long. copy ignore!");
|
||||
return;
|
||||
}
|
||||
if (dstFile.Length > maxPathLength)
|
||||
if (dstFile.Length > 255)
|
||||
{
|
||||
UnityEngine.Debug.LogError($"dstFile:{dstFile} path is too long. copy ignore!");
|
||||
return;
|
||||
|
||||
@@ -1,16 +1,27 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Diagnostics;
|
||||
|
||||
using Debug = UnityEngine.Debug;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Linq;
|
||||
using HybridCLR.Editor.Settings;
|
||||
|
||||
namespace HybridCLR.Editor.Installer
|
||||
{
|
||||
public enum InstallErrorCode
|
||||
{
|
||||
Ok,
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
public class InstallerController
|
||||
{
|
||||
@@ -25,17 +36,11 @@ namespace HybridCLR.Editor.Installer
|
||||
private readonly HybridclrVersionManifest _versionManifest;
|
||||
private readonly HybridclrVersionInfo _curDefaultVersion;
|
||||
|
||||
public string PackageVersion { get; private set; }
|
||||
|
||||
public string InstalledLibil2cppVersion { get; private set; }
|
||||
|
||||
public InstallerController()
|
||||
{
|
||||
_curVersion = ParseUnityVersion(Application.unityVersion);
|
||||
_versionManifest = GetHybridCLRVersionManifest();
|
||||
_curDefaultVersion = _versionManifest.versions.FirstOrDefault(v => _curVersion.isTuanjieEngine ? v.unity_version == $"{_curVersion.major}-tuanjie" : v.unity_version == _curVersion.major.ToString());
|
||||
PackageVersion = LoadPackageInfo().version;
|
||||
InstalledLibil2cppVersion = ReadLocalVersion();
|
||||
_curDefaultVersion = _versionManifest.versions.Find(v => v.unity_version == _curVersion.major.ToString());
|
||||
}
|
||||
|
||||
private HybridclrVersionManifest GetHybridCLRVersionManifest()
|
||||
@@ -44,21 +49,6 @@ 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
|
||||
{
|
||||
@@ -88,7 +78,6 @@ namespace HybridCLR.Editor.Installer
|
||||
public int major;
|
||||
public int minor1;
|
||||
public int minor2;
|
||||
public bool isTuanjieEngine;
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
@@ -98,6 +87,10 @@ namespace HybridCLR.Editor.Installer
|
||||
|
||||
private static readonly Regex s_unityVersionPat = new Regex(@"(\d+)\.(\d+)\.(\d+)");
|
||||
|
||||
public const int min2019_4_CompatibleMinorVersion = 40;
|
||||
public const int min2020_3_CompatibleMinorVersion = 21;
|
||||
public const int min2021_3_CompatibleMinorVersion = 0;
|
||||
|
||||
private UnityVersion ParseUnityVersion(string versionStr)
|
||||
{
|
||||
var matches = s_unityVersionPat.Matches(versionStr);
|
||||
@@ -105,12 +98,13 @@ 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);
|
||||
bool isTuanjieEngine = versionStr.Contains("t");
|
||||
return new UnityVersion { major = major, minor1 = minor1, minor2 = minor2, isTuanjieEngine = isTuanjieEngine };
|
||||
return new UnityVersion { major = major, minor1 = minor1, minor2 = minor2 };
|
||||
}
|
||||
|
||||
public string GetCurrentUnityVersionMinCompatibleVersionStr()
|
||||
@@ -122,38 +116,49 @@ namespace HybridCLR.Editor.Installer
|
||||
{
|
||||
switch(majorVersion)
|
||||
{
|
||||
case 2019: return $"2019.4.0";
|
||||
case 2020: return $"2020.3.0";
|
||||
case 2021: return $"2021.3.0";
|
||||
case 2022: return $"2022.3.0";
|
||||
default: return $"2020.3.0";
|
||||
case 2019: return $"2019.4.{min2019_4_CompatibleMinorVersion}";
|
||||
case 2020: return $"2020.3.{min2020_3_CompatibleMinorVersion}";
|
||||
case 2021: return $"2021.3.{min2021_3_CompatibleMinorVersion}";
|
||||
default: throw new Exception($"not support version:{majorVersion}");
|
||||
}
|
||||
}
|
||||
|
||||
public enum CompatibleType
|
||||
{
|
||||
Compatible,
|
||||
MaybeIncompatible,
|
||||
Incompatible,
|
||||
}
|
||||
|
||||
public CompatibleType GetCompatibleType()
|
||||
public bool IsComaptibleVersion()
|
||||
{
|
||||
UnityVersion version = _curVersion;
|
||||
if (version == null)
|
||||
switch (version.major)
|
||||
{
|
||||
return CompatibleType.Incompatible;
|
||||
case 2019:
|
||||
{
|
||||
if (version.major != 2019 || version.minor1 != 4)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return version.minor2 >= min2019_4_CompatibleMinorVersion;
|
||||
}
|
||||
case 2020:
|
||||
{
|
||||
if (version.major != 2020 || version.minor1 != 3)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return version.minor2 >= min2020_3_CompatibleMinorVersion;
|
||||
}
|
||||
case 2021:
|
||||
{
|
||||
if (version.major != 2021 || version.minor1 != 3)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return version.minor2 >= min2021_3_CompatibleMinorVersion;
|
||||
}
|
||||
default: throw new Exception($"not support il2cpp_plus branch:{version.major}");
|
||||
}
|
||||
if ((version.major == 2019 && version.minor1 < 4) || (version.major >= 2020 && version.minor1 < 3))
|
||||
{
|
||||
return CompatibleType.MaybeIncompatible;
|
||||
}
|
||||
return CompatibleType.Compatible;
|
||||
}
|
||||
|
||||
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)
|
||||
@@ -163,24 +168,6 @@ namespace HybridCLR.Editor.Installer
|
||||
|
||||
public string ApplicationIl2cppPath => GetIl2CppPathByContentPath(EditorApplication.applicationContentsPath);
|
||||
|
||||
public string LocalVersionFile => $"{SettingsUtil.LocalIl2CppDir}/libil2cpp/hybridclr/generated/libil2cpp-version.txt";
|
||||
|
||||
private string ReadLocalVersion()
|
||||
{
|
||||
if (!File.Exists(LocalVersionFile))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
return File.ReadAllText(LocalVersionFile, Encoding.UTF8);
|
||||
}
|
||||
|
||||
public void WriteLocalVersion()
|
||||
{
|
||||
InstalledLibil2cppVersion = PackageVersion;
|
||||
File.WriteAllText(LocalVersionFile, PackageVersion, Encoding.UTF8);
|
||||
Debug.Log($"Write installed version:'{PackageVersion}' to {LocalVersionFile}");
|
||||
}
|
||||
|
||||
public void InstallDefaultHybridCLR()
|
||||
{
|
||||
InstallFromLocal(PrepareLibil2cppWithHybridclrFromGitRepo());
|
||||
@@ -191,6 +178,7 @@ namespace HybridCLR.Editor.Installer
|
||||
return Directory.Exists($"{SettingsUtil.LocalIl2CppDir}/libil2cpp/hybridclr");
|
||||
}
|
||||
|
||||
|
||||
private string GetUnityIl2CppDllInstallLocation()
|
||||
{
|
||||
#if UNITY_EDITOR_WIN
|
||||
@@ -203,9 +191,9 @@ namespace HybridCLR.Editor.Installer
|
||||
private string GetUnityIl2CppDllModifiedPath(string curVersionStr)
|
||||
{
|
||||
#if UNITY_EDITOR_WIN
|
||||
return $"{SettingsUtil.ProjectDir}/{SettingsUtil.HybridCLRDataPathInPackage}/ModifiedUnityAssemblies/{curVersionStr}/Unity.IL2CPP-Win.dll";
|
||||
return $"{SettingsUtil.ProjectDir}/{SettingsUtil.HybridCLRDataPathInPackage}/ModifiedUnityAssemblies/{curVersionStr}/Unity.IL2CPP-Win.dll.bytes";
|
||||
#else
|
||||
return $"{SettingsUtil.ProjectDir}/{SettingsUtil.HybridCLRDataPathInPackage}/ModifiedUnityAssemblies/{curVersionStr}/Unity.IL2CPP-Mac.dll";
|
||||
return $"{SettingsUtil.ProjectDir}/{SettingsUtil.HybridCLRDataPathInPackage}/ModifiedUnityAssemblies/{curVersionStr}/Unity.IL2CPP-Mac.dll.bytes";
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -252,13 +240,19 @@ namespace HybridCLR.Editor.Installer
|
||||
|
||||
private void RunInitLocalIl2CppData(string editorIl2cppPath, string libil2cppWithHybridclrSourceDir, UnityVersion version)
|
||||
{
|
||||
if (GetCompatibleType() == CompatibleType.Incompatible)
|
||||
if (!IsComaptibleVersion())
|
||||
{
|
||||
Debug.LogError($"Incompatible with current version, minimum compatible version: {GetCurrentUnityVersionMinCompatibleVersionStr()}");
|
||||
Debug.LogError($"il2cpp 版本不兼容,最小版本为 {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;
|
||||
@@ -276,6 +270,7 @@ namespace HybridCLR.Editor.Installer
|
||||
|
||||
// clean Il2cppBuildCache
|
||||
BashUtil.RemoveDir($"{SettingsUtil.ProjectDir}/Library/Il2cppBuildCache", true);
|
||||
|
||||
if (version.major == 2019)
|
||||
{
|
||||
string curVersionStr = version.ToString();
|
||||
@@ -288,17 +283,16 @@ namespace HybridCLR.Editor.Installer
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new Exception($"the modified Unity.IL2CPP.dll of {curVersionStr} isn't found. please install hybridclr in 2019.4.40 first, then switch to your unity version");
|
||||
Debug.LogError($"未找到当前版本:{curVersionStr} 对应的改造过的 Unity.IL2CPP.dll,打包出的程序将会崩溃");
|
||||
}
|
||||
}
|
||||
if (HasInstalledHybridCLR())
|
||||
{
|
||||
WriteLocalVersion();
|
||||
Debug.Log("Install Sucessfully");
|
||||
Debug.Log("安装成功");
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.LogError("Installation failed!");
|
||||
Debug.LogError("安装失败");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,65 +41,70 @@ namespace HybridCLR.Editor.Installer
|
||||
GUILayout.Space(10f);
|
||||
|
||||
EditorGUILayout.BeginVertical("box");
|
||||
EditorGUILayout.LabelField($"Installed: {hasInstall}", EditorStyles.boldLabel);
|
||||
EditorGUILayout.LabelField($"安装状态:{(hasInstall ? "已安装" : "未安装")}", EditorStyles.boldLabel);
|
||||
GUILayout.Space(10f);
|
||||
|
||||
EditorGUILayout.LabelField($"Package Version: v{_controller.PackageVersion}");
|
||||
EditorGUILayout.LabelField($"HybridCLR 版本: {_controller.HybridclrLocalVersion}");
|
||||
GUILayout.Space(5f);
|
||||
EditorGUILayout.LabelField($"Installed Version: v{_controller.InstalledLibil2cppVersion ?? " Unknown"}");
|
||||
EditorGUILayout.LabelField($"il2cpp_plus 版本: {_controller.Il2cppPlusLocalVersion}");
|
||||
GUILayout.Space(5f);
|
||||
|
||||
//GUIInstallButton("检查更新", "检查", UpdateHybridCLR);
|
||||
//GUILayout.Space(40f);
|
||||
|
||||
GUILayout.Space(10f);
|
||||
|
||||
InstallerController.CompatibleType compatibleType = _controller.GetCompatibleType();
|
||||
if (compatibleType != InstallerController.CompatibleType.Incompatible)
|
||||
{
|
||||
if (compatibleType == InstallerController.CompatibleType.MaybeIncompatible)
|
||||
{
|
||||
EditorGUILayout.HelpBox($"Maybe incompatible with current version, recommend minimum compatible version:{_controller.GetCurrentUnityVersionMinCompatibleVersionStr()}", MessageType.Warning);
|
||||
}
|
||||
|
||||
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($"Source libil2cpp:'{_installLibil2cppWithHybridclrSourceDir}' doesn't exist.");
|
||||
Debug.LogError($"本地libil2cpp复制目录不存在. '{_installLibil2cppWithHybridclrSourceDir}'");
|
||||
return;
|
||||
}
|
||||
if (!File.Exists($"{_installLibil2cppWithHybridclrSourceDir}/il2cpp-config.h") || !File.Exists($"{_installLibil2cppWithHybridclrSourceDir}/hybridclr/RuntimeApi.cpp"))
|
||||
{
|
||||
Debug.LogError($"Source libil2cpp:' {_installLibil2cppWithHybridclrSourceDir} ' is invalid");
|
||||
Debug.LogError($"本地libil2cpp不是合法有效的源码目录. '{_installLibil2cppWithHybridclrSourceDir}'");
|
||||
return;
|
||||
}
|
||||
_controller.InstallFromLocal(_installLibil2cppWithHybridclrSourceDir);
|
||||
|
||||
@@ -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) => String.Compare(a.Key, b.Key, StringComparison.Ordinal));
|
||||
typesByAssembly.Sort((a, b) => a.Key.CompareTo(b.Key));
|
||||
|
||||
foreach(var assembly in typesByAssembly)
|
||||
{
|
||||
writer.WriteStartElement("assembly");
|
||||
writer.WriteAttributeString("fullname", assembly.Key);
|
||||
List<string> assTypeNames = assembly.Select(t => t.FullName).ToList();
|
||||
assTypeNames.Sort(string.CompareOrdinal);
|
||||
foreach(var typeName in assTypeNames)
|
||||
List<TypeRef> assTypes = assembly.ToList();
|
||||
assTypes.Sort((a, b) => a.FullName.CompareTo(b.FullName));
|
||||
foreach(var type in assTypes)
|
||||
{
|
||||
writer.WriteStartElement("type");
|
||||
writer.WriteAttributeString("fullname", typeName);
|
||||
writer.WriteAttributeString("fullname", type.FullName);
|
||||
writer.WriteAttributeString("preserve", "all");
|
||||
writer.WriteEndElement();
|
||||
}
|
||||
|
||||
@@ -9,12 +9,73 @@ using UnityEngine;
|
||||
|
||||
namespace HybridCLR.Editor.Meta
|
||||
{
|
||||
public class AssemblyCache : AssemblyCacheBase
|
||||
public class AssemblyCache : IDisposable
|
||||
{
|
||||
private readonly IAssemblyResolver _assemblyPathResolver;
|
||||
private readonly ModuleContext _modCtx;
|
||||
private readonly AssemblyResolver _asmResolver;
|
||||
private bool disposedValue;
|
||||
|
||||
public AssemblyCache(IAssemblyResolver assemblyResolver) : base(assemblyResolver)
|
||||
public Dictionary<string, ModuleDefMD> LoadedModules { get; } = new Dictionary<string, ModuleDefMD>();
|
||||
|
||||
public AssemblyCache(IAssemblyResolver assemblyResolver)
|
||||
{
|
||||
_assemblyPathResolver = assemblyResolver;
|
||||
_modCtx = ModuleDef.CreateModuleContext();
|
||||
_asmResolver = (AssemblyResolver)_modCtx.AssemblyResolver;
|
||||
_asmResolver.EnableTypeDefCache = true;
|
||||
_asmResolver.UseGAC = false;
|
||||
}
|
||||
|
||||
public ModuleDefMD LoadModule(string moduleName, bool loadReferenceAssemblies = true)
|
||||
{
|
||||
// Debug.Log($"load module:{moduleName}");
|
||||
if (LoadedModules.TryGetValue(moduleName, out var mod))
|
||||
{
|
||||
return mod;
|
||||
}
|
||||
mod = DoLoadModule(_assemblyPathResolver.ResolveAssembly(moduleName, true));
|
||||
LoadedModules.Add(moduleName, mod);
|
||||
|
||||
if (loadReferenceAssemblies)
|
||||
{
|
||||
foreach (var refAsm in mod.GetAssemblyRefs())
|
||||
{
|
||||
LoadModule(refAsm.Name);
|
||||
}
|
||||
}
|
||||
|
||||
return mod;
|
||||
}
|
||||
|
||||
private ModuleDefMD DoLoadModule(string dllPath)
|
||||
{
|
||||
//Debug.Log($"do load module:{dllPath}");
|
||||
ModuleDefMD mod = ModuleDefMD.Load(dllPath, _modCtx);
|
||||
_asmResolver.AddToCache(mod);
|
||||
return mod;
|
||||
}
|
||||
|
||||
protected virtual void Dispose(bool disposing)
|
||||
{
|
||||
if (!disposedValue)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
foreach(var mod in LoadedModules.Values)
|
||||
{
|
||||
mod.Dispose();
|
||||
}
|
||||
LoadedModules.Clear();
|
||||
}
|
||||
disposedValue = true;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(disposing: true);
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,123 +0,0 @@
|
||||
using dnlib.DotNet;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace HybridCLR.Editor.Meta
|
||||
{
|
||||
public abstract class AssemblyCacheBase : IDisposable
|
||||
{
|
||||
private readonly IAssemblyResolver _assemblyPathResolver;
|
||||
private readonly ModuleContext _modCtx;
|
||||
private readonly AssemblyResolver _asmResolver;
|
||||
private bool disposedValue;
|
||||
private bool _loadedNetstandard;
|
||||
|
||||
|
||||
public ModuleContext ModCtx => _modCtx;
|
||||
|
||||
public Dictionary<string, ModuleDefMD> LoadedModules { get; } = new Dictionary<string, ModuleDefMD>();
|
||||
|
||||
private readonly List<ModuleDefMD> _loadedModulesIncludeNetstandard = new List<ModuleDefMD>();
|
||||
|
||||
protected AssemblyCacheBase(IAssemblyResolver assemblyResolver)
|
||||
{
|
||||
_assemblyPathResolver = assemblyResolver;
|
||||
_modCtx = ModuleDef.CreateModuleContext();
|
||||
_asmResolver = (AssemblyResolver)_modCtx.AssemblyResolver;
|
||||
_asmResolver.EnableTypeDefCache = true;
|
||||
_asmResolver.UseGAC = false;
|
||||
}
|
||||
|
||||
|
||||
public ModuleDefMD TryLoadModule(string moduleName, bool loadReferenceAssemblies = true)
|
||||
{
|
||||
string dllPath = _assemblyPathResolver.ResolveAssembly(moduleName, false);
|
||||
if (string.IsNullOrEmpty(dllPath))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
return LoadModule(moduleName, loadReferenceAssemblies);
|
||||
}
|
||||
|
||||
public ModuleDefMD LoadModule(string moduleName, bool loadReferenceAssemblies = true)
|
||||
{
|
||||
// Debug.Log($"load module:{moduleName}");
|
||||
if (LoadedModules.TryGetValue(moduleName, out var mod))
|
||||
{
|
||||
return mod;
|
||||
}
|
||||
if (moduleName == "netstandard")
|
||||
{
|
||||
if (!_loadedNetstandard)
|
||||
{
|
||||
LoadNetStandard();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
mod = DoLoadModule(_assemblyPathResolver.ResolveAssembly(moduleName, true));
|
||||
LoadedModules.Add(moduleName, mod);
|
||||
|
||||
if (loadReferenceAssemblies)
|
||||
{
|
||||
foreach (var refAsm in mod.GetAssemblyRefs())
|
||||
{
|
||||
LoadModule(refAsm.Name);
|
||||
}
|
||||
}
|
||||
|
||||
return mod;
|
||||
}
|
||||
|
||||
private void LoadNetStandard()
|
||||
{
|
||||
string netstandardDllPath = _assemblyPathResolver.ResolveAssembly("netstandard", false);
|
||||
if (!string.IsNullOrEmpty(netstandardDllPath))
|
||||
{
|
||||
DoLoadModule(netstandardDllPath);
|
||||
}
|
||||
else
|
||||
{
|
||||
DoLoadModule(MetaUtil.ResolveNetStandardAssemblyPath("netstandard2.0"));
|
||||
DoLoadModule(MetaUtil.ResolveNetStandardAssemblyPath("netstandard2.1"));
|
||||
}
|
||||
_loadedNetstandard = true;
|
||||
}
|
||||
|
||||
private ModuleDefMD DoLoadModule(string dllPath)
|
||||
{
|
||||
//Debug.Log($"do load module:{dllPath}");
|
||||
ModuleDefMD mod = ModuleDefMD.Load(File.ReadAllBytes(dllPath), _modCtx);
|
||||
mod.EnableTypeDefFindCache = true;
|
||||
_asmResolver.AddToCache(mod);
|
||||
_loadedModulesIncludeNetstandard.Add(mod);
|
||||
return mod;
|
||||
}
|
||||
|
||||
protected virtual void Dispose(bool disposing)
|
||||
{
|
||||
if (!disposedValue)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
foreach (var mod in _loadedModulesIncludeNetstandard)
|
||||
{
|
||||
mod.Dispose();
|
||||
}
|
||||
_loadedModulesIncludeNetstandard.Clear();
|
||||
LoadedModules.Clear();
|
||||
}
|
||||
disposedValue = true;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(disposing: true);
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 3b01fa99119e72141bfee5628c0ffce1
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -9,10 +9,17 @@ using UnityEngine;
|
||||
|
||||
namespace HybridCLR.Editor.Meta
|
||||
{
|
||||
public class AssemblyReferenceDeepCollector : AssemblyCacheBase
|
||||
public class AssemblyReferenceDeepCollector : IDisposable
|
||||
{
|
||||
private readonly IAssemblyResolver _assemblyPathResolver;
|
||||
private readonly List<string> _rootAssemblies;
|
||||
|
||||
private readonly ModuleContext _modCtx;
|
||||
private readonly AssemblyResolver _asmResolver;
|
||||
private bool disposedValue;
|
||||
|
||||
public Dictionary<string, ModuleDefMD> LoadedModules { get; } = new Dictionary<string, ModuleDefMD>();
|
||||
|
||||
public IReadOnlyList<string> GetRootAssemblyNames()
|
||||
{
|
||||
return _rootAssemblies;
|
||||
@@ -23,19 +30,19 @@ namespace HybridCLR.Editor.Meta
|
||||
return LoadedModules.Where(e => !_rootAssemblies.Contains(e.Key)).Select(e => e.Value).ToList();
|
||||
}
|
||||
|
||||
public List<ModuleDefMD> GetLoadedModules()
|
||||
{
|
||||
return LoadedModules.Select(e => e.Value).ToList();
|
||||
}
|
||||
|
||||
public List<ModuleDefMD> GetLoadedModulesOfRootAssemblies()
|
||||
{
|
||||
return _rootAssemblies.Select(ass => LoadedModules[ass]).ToList();
|
||||
}
|
||||
|
||||
public AssemblyReferenceDeepCollector(IAssemblyResolver assemblyResolver, List<string> rootAssemblies) : base(assemblyResolver)
|
||||
public AssemblyReferenceDeepCollector(IAssemblyResolver assemblyResolver, List<string> rootAssemblies)
|
||||
{
|
||||
_assemblyPathResolver = assemblyResolver;
|
||||
_rootAssemblies = rootAssemblies;
|
||||
_modCtx = ModuleDef.CreateModuleContext();
|
||||
_asmResolver = (AssemblyResolver)_modCtx.AssemblyResolver;
|
||||
_asmResolver.EnableTypeDefCache = true;
|
||||
_asmResolver.UseGAC = false;
|
||||
LoadAllAssembiles();
|
||||
}
|
||||
|
||||
@@ -46,5 +53,52 @@ namespace HybridCLR.Editor.Meta
|
||||
LoadModule(asm);
|
||||
}
|
||||
}
|
||||
|
||||
private ModuleDefMD LoadModule(string moduleName)
|
||||
{
|
||||
// Debug.Log($"load module:{moduleName}");
|
||||
if (LoadedModules.TryGetValue(moduleName, out var mod))
|
||||
{
|
||||
return mod;
|
||||
}
|
||||
mod = DoLoadModule(_assemblyPathResolver.ResolveAssembly(moduleName, true));
|
||||
LoadedModules.Add(moduleName, mod);
|
||||
|
||||
foreach (var refAsm in mod.GetAssemblyRefs())
|
||||
{
|
||||
LoadModule(refAsm.Name);
|
||||
}
|
||||
return mod;
|
||||
}
|
||||
|
||||
private ModuleDefMD DoLoadModule(string dllPath)
|
||||
{
|
||||
//Debug.Log($"do load module:{dllPath}");
|
||||
ModuleDefMD mod = ModuleDefMD.Load(dllPath, _modCtx);
|
||||
_asmResolver.AddToCache(mod);
|
||||
return mod;
|
||||
}
|
||||
|
||||
protected virtual void Dispose(bool disposing)
|
||||
{
|
||||
if (!disposedValue)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
foreach(var mod in LoadedModules.Values)
|
||||
{
|
||||
mod.Dispose();
|
||||
}
|
||||
}
|
||||
LoadedModules.Clear();
|
||||
disposedValue = true;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(disposing: true);
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,11 +18,11 @@ namespace HybridCLR.Editor.Meta
|
||||
{
|
||||
if (SettingsUtil.HotUpdateAssemblyNamesIncludePreserved.Contains(assemblyName))
|
||||
{
|
||||
throw new Exception($"resolve Hot update dll:{assemblyName} failed! Please make sure that this hot update dll exists or the search path is configured in the external hot update path.");
|
||||
throw new Exception($"resolve 热更新 dll:{assemblyName} 失败!请确保已经编译了热更新dll或者外部热更新路径中配置了正确的值。更多请参阅常见错误文档");
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new Exception($"resolve AOT dll:{assemblyName} failed! Please make sure that the AOT project has referenced the dll and generated the trimmed AOT dll correctly.");
|
||||
throw new Exception($"resolve AOT dll:{assemblyName} 失败! 请确保主工程已经引用了该dll并且正确生成了裁剪后的AOT dll。更多请参阅常见错误文档");
|
||||
}
|
||||
}
|
||||
return null;
|
||||
|
||||
@@ -79,29 +79,7 @@ namespace HybridCLR.Editor.Meta
|
||||
|
||||
case ElementType.FnPtr:
|
||||
{
|
||||
var fptr = (FnPtrSig)typeSig;
|
||||
var cs = fptr.Signature;
|
||||
CallingConventionSig ccs;
|
||||
switch (cs)
|
||||
{
|
||||
case MethodSig ms:
|
||||
{
|
||||
ccs = new MethodSig(ms.GetCallingConvention(), ms.GenParamCount, Resolve(ms.RetType), ms.Params.Select(p => Resolve(p)).ToList());
|
||||
break;
|
||||
}
|
||||
case PropertySig ps:
|
||||
{
|
||||
ccs = new PropertySig(ps.HasThis, Resolve(ps.RetType));
|
||||
break;
|
||||
}
|
||||
case GenericInstMethodSig gims:
|
||||
{
|
||||
ccs = new GenericInstMethodSig(gims.GenericArguments.Select(ga => Resolve(ga)).ToArray());
|
||||
break;
|
||||
}
|
||||
default: throw new NotSupportedException(cs.ToString());
|
||||
}
|
||||
return new FnPtrSig(ccs);
|
||||
throw new NotSupportedException(typeSig.ToString());
|
||||
}
|
||||
|
||||
case ElementType.ValueArray:
|
||||
|
||||
@@ -22,7 +22,7 @@ namespace HybridCLR.Editor.Meta
|
||||
|
||||
public GenericClass ToGenericShare()
|
||||
{
|
||||
return new GenericClass(Type, MetaUtil.ToShareTypeSigs(Type.Module.CorLibTypes, KlassInst));
|
||||
return new GenericClass(Type, MetaUtil.ToShareTypeSigs(KlassInst));
|
||||
}
|
||||
|
||||
public override bool Equals(object obj)
|
||||
|
||||
@@ -26,8 +26,7 @@ namespace HybridCLR.Editor.Meta
|
||||
|
||||
public GenericMethod ToGenericShare()
|
||||
{
|
||||
ICorLibTypes corLibTypes = Method.Module.CorLibTypes;
|
||||
return new GenericMethod(Method, MetaUtil.ToShareTypeSigs(corLibTypes, KlassInst), MetaUtil.ToShareTypeSigs(corLibTypes, MethodInst));
|
||||
return new GenericMethod(Method, MetaUtil.ToShareTypeSigs(KlassInst), MetaUtil.ToShareTypeSigs(MethodInst));
|
||||
}
|
||||
|
||||
public override bool Equals(object obj)
|
||||
|
||||
+16
-51
@@ -1,6 +1,5 @@
|
||||
using dnlib.DotNet;
|
||||
using HybridCLR.Editor.Meta;
|
||||
using HybridCLR.Editor.Settings;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
@@ -60,8 +59,13 @@ namespace HybridCLR.Editor.Meta
|
||||
return ctx.Resolve(sig);
|
||||
}
|
||||
|
||||
public static TypeSig ToShareTypeSig(ICorLibTypes corTypes, TypeSig typeSig)
|
||||
public static TypeSig ToShareTypeSig(TypeSig typeSig)
|
||||
{
|
||||
var corTypes = typeSig?.Module?.CorLibTypes;
|
||||
if (corTypes == null)
|
||||
{
|
||||
return typeSig;
|
||||
}
|
||||
var a = typeSig.RemovePinnedAndModifiers();
|
||||
switch (a.ElementType)
|
||||
{
|
||||
@@ -84,43 +88,20 @@ namespace HybridCLR.Editor.Meta
|
||||
case ElementType.U: return corTypes.UIntPtr;
|
||||
case ElementType.Object: return corTypes.Object;
|
||||
case ElementType.Sentinel: return typeSig;
|
||||
case ElementType.Ptr: return corTypes.UIntPtr;
|
||||
case ElementType.ByRef: return corTypes.UIntPtr;
|
||||
case ElementType.Ptr: return corTypes.IntPtr;
|
||||
case ElementType.ByRef: return corTypes.IntPtr;
|
||||
case ElementType.SZArray: return corTypes.Object;
|
||||
case ElementType.Array: return corTypes.Object;
|
||||
case ElementType.ValueType:
|
||||
{
|
||||
TypeDef typeDef = a.ToTypeDefOrRef().ResolveTypeDef();
|
||||
if (typeDef == null)
|
||||
{
|
||||
throw new Exception($"type:{a} definition could not be found");
|
||||
}
|
||||
if (typeDef.IsEnum)
|
||||
{
|
||||
return ToShareTypeSig(corTypes, typeDef.GetEnumUnderlyingType());
|
||||
}
|
||||
return typeSig;
|
||||
}
|
||||
case ElementType.Var:
|
||||
case ElementType.MVar:
|
||||
case ElementType.ValueType: return typeSig;
|
||||
case ElementType.Class: return corTypes.Object;
|
||||
case ElementType.GenericInst:
|
||||
{
|
||||
var gia = (GenericInstSig)a;
|
||||
TypeDef typeDef = gia.GenericType.ToTypeDefOrRef().ResolveTypeDef();
|
||||
if (typeDef == null)
|
||||
{
|
||||
throw new Exception($"type:{a} definition could not be found");
|
||||
}
|
||||
if (typeDef.IsEnum)
|
||||
{
|
||||
return ToShareTypeSig(corTypes, typeDef.GetEnumUnderlyingType());
|
||||
}
|
||||
if (!typeDef.IsValueType)
|
||||
{
|
||||
return corTypes.Object;
|
||||
}
|
||||
return new GenericInstSig(gia.GenericType, gia.GenericArguments.Select(ga => ToShareTypeSig(corTypes, ga)).ToList());
|
||||
if (gia.GenericType.IsClassSig)
|
||||
{
|
||||
return corTypes.Object;
|
||||
}
|
||||
return new GenericInstSig(gia.GenericType, gia.GenericArguments.Select(ga => ToShareTypeSig(ga)).ToList());
|
||||
}
|
||||
case ElementType.FnPtr: return corTypes.IntPtr;
|
||||
case ElementType.ValueArray: return typeSig;
|
||||
@@ -130,13 +111,13 @@ namespace HybridCLR.Editor.Meta
|
||||
}
|
||||
}
|
||||
|
||||
public static List<TypeSig> ToShareTypeSigs(ICorLibTypes corTypes, IList<TypeSig> typeSigs)
|
||||
public static List<TypeSig> ToShareTypeSigs(IList<TypeSig> typeSigs)
|
||||
{
|
||||
if (typeSigs == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
return typeSigs.Select(s => ToShareTypeSig(corTypes, s)).ToList();
|
||||
return typeSigs.Select(s => ToShareTypeSig(s)).ToList();
|
||||
}
|
||||
|
||||
public static IAssemblyResolver CreateHotUpdateAssemblyResolver(BuildTarget target, List<string> hotUpdateDlls)
|
||||
@@ -172,22 +153,6 @@ namespace HybridCLR.Editor.Meta
|
||||
CreateHotUpdateAssemblyResolver(target, hotUpdateDlls),
|
||||
CreateAOTAssemblyResolver(target)
|
||||
);
|
||||
}
|
||||
|
||||
public static string ResolveNetStandardAssemblyPath(string assemblyName)
|
||||
{
|
||||
return $"{SettingsUtil.HybridCLRDataPathInPackage}/NetStandard/{assemblyName}.dll";
|
||||
}
|
||||
|
||||
|
||||
public static List<TypeSig> CreateDefaultGenericParams(ModuleDef module, int genericParamCount)
|
||||
{
|
||||
var methodGenericParams = new List<TypeSig>();
|
||||
for (int i = 0; i < genericParamCount; i++)
|
||||
{
|
||||
methodGenericParams.Add(module.CorLibTypes.Object);
|
||||
}
|
||||
return methodGenericParams;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
using dnlib.DotNet;
|
||||
using HybridCLR.Editor.ABI;
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
@@ -11,17 +10,26 @@ namespace HybridCLR.Editor.Meta
|
||||
{
|
||||
public class MethodReferenceAnalyzer
|
||||
{
|
||||
private readonly Action<MethodDef, List<TypeSig>, List<TypeSig>, GenericMethod> _onNewMethod;
|
||||
private readonly Action<GenericMethod> _onNewMethod;
|
||||
|
||||
private readonly ConcurrentDictionary<MethodDef, List<IMethod>> _methodEffectInsts = new ConcurrentDictionary<MethodDef, List<IMethod>>();
|
||||
|
||||
public MethodReferenceAnalyzer(Action<MethodDef, List<TypeSig>, List<TypeSig>, GenericMethod> onNewMethod)
|
||||
public MethodReferenceAnalyzer(Action<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))
|
||||
@@ -29,7 +37,7 @@ namespace HybridCLR.Editor.Meta
|
||||
foreach (var met in effectInsts)
|
||||
{
|
||||
var resolveMet = GenericMethod.ResolveMethod(met, ctx)?.ToGenericShare();
|
||||
_onNewMethod(method, klassGenericInst, methodGenericInst, resolveMet);
|
||||
_onNewMethod(resolveMet);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -61,7 +69,7 @@ namespace HybridCLR.Editor.Meta
|
||||
continue;
|
||||
}
|
||||
effectInsts.Add(met);
|
||||
_onNewMethod(method, klassGenericInst, methodGenericInst, resolveMet);
|
||||
_onNewMethod(resolveMet);
|
||||
break;
|
||||
}
|
||||
case ITokenOperand token:
|
||||
|
||||
@@ -25,6 +25,7 @@ namespace HybridCLR.Editor.MethodBridge
|
||||
private readonly object _lock = new object();
|
||||
|
||||
private readonly List<TypeDef> _typeDefs = new List<TypeDef>();
|
||||
private readonly List<MethodDef> _notGenericMethods = new List<MethodDef>();
|
||||
|
||||
private readonly HashSet<GenericClass> _genericTypes = new HashSet<GenericClass>();
|
||||
private readonly HashSet<GenericMethod> _genericMethods = new HashSet<GenericMethod>();
|
||||
@@ -34,6 +35,8 @@ namespace HybridCLR.Editor.MethodBridge
|
||||
|
||||
public IReadOnlyList<TypeDef> TypeDefs => _typeDefs;
|
||||
|
||||
public IReadOnlyList<MethodDef> NotGenericMethods => _notGenericMethods;
|
||||
|
||||
public IReadOnlyCollection<GenericClass> GenericTypes => _genericTypes;
|
||||
|
||||
public IReadOnlyCollection<GenericMethod> GenericMethods => _genericMethods;
|
||||
@@ -56,7 +59,7 @@ namespace HybridCLR.Editor.MethodBridge
|
||||
}
|
||||
lock(_lock)
|
||||
{
|
||||
gc = StandardizeClass(gc);
|
||||
gc = gc.ToGenericShare();
|
||||
if (_genericTypes.Add(gc))
|
||||
{
|
||||
WalkType(gc);
|
||||
@@ -64,28 +67,10 @@ namespace HybridCLR.Editor.MethodBridge
|
||||
}
|
||||
}
|
||||
|
||||
private GenericClass StandardizeClass(GenericClass gc)
|
||||
{
|
||||
TypeDef typeDef = gc.Type;
|
||||
ICorLibTypes corLibTypes = typeDef.Module.CorLibTypes;
|
||||
List<TypeSig> klassGenericParams = gc.KlassInst != null ? MetaUtil.ToShareTypeSigs(corLibTypes, gc.KlassInst) : (typeDef.GenericParameters.Count > 0 ? MetaUtil.CreateDefaultGenericParams(typeDef.Module, typeDef.GenericParameters.Count) : null);
|
||||
return new GenericClass(typeDef, klassGenericParams);
|
||||
}
|
||||
|
||||
private GenericMethod StandardizeMethod(GenericMethod gm)
|
||||
{
|
||||
TypeDef typeDef = gm.Method.DeclaringType;
|
||||
ICorLibTypes corLibTypes = typeDef.Module.CorLibTypes;
|
||||
List<TypeSig> klassGenericParams = gm.KlassInst != null ? MetaUtil.ToShareTypeSigs(corLibTypes, gm.KlassInst) : (typeDef.GenericParameters.Count > 0 ? MetaUtil.CreateDefaultGenericParams(typeDef.Module, typeDef.GenericParameters.Count) : null);
|
||||
List<TypeSig> methodGenericParams = gm.MethodInst != null ? MetaUtil.ToShareTypeSigs(corLibTypes, gm.MethodInst) : (gm.Method.GenericParameters.Count > 0 ? MetaUtil.CreateDefaultGenericParams(typeDef.Module, gm.Method.GenericParameters.Count) : null);
|
||||
return new GenericMethod(gm.Method, klassGenericParams, methodGenericParams);
|
||||
}
|
||||
|
||||
private void OnNewMethod(MethodDef methodDef, List<TypeSig> klassGenericInst, List<TypeSig> methodGenericInst, GenericMethod method)
|
||||
private void OnNewMethod(GenericMethod method)
|
||||
{
|
||||
lock(_lock)
|
||||
{
|
||||
method = StandardizeMethod(method);
|
||||
if (_genericMethods.Add(method))
|
||||
{
|
||||
_newMethods.Add(method);
|
||||
@@ -109,7 +94,11 @@ namespace HybridCLR.Editor.MethodBridge
|
||||
}
|
||||
foreach (var method in gc.Type.Methods)
|
||||
{
|
||||
var gm = StandardizeMethod(new GenericMethod(method, gc.KlassInst, null));
|
||||
if (method.HasGenericParameters)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
var gm = new GenericMethod(method, gc.KlassInst, null).ToGenericShare();
|
||||
//Debug.Log($"add method:{gm.Method} {gm.KlassInst}");
|
||||
|
||||
if (_genericMethods.Add(gm))
|
||||
@@ -134,8 +123,7 @@ namespace HybridCLR.Editor.MethodBridge
|
||||
foreach (var method in typeDef.Methods)
|
||||
{
|
||||
// 对于带泛型的参数,统一泛型共享为object
|
||||
var gm = StandardizeMethod(new GenericMethod(method, null, null));
|
||||
_genericMethods.Add(gm);
|
||||
_notGenericMethods.Add(method);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -143,7 +131,7 @@ namespace HybridCLR.Editor.MethodBridge
|
||||
{
|
||||
// 将所有非泛型函数全部加入函数列表,同时立马walk这些method。
|
||||
// 后续迭代中将只遍历MethodSpec
|
||||
foreach (var ass in _assemblyCollector.GetLoadedModules())
|
||||
foreach (var ass in _assemblyCollector.GetLoadedModulesExcludeRootAssemblies())
|
||||
{
|
||||
foreach (TypeDef typeDef in ass.GetTypes())
|
||||
{
|
||||
@@ -153,29 +141,40 @@ namespace HybridCLR.Editor.MethodBridge
|
||||
for (uint rid = 1, n = ass.Metadata.TablesStream.TypeSpecTable.Rows; rid <= n; rid++)
|
||||
{
|
||||
var ts = ass.ResolveTypeSpec(rid);
|
||||
var cs = GenericClass.ResolveClass(ts, null);
|
||||
if (cs != null)
|
||||
if (!ts.ContainsGenericParameter)
|
||||
{
|
||||
TryAddAndWalkGenericType(cs);
|
||||
var cs = GenericClass.ResolveClass(ts, null)?.ToGenericShare();
|
||||
if (cs != null)
|
||||
{
|
||||
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)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
gm = StandardizeMethod(gm);
|
||||
|
||||
if (_genericMethods.Add(gm))
|
||||
{
|
||||
_newMethods.Add(gm);
|
||||
}
|
||||
//if (gm.KlassInst != null)
|
||||
//{
|
||||
// TryAddAndWalkGenericType(new GenericClass(gm.Method.DeclaringType, gm.KlassInst));
|
||||
//}
|
||||
}
|
||||
}
|
||||
Debug.Log($"PostPrepare allMethods:{_genericMethods.Count} newMethods:{_newMethods.Count}");
|
||||
Debug.Log($"PostPrepare allMethods:{_notGenericMethods.Count} newMethods:{_newMethods.Count}");
|
||||
}
|
||||
|
||||
private void RecursiveCollect()
|
||||
@@ -191,7 +190,7 @@ namespace HybridCLR.Editor.MethodBridge
|
||||
{
|
||||
_methodReferenceAnalyzer.WalkMethod(method.Method, method.KlassInst, method.MethodInst);
|
||||
})).ToArray());
|
||||
Debug.Log($"iteration:[{i}] genericClass:{_genericTypes.Count} genericMethods:{_genericMethods.Count} newMethods:{_newMethods.Count}");
|
||||
Debug.Log($"iteration:[{i}] allMethods:{_notGenericMethods.Count} genericClass:{_genericTypes.Count} genericMethods:{_genericMethods.Count} newMethods:{_newMethods.Count}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,6 @@ 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;
|
||||
@@ -20,54 +19,64 @@ namespace HybridCLR.Editor.MethodBridge
|
||||
{
|
||||
public class Options
|
||||
{
|
||||
public PlatformABI PlatformABI { get; set; }
|
||||
|
||||
public string TemplateCode { get; set; }
|
||||
|
||||
public string OutputFile { get; set; }
|
||||
|
||||
public IReadOnlyList<MethodDef> NotGenericMethods { get; set; }
|
||||
|
||||
public IReadOnlyCollection<GenericMethod> GenericMethods { get; set; }
|
||||
}
|
||||
|
||||
private readonly List<GenericMethod> _genericMethods;
|
||||
private PlatformABI _platformABI;
|
||||
|
||||
private readonly IReadOnlyList<MethodDef> _notGenericMethods;
|
||||
|
||||
private readonly IReadOnlyCollection<GenericMethod> _genericMethods;
|
||||
|
||||
private readonly string _templateCode;
|
||||
|
||||
private readonly string _outputFile;
|
||||
|
||||
private readonly TypeCreator _typeCreator;
|
||||
private readonly PlatformGeneratorBase _platformAdaptor;
|
||||
|
||||
private readonly TypeCreatorBase _typeCreator;
|
||||
|
||||
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)
|
||||
{
|
||||
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();
|
||||
|
||||
_platformABI = options.PlatformABI;
|
||||
_notGenericMethods = options.NotGenericMethods;
|
||||
_genericMethods = options.GenericMethods;
|
||||
_templateCode = options.TemplateCode;
|
||||
_outputFile = options.OutputFile;
|
||||
_typeCreator = new TypeCreator();
|
||||
_platformAdaptor = CreatePlatformAdaptor(options.PlatformABI);
|
||||
_typeCreator = TypeCreatorFactory.CreateTypeCreator(options.PlatformABI);
|
||||
}
|
||||
|
||||
private readonly Dictionary<string, TypeInfo> _sig2Types = new Dictionary<string, TypeInfo>();
|
||||
|
||||
private TypeInfo GetSharedTypeInfo(TypeSig type)
|
||||
private static PlatformGeneratorBase CreatePlatformAdaptor(PlatformABI type)
|
||||
{
|
||||
var typeInfo = _typeCreator.CreateTypeInfo(type);
|
||||
if (!typeInfo.IsStruct)
|
||||
switch (type)
|
||||
{
|
||||
return typeInfo;
|
||||
case PlatformABI.Universal32: return new PlatformGeneratorUniversal32();
|
||||
case PlatformABI.Universal64: return new PlatformGeneratorUniversal64();
|
||||
case PlatformABI.Arm64: return new PlatformGeneratorArm64();
|
||||
case PlatformABI.WebGL32: return new PlatformGeneratorWebGL32();
|
||||
default: throw new NotSupportedException();
|
||||
}
|
||||
string sigName = ToFullName(typeInfo.Klass);
|
||||
if (!_sig2Types.TryGetValue(sigName, out var sharedTypeInfo))
|
||||
{
|
||||
sharedTypeInfo = typeInfo;
|
||||
_sig2Types.Add(sigName, sharedTypeInfo);
|
||||
}
|
||||
return sharedTypeInfo;
|
||||
}
|
||||
|
||||
private MethodDesc CreateMethodDesc(MethodDef methodDef, bool forceRemoveThis, TypeSig returnType, List<TypeSig> parameters)
|
||||
@@ -77,24 +86,17 @@ namespace HybridCLR.Editor.MethodBridge
|
||||
{
|
||||
parameters.RemoveAt(0);
|
||||
}
|
||||
if (returnType.ContainsGenericParameter)
|
||||
{
|
||||
throw new Exception($"[PreservedMethod] method:{methodDef} has generic parameters");
|
||||
}
|
||||
foreach (var paramInfo in parameters)
|
||||
{
|
||||
if (paramInfo.ContainsGenericParameter)
|
||||
{
|
||||
throw new Exception($"[PreservedMethod] method:{methodDef} has generic parameters");
|
||||
}
|
||||
paramInfos.Add(new ParamInfo() { Type = GetSharedTypeInfo(paramInfo) });
|
||||
paramInfos.Add(new ParamInfo() { Type = _typeCreator.CreateTypeInfo(paramInfo) });
|
||||
}
|
||||
var mbs = new MethodDesc()
|
||||
{
|
||||
MethodDef = methodDef,
|
||||
ReturnInfo = new ReturnInfo() { Type = returnType != null ? GetSharedTypeInfo(returnType) : TypeInfo.s_void },
|
||||
ReturnInfo = new ReturnInfo() { Type = returnType != null ? _typeCreator.CreateTypeInfo(returnType) : TypeInfo.s_void },
|
||||
ParamInfos = paramInfos,
|
||||
};
|
||||
_typeCreator.OptimizeMethod(mbs);
|
||||
return mbs;
|
||||
}
|
||||
|
||||
@@ -120,32 +122,21 @@ namespace HybridCLR.Editor.MethodBridge
|
||||
{
|
||||
if (method.IsPrivate || (method.IsAssembly && !method.IsPublic && !method.IsFamily))
|
||||
{
|
||||
if (klassInst == null && methodInst == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
else
|
||||
{
|
||||
//Debug.Log($"[PreservedMethod] method:{method}");
|
||||
}
|
||||
return;
|
||||
}
|
||||
ICorLibTypes corLibTypes = method.Module.CorLibTypes;
|
||||
|
||||
TypeSig returnType;
|
||||
List<TypeSig> parameters;
|
||||
if (klassInst == null && methodInst == null)
|
||||
{
|
||||
if (method.HasGenericParameters)
|
||||
{
|
||||
throw new Exception($"[PreservedMethod] method:{method} has generic parameters");
|
||||
}
|
||||
returnType = MetaUtil.ToShareTypeSig(corLibTypes, method.ReturnType);
|
||||
parameters = method.Parameters.Select(p => MetaUtil.ToShareTypeSig(corLibTypes, p.Type)).ToList();
|
||||
returnType = method.ReturnType;
|
||||
parameters = method.Parameters.Select(p => p.Type).ToList();
|
||||
}
|
||||
else
|
||||
{
|
||||
var gc = new GenericArgumentContext(klassInst, methodInst);
|
||||
returnType = MetaUtil.ToShareTypeSig(corLibTypes, MetaUtil.Inflate(method.ReturnType, gc));
|
||||
parameters = method.Parameters.Select(p => MetaUtil.ToShareTypeSig(corLibTypes, MetaUtil.Inflate(p.Type, gc))).ToList();
|
||||
returnType = MetaUtil.Inflate(method.ReturnType, gc);
|
||||
parameters = method.Parameters.Select(p => MetaUtil.Inflate(p.Type, gc)).ToList();
|
||||
}
|
||||
|
||||
var m2nMethod = CreateMethodDesc(method, false, returnType, parameters);
|
||||
@@ -169,260 +160,71 @@ namespace HybridCLR.Editor.MethodBridge
|
||||
|
||||
public void PrepareMethods()
|
||||
{
|
||||
foreach(var method in _notGenericMethods)
|
||||
{
|
||||
ProcessMethod(method, null, null);
|
||||
}
|
||||
|
||||
foreach(var method in _genericMethods)
|
||||
{
|
||||
ProcessMethod(method.Method, method.KlassInst, method.MethodInst);
|
||||
}
|
||||
}
|
||||
|
||||
static void CheckUnique(IEnumerable<string> names)
|
||||
{
|
||||
var set = new HashSet<string>();
|
||||
foreach (var name in names)
|
||||
{
|
||||
if (!set.Add(name))
|
||||
{
|
||||
throw new Exception($"[CheckUnique] duplicate name:{name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private List<MethodDesc> _managed2NativeMethodList0;
|
||||
private List<MethodDesc> _native2ManagedMethodList0;
|
||||
private List<MethodDesc> _adjustThunkMethodList0;
|
||||
|
||||
private List<TypeInfo> _structTypes0;
|
||||
|
||||
private void CollectTypesAndMethods()
|
||||
{
|
||||
_managed2NativeMethodList0 = _managed2nativeMethodSet.ToList();
|
||||
_managed2NativeMethodList0.Sort((a, b) => string.CompareOrdinal(a.Sig, b.Sig));
|
||||
|
||||
_native2ManagedMethodList0 = _native2managedMethodSet.ToList();
|
||||
_native2ManagedMethodList0.Sort((a, b) => string.CompareOrdinal(a.Sig, b.Sig));
|
||||
|
||||
_adjustThunkMethodList0 = _adjustThunkMethodSet.ToList();
|
||||
_adjustThunkMethodList0.Sort((a, b) => string.CompareOrdinal(a.Sig, b.Sig));
|
||||
|
||||
|
||||
var structTypeSet = new HashSet<TypeInfo>();
|
||||
CollectStructDefs(_managed2NativeMethodList0, structTypeSet);
|
||||
CollectStructDefs(_native2ManagedMethodList0, structTypeSet);
|
||||
CollectStructDefs(_adjustThunkMethodList0, structTypeSet);
|
||||
_structTypes0 = structTypeSet.ToList();
|
||||
_structTypes0.Sort((a, b) => a.TypeId - b.TypeId);
|
||||
|
||||
CheckUnique(_structTypes0.Select(t => ToFullName(t.Klass)));
|
||||
CheckUnique(_structTypes0.Select(t => t.CreateSigName()));
|
||||
|
||||
Debug.LogFormat("== before optimization struct:{3} managed2native:{0} native2managed:{1} adjustThunk:{2}",
|
||||
_managed2NativeMethodList0.Count, _native2ManagedMethodList0.Count, _adjustThunkMethodList0.Count, _structTypes0.Count);
|
||||
}
|
||||
|
||||
private class AnalyzeTypeInfo
|
||||
{
|
||||
public TypeInfo toSharedType;
|
||||
public List<TypeInfo> fields;
|
||||
public string signature;
|
||||
}
|
||||
|
||||
private readonly Dictionary<TypeInfo, AnalyzeTypeInfo> _analyzeTypeInfos = new Dictionary<TypeInfo, AnalyzeTypeInfo>();
|
||||
|
||||
private readonly Dictionary<string, TypeInfo> _signature2Type = new Dictionary<string, TypeInfo>();
|
||||
|
||||
private AnalyzeTypeInfo CalculateAnalyzeTypeInfoBasic(TypeInfo typeInfo)
|
||||
{
|
||||
TypeSig type = typeInfo.Klass;
|
||||
TypeDef typeDef = type.ToTypeDefOrRef().ResolveTypeDefThrow();
|
||||
|
||||
List<TypeSig> klassInst = type.ToGenericInstSig()?.GenericArguments?.ToList();
|
||||
GenericArgumentContext ctx = klassInst != null ? new GenericArgumentContext(klassInst, null) : null;
|
||||
|
||||
ClassLayout sa = typeDef.ClassLayout;
|
||||
var analyzeTypeInfo = new AnalyzeTypeInfo();
|
||||
|
||||
// don't share type with explicit layout
|
||||
if (sa != null)
|
||||
{
|
||||
analyzeTypeInfo.toSharedType = typeInfo;
|
||||
analyzeTypeInfo.signature = typeInfo.CreateSigName();
|
||||
_signature2Type.Add(analyzeTypeInfo.signature, typeInfo);
|
||||
return analyzeTypeInfo;
|
||||
}
|
||||
|
||||
var fields = analyzeTypeInfo.fields = new List<TypeInfo>();
|
||||
|
||||
foreach (FieldDef field in typeDef.Fields)
|
||||
{
|
||||
if (field.IsStatic)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
TypeSig fieldType = ctx != null ? MetaUtil.Inflate(field.FieldType, ctx) : field.FieldType;
|
||||
fields.Add(GetSharedTypeInfo(fieldType));
|
||||
}
|
||||
return analyzeTypeInfo;
|
||||
}
|
||||
|
||||
private string GetOrCalculateTypeInfoSignature(TypeInfo typeInfo)
|
||||
{
|
||||
if (!typeInfo.IsStruct)
|
||||
{
|
||||
return typeInfo.CreateSigName();
|
||||
}
|
||||
|
||||
var ati = _analyzeTypeInfos[typeInfo];
|
||||
|
||||
//if (_analyzeTypeInfos.TryGetValue(typeInfo, out var ati))
|
||||
//{
|
||||
// return ati.signature;
|
||||
//}
|
||||
//ati = CalculateAnalyzeTypeInfoBasic(typeInfo);
|
||||
//_analyzeTypeInfos.Add(typeInfo, ati);
|
||||
if (ati.signature != null)
|
||||
{
|
||||
return ati.signature;
|
||||
}
|
||||
|
||||
var sigBuf = new StringBuilder();
|
||||
foreach (var field in ati.fields)
|
||||
{
|
||||
sigBuf.Append(GetOrCalculateTypeInfoSignature(ToIsomorphicType(field)));
|
||||
}
|
||||
return ati.signature = sigBuf.ToString();
|
||||
}
|
||||
|
||||
private TypeInfo ToIsomorphicType(TypeInfo type)
|
||||
{
|
||||
if (!type.IsStruct)
|
||||
{
|
||||
return type;
|
||||
}
|
||||
if (!_analyzeTypeInfos.TryGetValue(type, out var ati))
|
||||
{
|
||||
ati = CalculateAnalyzeTypeInfoBasic(type);
|
||||
_analyzeTypeInfos.Add(type, ati);
|
||||
}
|
||||
if (ati.toSharedType == null)
|
||||
{
|
||||
string signature = GetOrCalculateTypeInfoSignature(type);
|
||||
Debug.Assert(signature == ati.signature);
|
||||
if (_signature2Type.TryGetValue(signature, out var sharedType))
|
||||
var sortedMethods = new SortedDictionary<string, MethodDesc>();
|
||||
foreach (var method in _managed2nativeMethodSet)
|
||||
{
|
||||
// Debug.Log($"[ToIsomorphicType] type:{type.Klass} ==> sharedType:{sharedType.Klass} signature:{signature} ");
|
||||
ati.toSharedType = sharedType;
|
||||
sortedMethods.Add(method.CreateCallSigName(), method);
|
||||
}
|
||||
else
|
||||
_managed2nativeMethodList = sortedMethods.Values.ToList();
|
||||
}
|
||||
{
|
||||
var sortedMethods = new SortedDictionary<string, MethodDesc>();
|
||||
foreach (var method in _native2managedMethodSet)
|
||||
{
|
||||
ati.toSharedType = type;
|
||||
_signature2Type.Add(signature, type);
|
||||
sortedMethods.Add(method.CreateCallSigName(), method);
|
||||
}
|
||||
_native2managedMethodList = sortedMethods.Values.ToList();
|
||||
}
|
||||
return ati.toSharedType;
|
||||
}
|
||||
|
||||
private MethodDesc ToIsomorphicMethod(MethodDesc method)
|
||||
{
|
||||
var paramInfos = new List<ParamInfo>();
|
||||
foreach (var paramInfo in method.ParamInfos)
|
||||
{
|
||||
paramInfos.Add(new ParamInfo() { Type = ToIsomorphicType(paramInfo.Type) });
|
||||
}
|
||||
var mbs = new MethodDesc()
|
||||
{
|
||||
MethodDef = method.MethodDef,
|
||||
ReturnInfo = new ReturnInfo() { Type = ToIsomorphicType(method.ReturnInfo.Type) },
|
||||
ParamInfos = paramInfos,
|
||||
};
|
||||
mbs.Init();
|
||||
return mbs;
|
||||
}
|
||||
|
||||
private List<MethodDesc> _managed2NativeMethodList;
|
||||
private List<MethodDesc> _native2ManagedMethodList;
|
||||
private List<MethodDesc> _adjustThunkMethodList;
|
||||
|
||||
private List<TypeInfo> structTypes;
|
||||
|
||||
private void BuildAnalyzeTypeInfos()
|
||||
{
|
||||
foreach (var type in _structTypes0)
|
||||
{
|
||||
ToIsomorphicType(type);
|
||||
}
|
||||
structTypes = _signature2Type.Values.ToList();
|
||||
structTypes.Sort((a, b) => a.TypeId - b.TypeId);
|
||||
}
|
||||
|
||||
private List<MethodDesc> ToUniqueOrderedList(List<MethodDesc> methods)
|
||||
{
|
||||
var methodMap = new SortedDictionary<string, MethodDesc>();
|
||||
foreach (var method in methods)
|
||||
{
|
||||
var sharedMethod = ToIsomorphicMethod(method);
|
||||
var sig = sharedMethod.Sig;
|
||||
if (!methodMap.TryGetValue(sig, out var _))
|
||||
var sortedMethods = new SortedDictionary<string, MethodDesc>();
|
||||
foreach (var method in _adjustThunkMethodSet)
|
||||
{
|
||||
methodMap.Add(sig, sharedMethod);
|
||||
sortedMethods.Add(method.CreateCallSigName(), method);
|
||||
}
|
||||
_adjustThunkMethodList = sortedMethods.Values.ToList();
|
||||
}
|
||||
return methodMap.Values.ToList();
|
||||
}
|
||||
|
||||
private void BuildOptimizedMethods()
|
||||
public void Generate()
|
||||
{
|
||||
_managed2NativeMethodList = ToUniqueOrderedList(_managed2NativeMethodList0);
|
||||
_native2ManagedMethodList = ToUniqueOrderedList(_native2ManagedMethodList0);
|
||||
_adjustThunkMethodList = ToUniqueOrderedList(_adjustThunkMethodList0);
|
||||
}
|
||||
|
||||
private void OptimizationTypesAndMethods()
|
||||
{
|
||||
BuildAnalyzeTypeInfos();
|
||||
BuildOptimizedMethods();
|
||||
Debug.LogFormat("== after optimization struct:{3} managed2native:{0} native2managed:{1} adjustThunk:{2}",
|
||||
_managed2NativeMethodList.Count, _native2ManagedMethodList.Count, _adjustThunkMethodList.Count, structTypes.Count);
|
||||
}
|
||||
|
||||
private void GenerateCode()
|
||||
{
|
||||
var frr = new FileRegionReplace(_templateCode);
|
||||
var frr = new FileRegionReplace(_templateCode.Replace("{PLATFORM_ABI}", ABIUtil.GetHybridCLRPlatformMacro(_platformABI)));
|
||||
|
||||
List<string> lines = new List<string>(20_0000);
|
||||
|
||||
var classInfos = new List<ClassInfo>();
|
||||
var classTypeSet = new HashSet<TypeInfo>();
|
||||
foreach (var type in structTypes)
|
||||
Debug.LogFormat("== managed2native:{0} native2managed:{1} adjustThunk:{2}",
|
||||
_managed2nativeMethodList.Count, _native2managedMethodList.Count, _adjustThunkMethodList.Count);
|
||||
|
||||
foreach(var method in _managed2nativeMethodList)
|
||||
{
|
||||
GenerateClassInfo(type, classTypeSet, classInfos);
|
||||
_platformAdaptor.GenerateManaged2NativeMethod(method, lines);
|
||||
}
|
||||
|
||||
GenerateStructDefines(classInfos, lines);
|
||||
_platformAdaptor.GenerateManaged2NativeStub(_managed2nativeMethodList, lines);
|
||||
|
||||
// use structTypes0 to generate signature
|
||||
GenerateStructureSignatureStub(_structTypes0, lines);
|
||||
|
||||
foreach (var method in _managed2NativeMethodList)
|
||||
foreach (var method in _native2managedMethodList)
|
||||
{
|
||||
GenerateManaged2NativeMethod(method, lines);
|
||||
_platformAdaptor.GenerateNative2ManagedMethod(method, lines);
|
||||
}
|
||||
|
||||
GenerateManaged2NativeStub(_managed2NativeMethodList, lines);
|
||||
|
||||
foreach (var method in _native2ManagedMethodList)
|
||||
{
|
||||
GenerateNative2ManagedMethod(method, lines);
|
||||
}
|
||||
|
||||
GenerateNative2ManagedStub(_native2ManagedMethodList, lines);
|
||||
_platformAdaptor.GenerateNative2ManagedStub(_native2managedMethodList, lines);
|
||||
|
||||
foreach (var method in _adjustThunkMethodList)
|
||||
{
|
||||
GenerateAdjustThunkMethod(method, lines);
|
||||
_platformAdaptor.GenerateAdjustThunkMethod(method, lines);
|
||||
}
|
||||
|
||||
GenerateAdjustThunkStub(_adjustThunkMethodList, lines);
|
||||
_platformAdaptor.GenerateAdjustThunkStub(_adjustThunkMethodList, lines);
|
||||
|
||||
frr.Replace("CODE", string.Join("\n", lines));
|
||||
|
||||
@@ -431,398 +233,5 @@ namespace HybridCLR.Editor.MethodBridge
|
||||
frr.Commit(_outputFile);
|
||||
}
|
||||
|
||||
public void Generate()
|
||||
{
|
||||
CollectTypesAndMethods();
|
||||
OptimizationTypesAndMethods();
|
||||
GenerateCode();
|
||||
}
|
||||
|
||||
private void CollectStructDefs(List<MethodDesc> methods, HashSet<TypeInfo> structTypes)
|
||||
{
|
||||
foreach (var method in methods)
|
||||
{
|
||||
foreach(var paramInfo in method.ParamInfos)
|
||||
{
|
||||
if (paramInfo.Type.IsStruct)
|
||||
{
|
||||
structTypes.Add(paramInfo.Type);
|
||||
if (paramInfo.Type.Klass.ContainsGenericParameter)
|
||||
{
|
||||
throw new Exception($"[CollectStructDefs] method:{method.MethodDef} type:{paramInfo.Type.Klass} contains generic parameter");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
if (method.ReturnInfo.Type.IsStruct)
|
||||
{
|
||||
structTypes.Add(method.ReturnInfo.Type);
|
||||
if (method.ReturnInfo.Type.Klass.ContainsGenericParameter)
|
||||
{
|
||||
throw new Exception($"[CollectStructDefs] method:{method.MethodDef} type:{method.ReturnInfo.Type.Klass} contains generic parameter");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class FieldInfo
|
||||
{
|
||||
public FieldDef field;
|
||||
public TypeInfo type;
|
||||
}
|
||||
|
||||
class ClassInfo
|
||||
{
|
||||
public TypeInfo type;
|
||||
|
||||
public TypeDef typeDef;
|
||||
|
||||
public List<FieldInfo> fields = new List<FieldInfo>();
|
||||
|
||||
public ClassLayout layout;
|
||||
}
|
||||
|
||||
private void GenerateClassInfo(TypeInfo type, HashSet<TypeInfo> typeSet, List<ClassInfo> classInfos)
|
||||
{
|
||||
if (!typeSet.Add(type))
|
||||
{
|
||||
return;
|
||||
}
|
||||
TypeSig typeSig = type.Klass;
|
||||
var fields = new List<FieldInfo>();
|
||||
|
||||
TypeDef typeDef = typeSig.ToTypeDefOrRef().ResolveTypeDefThrow();
|
||||
|
||||
List<TypeSig> klassInst = typeSig.ToGenericInstSig()?.GenericArguments?.ToList();
|
||||
GenericArgumentContext ctx = klassInst != null ? new GenericArgumentContext(klassInst, null) : null;
|
||||
|
||||
ClassLayout sa = typeDef.ClassLayout;
|
||||
|
||||
ICorLibTypes corLibTypes = typeDef.Module.CorLibTypes;
|
||||
foreach (FieldDef field in typeDef.Fields)
|
||||
{
|
||||
if (field.IsStatic)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
TypeSig fieldType = ctx != null ? MetaUtil.Inflate(field.FieldType, ctx) : field.FieldType;
|
||||
fieldType = MetaUtil.ToShareTypeSig(corLibTypes, fieldType);
|
||||
var fieldTypeInfo = ToIsomorphicType(_typeCreator.CreateTypeInfo(fieldType));
|
||||
if (fieldTypeInfo.IsStruct)
|
||||
{
|
||||
GenerateClassInfo(fieldTypeInfo, typeSet, classInfos);
|
||||
}
|
||||
fields.Add(new FieldInfo { field = field, type = fieldTypeInfo });
|
||||
}
|
||||
classInfos.Add(new ClassInfo() { type = type, typeDef = typeDef, fields = fields, layout = sa });
|
||||
}
|
||||
|
||||
private void GenerateStructDefines(List<ClassInfo> classInfos, List<string> lines)
|
||||
{
|
||||
foreach (var ci in classInfos)
|
||||
{
|
||||
lines.Add($"// {ci.type.Klass}");
|
||||
uint packingSize = ci.layout?.PackingSize ?? 0;
|
||||
if (packingSize != 0)
|
||||
{
|
||||
lines.Add($"#pragma pack(push, {packingSize})");
|
||||
}
|
||||
uint classSize = ci.layout?.ClassSize ?? 0;
|
||||
|
||||
if (ci.typeDef.IsExplicitLayout)
|
||||
{
|
||||
lines.Add($"union {ci.type.GetTypeName()} {{");
|
||||
if (classSize > 0)
|
||||
{
|
||||
lines.Add($"\tstruct {{ char __fieldSize_offsetPadding[{classSize}];}};");
|
||||
}
|
||||
int index = 0;
|
||||
foreach (var field in ci.fields)
|
||||
{
|
||||
uint offset = field.field.FieldOffset.Value;
|
||||
string fieldName = $"__{index}";
|
||||
string commentFieldName = $"{field.field.Name}";
|
||||
lines.Add("\t#pragma pack(push, 1)");
|
||||
lines.Add($"\tstruct {{ {(offset > 0 ? $"char {fieldName}_offsetPadding[{offset}];" : "")} {field.type.GetTypeName()} {fieldName};}}; // {commentFieldName}");
|
||||
lines.Add($"\t#pragma pack(pop)");
|
||||
lines.Add($"\tstruct {{ {field.type.GetTypeName()} {fieldName}_forAlignmentOnly;}}; // {commentFieldName}");
|
||||
++index;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
lines.Add($"{(classSize > 0 ? "union" : "struct")} {ci.type.GetTypeName()} {{");
|
||||
if (classSize > 0)
|
||||
{
|
||||
lines.Add($"\tstruct {{ char __fieldSize_offsetPadding[{classSize}];}};");
|
||||
lines.Add("\tstruct {");
|
||||
}
|
||||
int index = 0;
|
||||
foreach (var field in ci.fields)
|
||||
{
|
||||
string fieldName = $"__{index}";
|
||||
string commentFieldName = $"{field.field.Name}";
|
||||
lines.Add($"\t{field.type.GetTypeName()} {fieldName}; // {commentFieldName}");
|
||||
++index;
|
||||
}
|
||||
if (classSize > 0)
|
||||
{
|
||||
lines.Add("\t};");
|
||||
}
|
||||
}
|
||||
lines.Add("};");
|
||||
if (packingSize != 0)
|
||||
{
|
||||
lines.Add($"#pragma pack(pop)");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public const string SigOfObj = "u";
|
||||
|
||||
public static string ToFullName(TypeSig type)
|
||||
{
|
||||
type = type.RemovePinnedAndModifiers();
|
||||
switch (type.ElementType)
|
||||
{
|
||||
case ElementType.Void: return "v";
|
||||
case ElementType.Boolean: return "u1";
|
||||
case ElementType.I1: return "i1";
|
||||
case ElementType.U1: return "u1";
|
||||
case ElementType.I2: return "i2";
|
||||
case ElementType.Char:
|
||||
case ElementType.U2: return "u2";
|
||||
case ElementType.I4: return "i4";
|
||||
case ElementType.U4: return "u4";
|
||||
case ElementType.I8: return "i8";
|
||||
case ElementType.U8: return "u8";
|
||||
case ElementType.R4: return "r4";
|
||||
case ElementType.R8: return "r8";
|
||||
case ElementType.I: return "i";
|
||||
case ElementType.U:
|
||||
case ElementType.String:
|
||||
case ElementType.Ptr:
|
||||
case ElementType.ByRef:
|
||||
case ElementType.Class:
|
||||
case ElementType.Array:
|
||||
case ElementType.SZArray:
|
||||
case ElementType.FnPtr:
|
||||
case ElementType.Object:
|
||||
return SigOfObj;
|
||||
case ElementType.Module:
|
||||
case ElementType.Var:
|
||||
case ElementType.MVar:
|
||||
throw new NotSupportedException($"ToFullName type:{type}");
|
||||
case ElementType.TypedByRef: return TypeInfo.strTypedByRef;
|
||||
case ElementType.ValueType:
|
||||
{
|
||||
TypeDef typeDef = type.ToTypeDefOrRef().ResolveTypeDef();
|
||||
if (typeDef == null)
|
||||
{
|
||||
throw new Exception($"type:{type} definition could not be found. Please try `HybridCLR/Genergate/LinkXml`, then Build once to generate the AOT dll, and then regenerate the bridge function");
|
||||
}
|
||||
if (typeDef.IsEnum)
|
||||
{
|
||||
return ToFullName(typeDef.GetEnumUnderlyingType());
|
||||
}
|
||||
return ToValueTypeFullName((ClassOrValueTypeSig)type);
|
||||
}
|
||||
case ElementType.GenericInst:
|
||||
{
|
||||
GenericInstSig gis = (GenericInstSig)type;
|
||||
if (!gis.GenericType.IsValueType)
|
||||
{
|
||||
return SigOfObj;
|
||||
}
|
||||
TypeDef typeDef = gis.GenericType.ToTypeDefOrRef().ResolveTypeDef();
|
||||
if (typeDef.IsEnum)
|
||||
{
|
||||
return ToFullName(typeDef.GetEnumUnderlyingType());
|
||||
}
|
||||
return $"{ToValueTypeFullName(gis.GenericType)}<{string.Join(",", gis.GenericArguments.Select(a => ToFullName(a)))}>";
|
||||
}
|
||||
default: throw new NotSupportedException($"{type.ElementType}");
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsSystemOrUnityAssembly(ModuleDef module)
|
||||
{
|
||||
if (module.IsCoreLibraryModule == true)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
string assName = module.Assembly.Name.String;
|
||||
return assName.StartsWith("System.") || assName.StartsWith("UnityEngine.");
|
||||
}
|
||||
|
||||
private static string ToValueTypeFullName(ClassOrValueTypeSig type)
|
||||
{
|
||||
TypeDef typeDef = type.ToTypeDefOrRef().ResolveTypeDef();
|
||||
if (typeDef == null)
|
||||
{
|
||||
throw new Exception($"type:{type} resolve fail");
|
||||
}
|
||||
|
||||
if (typeDef.DeclaringType != null)
|
||||
{
|
||||
return $"{ToValueTypeFullName((ClassOrValueTypeSig)typeDef.DeclaringType.ToTypeSig())}/{typeDef.Name}";
|
||||
}
|
||||
|
||||
if (IsSystemOrUnityAssembly(typeDef.Module))
|
||||
{
|
||||
return type.FullName;
|
||||
}
|
||||
return $"{Path.GetFileNameWithoutExtension(typeDef.Module.Name)}:{typeDef.FullName}";
|
||||
}
|
||||
|
||||
public void GenerateStructureSignatureStub(List<TypeInfo> types, List<string> lines)
|
||||
{
|
||||
lines.Add("FullName2Signature hybridclr::interpreter::g_fullName2SignatureStub[] = {");
|
||||
foreach (var type in types)
|
||||
{
|
||||
TypeInfo isoType = ToIsomorphicType(type);
|
||||
lines.Add($"\t{{\"{ToFullName(type.Klass)}\", \"{isoType.CreateSigName()}\"}},");
|
||||
}
|
||||
lines.Add("\t{ nullptr, nullptr},");
|
||||
lines.Add("};");
|
||||
}
|
||||
|
||||
public void GenerateManaged2NativeStub(List<MethodDesc> methods, List<string> lines)
|
||||
{
|
||||
lines.Add($@"
|
||||
Managed2NativeMethodInfo hybridclr::interpreter::g_managed2nativeStub[] =
|
||||
{{
|
||||
");
|
||||
|
||||
foreach (var method in methods)
|
||||
{
|
||||
lines.Add($"\t{{\"{method.CreateInvokeSigName()}\", __M2N_{method.CreateInvokeSigName()}}},");
|
||||
}
|
||||
|
||||
lines.Add($"\t{{nullptr, nullptr}},");
|
||||
lines.Add("};");
|
||||
}
|
||||
|
||||
public void GenerateNative2ManagedStub(List<MethodDesc> methods, List<string> lines)
|
||||
{
|
||||
lines.Add($@"
|
||||
Native2ManagedMethodInfo hybridclr::interpreter::g_native2managedStub[] =
|
||||
{{
|
||||
");
|
||||
|
||||
foreach (var method in methods)
|
||||
{
|
||||
lines.Add($"\t{{\"{method.CreateInvokeSigName()}\", (Il2CppMethodPointer)__N2M_{method.CreateInvokeSigName()}}},");
|
||||
}
|
||||
|
||||
lines.Add($"\t{{nullptr, nullptr}},");
|
||||
lines.Add("};");
|
||||
}
|
||||
|
||||
public void GenerateAdjustThunkStub(List<MethodDesc> methods, List<string> lines)
|
||||
{
|
||||
lines.Add($@"
|
||||
NativeAdjustThunkMethodInfo hybridclr::interpreter::g_adjustThunkStub[] =
|
||||
{{
|
||||
");
|
||||
|
||||
foreach (var method in methods)
|
||||
{
|
||||
lines.Add($"\t{{\"{method.CreateInvokeSigName()}\", (Il2CppMethodPointer)__N2M_AdjustorThunk_{method.CreateCallSigName()}}},");
|
||||
}
|
||||
|
||||
lines.Add($"\t{{nullptr, nullptr}},");
|
||||
lines.Add("};");
|
||||
}
|
||||
|
||||
private string GetManaged2NativePassParam(TypeInfo type, string varName)
|
||||
{
|
||||
return $"M2NFromValueOrAddress<{type.GetTypeName()}>({varName})";
|
||||
}
|
||||
|
||||
private string GetNative2ManagedPassParam(TypeInfo type, string varName)
|
||||
{
|
||||
return type.NeedExpandValue() ? $"(uint64_t)({varName})" : $"N2MAsUint64ValueOrAddress<{type.GetTypeName()}>({varName})";
|
||||
}
|
||||
|
||||
public void GenerateManaged2NativeMethod(MethodDesc method, List<string> lines)
|
||||
{
|
||||
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 => GetManaged2NativePassParam(p.Type, $"localVarBase+argVarIndexs[{p.Index}]")).Concat(new string[] { "method" }));
|
||||
|
||||
lines.Add($@"
|
||||
static void __M2N_{method.CreateCallSigName()}(const MethodInfo* method, uint16_t* argVarIndexs, StackObject* localVarBase, void* ret)
|
||||
{{
|
||||
typedef {method.ReturnInfo.Type.GetTypeName()} (*NativeMethod)({paramListStr});
|
||||
{(!method.ReturnInfo.IsVoid ? $"*({method.ReturnInfo.Type.GetTypeName()}*)ret = " : "")}((NativeMethod)(method->methodPointerCallByInterp))({paramNameListStr});
|
||||
}}
|
||||
");
|
||||
}
|
||||
|
||||
public string GenerateArgumentSizeAndOffset(List<ParamInfo> paramInfos)
|
||||
{
|
||||
StringBuilder s = new StringBuilder();
|
||||
int index = 0;
|
||||
foreach (var param in paramInfos)
|
||||
{
|
||||
s.AppendLine($"\tconstexpr int __ARG_OFFSET_{index}__ = {(index > 0 ? $"__ARG_OFFSET_{index - 1}__ + __ARG_SIZE_{index-1}__" : "0")};");
|
||||
s.AppendLine($"\tconstexpr int __ARG_SIZE_{index}__ = (sizeof(__arg{index}) + 7)/8;");
|
||||
index++;
|
||||
}
|
||||
s.AppendLine($"\tconstexpr int __TOTAL_ARG_SIZE__ = {(paramInfos.Count > 0 ? $"__ARG_OFFSET_{index-1}__ + __ARG_SIZE_{index-1}__" : "1")};");
|
||||
return s.ToString();
|
||||
}
|
||||
|
||||
public string GenerateCopyArgumentToInterpreterStack(List<ParamInfo> paramInfos)
|
||||
{
|
||||
StringBuilder s = new StringBuilder();
|
||||
int index = 0;
|
||||
foreach (var param in paramInfos)
|
||||
{
|
||||
if (param.Type.IsPrimitiveType)
|
||||
{
|
||||
if (param.Type.NeedExpandValue())
|
||||
{
|
||||
s.AppendLine($"\targs[__ARG_OFFSET_{index}__].u64 = __arg{index};");
|
||||
}
|
||||
else
|
||||
{
|
||||
s.AppendLine($"\t*({param.Type.GetTypeName()}*)(args + __ARG_OFFSET_{index}__) = __arg{index};");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
s.AppendLine($"\t*({param.Type.GetTypeName()}*)(args + __ARG_OFFSET_{index}__) = __arg{index};");
|
||||
}
|
||||
index++;
|
||||
}
|
||||
return s.ToString();
|
||||
}
|
||||
|
||||
private void GenerateNative2ManagedMethod0(MethodDesc method, bool adjustorThunk, List<string> lines)
|
||||
{
|
||||
string paramListStr = string.Join(", ", method.ParamInfos.Select(p => $"{p.Type.GetTypeName()} __arg{p.Index}").Concat(new string[] { "const MethodInfo* method" }));
|
||||
lines.Add($@"
|
||||
static {method.ReturnInfo.Type.GetTypeName()} __N2M_{(adjustorThunk ? "AdjustorThunk_" : "")}{method.CreateCallSigName()}({paramListStr})
|
||||
{{
|
||||
{(adjustorThunk ? "__arg0 += sizeof(Il2CppObject);" : "")}
|
||||
{GenerateArgumentSizeAndOffset(method.ParamInfos)}
|
||||
StackObject args[__TOTAL_ARG_SIZE__];
|
||||
{GenerateCopyArgumentToInterpreterStack(method.ParamInfos)}
|
||||
{(method.ReturnInfo.IsVoid ? "Interpreter::Execute(method, args, nullptr);" : $"{method.ReturnInfo.Type.GetTypeName()} ret; Interpreter::Execute(method, args, &ret); return ret;")}
|
||||
}}
|
||||
");
|
||||
}
|
||||
|
||||
public void GenerateNative2ManagedMethod(MethodDesc method, List<string> lines)
|
||||
{
|
||||
GenerateNative2ManagedMethod0(method, false, lines);
|
||||
}
|
||||
|
||||
public void GenerateAdjustThunkMethod(MethodDesc method, List<string> lines)
|
||||
{
|
||||
GenerateNative2ManagedMethod0(method, true, lines);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
using dnlib.DotNet;
|
||||
using HybridCLR.Editor.ABI;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using UnityEngine;
|
||||
|
||||
namespace HybridCLR.Editor.MethodBridge
|
||||
{
|
||||
|
||||
|
||||
|
||||
public class PlatformGeneratorArm64 : PlatformGeneratorBase
|
||||
{
|
||||
public override PlatformABI PlatformABI { get; } = PlatformABI.Universal64;
|
||||
|
||||
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});
|
||||
{(!method.ReturnInfo.IsVoid ? $"*({method.ReturnInfo.Type.GetTypeName()}*)ret = " : "")}((NativeMethod)(method->methodPointerCallByInterp))({paramNameListStr});
|
||||
}}
|
||||
");
|
||||
}
|
||||
|
||||
public override void GenerateNative2ManagedMethod(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" }));
|
||||
|
||||
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)))} }};
|
||||
StackObject* ret = {(method.ReturnInfo.IsVoid ? "nullptr" : "args + " + method.ParamInfos.Count)};
|
||||
Interpreter::Execute(method, args, ret);
|
||||
{(!method.ReturnInfo.IsVoid ? $"return *({method.ReturnInfo.Type.GetTypeName()}*)ret;" : "")}
|
||||
}}
|
||||
");
|
||||
}
|
||||
|
||||
public override void GenerateAdjustThunkMethod(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" }));
|
||||
|
||||
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))))} }};
|
||||
StackObject* ret = {(method.ReturnInfo.IsVoid ? "nullptr" : "args + " + method.ParamInfos.Count)};
|
||||
Interpreter::Execute(method, args, ret);
|
||||
{(!method.ReturnInfo.IsVoid ? $"return *({method.ReturnInfo.Type.GetTypeName()}*)ret;" : "")}
|
||||
}}
|
||||
");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 4bd8c3b77879ac44b8921a67b5216ca6
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,75 @@
|
||||
using dnlib.DotNet;
|
||||
using HybridCLR.Editor.ABI;
|
||||
using HybridCLR.Editor.Meta;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Reflection.Emit;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using UnityEngine;
|
||||
using TypeInfo = HybridCLR.Editor.ABI.TypeInfo;
|
||||
|
||||
namespace HybridCLR.Editor.MethodBridge
|
||||
{
|
||||
public abstract class PlatformGeneratorBase
|
||||
{
|
||||
public abstract PlatformABI PlatformABI { get; }
|
||||
|
||||
public abstract void GenerateManaged2NativeMethod(MethodDesc method, List<string> lines);
|
||||
|
||||
public abstract void GenerateNative2ManagedMethod(MethodDesc method, List<string> lines);
|
||||
|
||||
public abstract void GenerateAdjustThunkMethod(MethodDesc method, List<string> outputLines);
|
||||
|
||||
|
||||
public void GenerateManaged2NativeStub(List<MethodDesc> methods, List<string> lines)
|
||||
{
|
||||
lines.Add($@"
|
||||
Managed2NativeMethodInfo hybridclr::interpreter::g_managed2nativeStub[] =
|
||||
{{
|
||||
");
|
||||
|
||||
foreach (var method in methods)
|
||||
{
|
||||
lines.Add($"\t{{\"{method.CreateInvokeSigName()}\", __M2N_{method.CreateInvokeSigName()}}},");
|
||||
}
|
||||
|
||||
lines.Add($"\t{{nullptr, nullptr}},");
|
||||
lines.Add("};");
|
||||
}
|
||||
|
||||
public void GenerateNative2ManagedStub(List<MethodDesc> methods, List<string> lines)
|
||||
{
|
||||
lines.Add($@"
|
||||
Native2ManagedMethodInfo hybridclr::interpreter::g_native2managedStub[] =
|
||||
{{
|
||||
");
|
||||
|
||||
foreach (var method in methods)
|
||||
{
|
||||
lines.Add($"\t{{\"{method.CreateInvokeSigName()}\", (Il2CppMethodPointer)__N2M_{method.CreateInvokeSigName()}}},");
|
||||
}
|
||||
|
||||
lines.Add($"\t{{nullptr, nullptr}},");
|
||||
lines.Add("};");
|
||||
}
|
||||
|
||||
public void GenerateAdjustThunkStub(List<MethodDesc> methods, List<string> lines)
|
||||
{
|
||||
lines.Add($@"
|
||||
NativeAdjustThunkMethodInfo hybridclr::interpreter::g_adjustThunkStub[] =
|
||||
{{
|
||||
");
|
||||
|
||||
foreach (var method in methods)
|
||||
{
|
||||
lines.Add($"\t{{\"{method.CreateInvokeSigName()}\", (Il2CppMethodPointer)__N2M_AdjustorThunk_{method.CreateCallSigName()}}},");
|
||||
}
|
||||
|
||||
lines.Add($"\t{{nullptr, nullptr}},");
|
||||
lines.Add("};");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 2d2e42e9b08396e42bbaaab79865529f
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,67 @@
|
||||
using dnlib.DotNet;
|
||||
using HybridCLR.Editor.ABI;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using UnityEngine;
|
||||
|
||||
namespace HybridCLR.Editor.MethodBridge
|
||||
{
|
||||
public class PlatformGeneratorUniversal32 : PlatformGeneratorBase
|
||||
{
|
||||
public override PlatformABI PlatformABI { get; } = PlatformABI.Universal32;
|
||||
|
||||
public override void GenerateManaged2NativeMethod(MethodDesc method, List<string> lines)
|
||||
{
|
||||
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});
|
||||
{(!method.ReturnInfo.IsVoid ? $"*({method.ReturnInfo.Type.GetTypeName()}*)ret = " : "")}((NativeMethod)(method->methodPointerCallByInterp))({paramNameListStr});
|
||||
}}
|
||||
");
|
||||
}
|
||||
public override void GenerateNative2ManagedMethod(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" }));
|
||||
|
||||
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)))} }};
|
||||
StackObject* ret = {(method.ReturnInfo.IsVoid ? "nullptr" : "args + " + method.ParamInfos.Count)};
|
||||
Interpreter::Execute(method, args, ret);
|
||||
{(!method.ReturnInfo.IsVoid ? $"return *({method.ReturnInfo.Type.GetTypeName()}*)ret;" : "")}
|
||||
}}
|
||||
");
|
||||
}
|
||||
public override void GenerateAdjustThunkMethod(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" }));
|
||||
|
||||
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))))} }};
|
||||
StackObject* ret = {(method.ReturnInfo.IsVoid ? "nullptr" : "args + " + method.ParamInfos.Count)};
|
||||
Interpreter::Execute(method, args, ret);
|
||||
{(!method.ReturnInfo.IsVoid ? $"return *({method.ReturnInfo.Type.GetTypeName()}*)ret;" : "")}
|
||||
}}
|
||||
");
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: cee9b0142fca88747b2414ca4b3d2b7a
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,67 @@
|
||||
using dnlib.DotNet;
|
||||
using HybridCLR.Editor.ABI;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using UnityEngine;
|
||||
using TypeInfo = HybridCLR.Editor.ABI.TypeInfo;
|
||||
|
||||
namespace HybridCLR.Editor.MethodBridge
|
||||
{
|
||||
public class PlatformGeneratorUniversal64 : PlatformGeneratorBase
|
||||
{
|
||||
public override PlatformABI PlatformABI { get; } = PlatformABI.Universal64;
|
||||
|
||||
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});
|
||||
{(!method.ReturnInfo.IsVoid ? $"*({method.ReturnInfo.Type.GetTypeName()}*)ret = " : "")}((NativeMethod)(method->methodPointerCallByInterp))({paramNameListStr});
|
||||
}}
|
||||
");
|
||||
}
|
||||
public override void GenerateNative2ManagedMethod(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" }));
|
||||
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)))} }};
|
||||
StackObject* ret = {(method.ReturnInfo.IsVoid ? "nullptr" : "args + " + method.ParamInfos.Count)};
|
||||
Interpreter::Execute(method, args, ret);
|
||||
{(!method.ReturnInfo.IsVoid ? $"return *({method.ReturnInfo.Type.GetTypeName()}*)ret;" : "")}
|
||||
}}
|
||||
");
|
||||
}
|
||||
|
||||
public override void GenerateAdjustThunkMethod(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" }));
|
||||
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))))} }};
|
||||
StackObject* ret = {(method.ReturnInfo.IsVoid ? "nullptr" : "args + " + method.ParamInfos.Count)};
|
||||
Interpreter::Execute(method, args, ret);
|
||||
{(!method.ReturnInfo.IsVoid ? $"return *({method.ReturnInfo.Type.GetTypeName()}*)ret;" : "")}
|
||||
}}
|
||||
");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 96d94c3da2c6a394590218ce38eaec72
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,68 @@
|
||||
using dnlib.DotNet;
|
||||
using HybridCLR.Editor.ABI;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using UnityEngine;
|
||||
|
||||
namespace HybridCLR.Editor.MethodBridge
|
||||
{
|
||||
public class PlatformGeneratorWebGL32 : PlatformGeneratorBase
|
||||
{
|
||||
public override PlatformABI PlatformABI { get; } = PlatformABI.WebGL32;
|
||||
|
||||
|
||||
public override void GenerateManaged2NativeMethod(MethodDesc method, List<string> lines)
|
||||
{
|
||||
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});
|
||||
{(!method.ReturnInfo.IsVoid ? $"*({method.ReturnInfo.Type.GetTypeName()}*)ret = " : "")}((NativeMethod)(method->methodPointerCallByInterp))({paramNameListStr});
|
||||
}}
|
||||
");
|
||||
}
|
||||
public override void GenerateNative2ManagedMethod(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" }));
|
||||
|
||||
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)))} }};
|
||||
StackObject* ret = {(method.ReturnInfo.IsVoid ? "nullptr" : "args + " + method.ParamInfos.Count)};
|
||||
Interpreter::Execute(method, args, ret);
|
||||
{(!method.ReturnInfo.IsVoid ? $"return *({method.ReturnInfo.Type.GetTypeName()}*)ret;" : "")}
|
||||
}}
|
||||
");
|
||||
}
|
||||
public override void GenerateAdjustThunkMethod(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" }));
|
||||
|
||||
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))))} }};
|
||||
StackObject* ret = {(method.ReturnInfo.IsVoid ? "nullptr" : "args + " + method.ParamInfos.Count)};
|
||||
Interpreter::Execute(method, args, ret);
|
||||
{(!method.ReturnInfo.IsVoid ? $"return *({method.ReturnInfo.Type.GetTypeName()}*)ret;" : "")}
|
||||
}}
|
||||
");
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 2912d21f60f4c684785c31efcf2d9b29
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -33,7 +33,7 @@ namespace HybridCLR.Editor.ReversePInvokeWrap
|
||||
|
||||
public Analyzer(AssemblyCache cache, List<string> assemblyNames)
|
||||
{
|
||||
foreach (var assemblyName in assemblyNames)
|
||||
foreach(var assemblyName in assemblyNames)
|
||||
{
|
||||
_rootModules.Add(cache.LoadModule(assemblyName));
|
||||
}
|
||||
@@ -70,10 +70,10 @@ namespace HybridCLR.Editor.ReversePInvokeWrap
|
||||
}
|
||||
}
|
||||
|
||||
public List<ABIReversePInvokeMethodInfo> BuildABIMethods()
|
||||
public List<ABIReversePInvokeMethodInfo> BuildABIMethods(PlatformABI abi)
|
||||
{
|
||||
var methodsBySig = new Dictionary<string, ABIReversePInvokeMethodInfo>();
|
||||
var typeCreator = new TypeCreator();
|
||||
var typeCreator = TypeCreatorFactory.CreateTypeCreator(abi);
|
||||
foreach(var method in _reversePInvokeMethods)
|
||||
{
|
||||
MethodDesc desc = new MethodDesc
|
||||
@@ -82,6 +82,7 @@ namespace HybridCLR.Editor.ReversePInvokeWrap
|
||||
ReturnInfo = new ReturnInfo { Type = typeCreator.CreateTypeInfo(method.Method.ReturnType)},
|
||||
ParamInfos = method.Method.Parameters.Select(p => new ParamInfo { Type = typeCreator.CreateTypeInfo(p.Type)}).ToList(),
|
||||
};
|
||||
typeCreator.OptimizeMethod(desc);
|
||||
desc.Init();
|
||||
if (!methodsBySig.TryGetValue(desc.Sig, out var arm))
|
||||
{
|
||||
@@ -96,7 +97,7 @@ namespace HybridCLR.Editor.ReversePInvokeWrap
|
||||
arm.Count += preserveCount;
|
||||
}
|
||||
var methods = methodsBySig.Values.ToList();
|
||||
methods.Sort((a, b) => String.CompareOrdinal(a.Method.Sig, b.Method.Sig));
|
||||
methods.Sort((a, b) => a.Method.Sig.CompareTo(b.Method.Sig));
|
||||
return methods;
|
||||
}
|
||||
|
||||
|
||||
@@ -2,18 +2,16 @@
|
||||
using HybridCLR.Editor.Template;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using UnityEngine;
|
||||
|
||||
namespace HybridCLR.Editor.ReversePInvokeWrap
|
||||
{
|
||||
public class Generator
|
||||
{
|
||||
public void Generate(List<ABIReversePInvokeMethodInfo> methods, string outputFile)
|
||||
public void Generate(string template, PlatformABI abi, List<ABIReversePInvokeMethodInfo> methods, string outputFile)
|
||||
{
|
||||
string template = File.ReadAllText(outputFile, Encoding.UTF8);
|
||||
template = template.Replace("{PLATFORM_ABI}", ABIUtil.GetHybridCLRPlatformMacro(abi));
|
||||
var frr = new FileRegionReplace(template);
|
||||
var codes = new List<string>();
|
||||
|
||||
@@ -31,7 +29,6 @@ namespace HybridCLR.Editor.ReversePInvokeWrap
|
||||
codes.Add($@"
|
||||
{method.ReturnInfo.Type.GetTypeName()} __ReversePInvokeMethod_{methodIndex}({paramDeclaringListWithoutMethodInfoStr})
|
||||
{{
|
||||
il2cpp::vm::ScopedThreadAttacher _vmThreadHelper;
|
||||
const MethodInfo* method = MetadataModule::GetMethodInfoByReversePInvokeWrapperIndex({methodIndex});
|
||||
{methodTypeDef};
|
||||
{(method.ReturnInfo.IsVoid ? "" : "return ")}((Callback)(method->methodPointerCallByInterp))({paramNameListWithoutMethodInfoStr});
|
||||
|
||||
@@ -3,30 +3,25 @@ using System;
|
||||
using UnityEditor;
|
||||
using UnityEditorInternal;
|
||||
|
||||
namespace HybridCLR.Editor.Settings
|
||||
/// <summary>
|
||||
/// 监听编辑器状态,当编辑器重新 focus 时,重新加载实例,避免某些情景下 svn 、git 等外部修改了数据却无法同步的异常。
|
||||
/// </summary>
|
||||
[InitializeOnLoad]
|
||||
public static class EditorStatusWatcher
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// 监听编辑器状态,当编辑器重新 focus 时,重新加载实例,避免某些情景下 svn 、git 等外部修改了数据却无法同步的异常。
|
||||
/// </summary>
|
||||
[InitializeOnLoad]
|
||||
public static class EditorStatusWatcher
|
||||
public static Action OnEditorFocused;
|
||||
static bool isFocused;
|
||||
static EditorStatusWatcher() => EditorApplication.update += Update;
|
||||
static void Update()
|
||||
{
|
||||
public static Action OnEditorFocused;
|
||||
static bool isFocused;
|
||||
static EditorStatusWatcher() => EditorApplication.update += Update;
|
||||
static void Update()
|
||||
if (isFocused != InternalEditorUtility.isApplicationActive)
|
||||
{
|
||||
if (isFocused != InternalEditorUtility.isApplicationActive)
|
||||
isFocused = InternalEditorUtility.isApplicationActive;
|
||||
if (isFocused)
|
||||
{
|
||||
isFocused = InternalEditorUtility.isApplicationActive;
|
||||
if (isFocused)
|
||||
{
|
||||
HybridCLRSettings.LoadOrCreate();
|
||||
OnEditorFocused?.Invoke();
|
||||
}
|
||||
HybridCLRSettings.LoadOrCreate();
|
||||
OnEditorFocused?.Invoke();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -4,8 +4,7 @@ using UnityEditor;
|
||||
using UnityEditor.Presets;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
namespace HybridCLR.Editor.Settings
|
||||
namespace HybridCLR.Editor
|
||||
{
|
||||
public class HybridCLRSettingsProvider : SettingsProvider
|
||||
{
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
using UnityEditorInternal;
|
||||
using UnityEngine;
|
||||
|
||||
namespace HybridCLR.Editor.Settings
|
||||
namespace HybridCLR.Editor
|
||||
{
|
||||
[FilePath("ProjectSettings/HybridCLRSettings.asset")]
|
||||
public class HybridCLRSettings : ScriptableSingleton<HybridCLRSettings>
|
||||
@@ -40,10 +39,10 @@ namespace HybridCLR.Editor.Settings
|
||||
public string[] patchAOTAssemblies;
|
||||
|
||||
[Header("生成的link.xml路径")]
|
||||
public string outputLinkFile = "HybridCLRGenerate/link.xml";
|
||||
public string outputLinkFile = "HybridCLRData/Generated/link.xml";
|
||||
|
||||
[Header("自动扫描生成的AOTGenericReferences.cs路径")]
|
||||
public string outputAOTGenericReferenceFile = "HybridCLRGenerate/AOTGenericReferences.cs";
|
||||
public string outputAOTGenericReferenceFile = "HybridCLRData/Generated/AOTGenericReferences.cs";
|
||||
|
||||
[Header("AOT泛型实例化搜索迭代次数")]
|
||||
public int maxGenericReferenceIteration = 10;
|
||||
|
||||
@@ -1,39 +1,21 @@
|
||||
using HybridCLR.Editor.Installer;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
|
||||
namespace HybridCLR.Editor.Settings
|
||||
public static class MenuProvider
|
||||
{
|
||||
public static class MenuProvider
|
||||
{
|
||||
[MenuItem("HybridCLR/Settings", priority = 200)]
|
||||
public static void OpenSettings() => SettingsService.OpenProjectSettings("Project/HybridCLR Settings");
|
||||
[MenuItem("HybridCLR/Documents/", menuItem = "HybridCLR/Documents/Quick Start")]
|
||||
public static void OpenQuickStart() => Application.OpenURL("https://focus-creative-games.github.io/hybridclr/start_up/");
|
||||
[MenuItem("HybridCLR/Documents/", menuItem = "HybridCLR/Documents/Benchmark")]
|
||||
public static void OpenBenchmark() => Application.OpenURL("https://focus-creative-games.github.io/hybridclr/benchmark/");
|
||||
[MenuItem("HybridCLR/Documents/", menuItem = "HybridCLR/Documents/FAQ")]
|
||||
public static void OpenFAQ() => Application.OpenURL("https://focus-creative-games.github.io/hybridclr/faq/");
|
||||
[MenuItem("HybridCLR/Documents/", menuItem = "HybridCLR/Documents/Common Errors")]
|
||||
public static void OpenCommonErrors() => Application.OpenURL("https://focus-creative-games.github.io/hybridclr/common_errors/");
|
||||
[MenuItem("HybridCLR/Documents/", menuItem = "HybridCLR/Documents/Bug Report")]
|
||||
public static void OpenBugReport() => Application.OpenURL("https://focus-creative-games.github.io/hybridclr/bug_reporter/");
|
||||
[MenuItem("HybridCLR/Documents/", menuItem = "HybridCLR/Documents/About HybridCLR")]
|
||||
public static void OpenAbout() => Application.OpenURL("https://focus-creative-games.github.io/hybridclr/about/");
|
||||
}
|
||||
|
||||
[MenuItem("HybridCLR/About", priority = 0)]
|
||||
public static void OpenAbout() => Application.OpenURL("https://hybridclr.doc.code-philosophy.com/docs/intro");
|
||||
|
||||
[MenuItem("HybridCLR/Installer...", priority = 60)]
|
||||
private static void Open()
|
||||
{
|
||||
InstallerWindow window = EditorWindow.GetWindow<InstallerWindow>("HybridCLR Installer", true);
|
||||
window.minSize = new Vector2(800f, 500f);
|
||||
}
|
||||
|
||||
[MenuItem("HybridCLR/Settings...", priority = 61)]
|
||||
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/docs/beginner/quickstart");
|
||||
|
||||
[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/docs/help/faq");
|
||||
|
||||
[MenuItem("HybridCLR/Documents/Common Errors")]
|
||||
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/docs/help/issue");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -5,7 +5,7 @@ using UnityEditor;
|
||||
using UnityEditorInternal;
|
||||
using UnityEngine;
|
||||
|
||||
namespace HybridCLR.Editor.Settings
|
||||
namespace HybridCLR.Editor
|
||||
{
|
||||
public class ScriptableSingleton<T> : ScriptableObject where T : ScriptableObject
|
||||
{
|
||||
@@ -31,7 +31,7 @@ namespace HybridCLR.Editor.Settings
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.LogError($"save location of {nameof(ScriptableSingleton<T>)} is invalid");
|
||||
Debug.LogError($"{nameof(ScriptableSingleton<T>)}: 请指定单例存档路径! ");
|
||||
}
|
||||
return s_Instance;
|
||||
}
|
||||
@@ -59,10 +59,9 @@ namespace HybridCLR.Editor.Settings
|
||||
protected static string GetFilePath()
|
||||
{
|
||||
return typeof(T).GetCustomAttributes(inherit: true)
|
||||
.Where(v => v is FilePathAttribute)
|
||||
.Cast<FilePathAttribute>()
|
||||
.FirstOrDefault()
|
||||
?.filepath;
|
||||
.Cast<FilePathAttribute>()
|
||||
.FirstOrDefault(v => v != null)
|
||||
?.filepath;
|
||||
}
|
||||
}
|
||||
[AttributeUsage(AttributeTargets.Class)]
|
||||
|
||||
@@ -2,7 +2,7 @@ using UnityEditor;
|
||||
using UnityEditor.Presets;
|
||||
using UnityEngine;
|
||||
|
||||
namespace HybridCLR.Editor.Settings
|
||||
namespace HybridCLR.Editor
|
||||
{
|
||||
public class SettingsPresetReceiver : PresetSelectorReceiver
|
||||
{
|
||||
|
||||
@@ -5,7 +5,6 @@ using System.Linq;
|
||||
using UnityEditor;
|
||||
using UnityEditorInternal;
|
||||
using UnityEngine;
|
||||
using HybridCLR.Editor.Settings;
|
||||
|
||||
|
||||
namespace HybridCLR.Editor
|
||||
@@ -22,7 +21,7 @@ namespace HybridCLR.Editor
|
||||
}
|
||||
}
|
||||
|
||||
public static string PackageName { get; } = "com.code-philosophy.hybridclr";
|
||||
public static string PackageName { get; } = "com.focus-creative-games.hybridclr_unity";
|
||||
|
||||
public static string HybridCLRDataPathInPackage => $"Packages/{PackageName}/Data~";
|
||||
|
||||
@@ -32,6 +31,10 @@ namespace HybridCLR.Editor
|
||||
|
||||
public static string ScriptingAssembliesJsonFile { get; } = "ScriptingAssemblies.json";
|
||||
|
||||
public static string GlobalgamemanagersBinFile { get; } = "globalgamemanagers";
|
||||
|
||||
public static string Dataunity3dBinFile { get; } = "data.unity3d";
|
||||
|
||||
public static string HotUpdateDllsRootOutputDir => HybridCLRSettings.Instance.hotUpdateDllCompileOutputRootDir;
|
||||
|
||||
public static string AssembliesPostIl2CppStripDir => HybridCLRSettings.Instance.strippedAOTDllOutputRootDir;
|
||||
@@ -46,10 +49,6 @@ namespace HybridCLR.Editor
|
||||
|
||||
public static string Il2CppBuildCacheDir { get; } = $"{ProjectDir}/Library/Il2cppBuildCache";
|
||||
|
||||
public static string GlobalgamemanagersBinFile { get; } = "globalgamemanagers";
|
||||
|
||||
public static string Dataunity3dBinFile { get; } = "data.unity3d";
|
||||
|
||||
public static string GetHotUpdateDllsOutputDirByTarget(BuildTarget target)
|
||||
{
|
||||
return $"{HotUpdateDllsRootOutputDir}/{target}";
|
||||
@@ -100,7 +99,7 @@ namespace HybridCLR.Editor
|
||||
{
|
||||
if (allAsses.Contains(assemblyName))
|
||||
{
|
||||
throw new Exception($"[HotUpdateAssemblyNamesIncludePreserved] assembly:'{assemblyName}' is duplicated");
|
||||
throw new Exception($"[HotUpdateAssemblyNamesIncludePreserved] assembly:'{assemblyName}' 重复");
|
||||
}
|
||||
allAsses.Add(assemblyName);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2023 Code Philosophy Technology Ltd.
|
||||
Copyright (c) 2022 focus creative games
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
||||
@@ -1,91 +1,11 @@
|
||||
# hybridclr_unity
|
||||
|
||||
- [README 中文](./README_zh.md)
|
||||
- [README English](./README.md)
|
||||
Unity Package for HybridCLR
|
||||
|
||||
# HybridCLR
|
||||
## 改动日志
|
||||
|
||||
[](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,大幅缩短安装时间
|
||||
|
||||

|
||||
|
||||
<br/>
|
||||
<br/>
|
||||
|
||||
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/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/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.
|
||||
|
||||

|
||||
|
||||
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 C# Hot-Update Solution
|
||||
|
||||
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.
|
||||
|
||||
## Supported Versions And Platforms
|
||||
|
||||
- Support 2019.4.x, 2020.3.x, 2021.3.x, 2022.3.x full series of LTS versions. The `2023.2.0ax` version is also supported, but not released to the public.
|
||||
- Supports all il2cpp supported platforms
|
||||
|
||||
## Stability Status
|
||||
|
||||
HybridCLR has been widely verified as a very efficient and stable solution for hot update of Unity.
|
||||
|
||||
The official versions of **extremely stable** 1.x, 2.x, and 3.x are currently released, which are sufficient to meet the stability requirements of large and medium-sized commercial projects.
|
||||
At present, at least thousands of commercial game projects have been integrated, and hundreds of them have been launched on both ends. The online projects include MMORPG, heavy card, heavy tower defense and other games. **Most top game companies** (such as Tencent and NetEase) are already using HybridCLR.
|
||||
|
||||
You can read the [game projects in top game companies](https://hybridclr.doc.code-philosophy.com/en/docs/other/businesscase) those are using HybridCLR and has been launched.
|
||||
|
||||
## Support And Contact
|
||||
|
||||
- Official 1 group: 651188171 (full)
|
||||
- Novice QQ group 1: 428404198 (full)
|
||||
- Novice QQ group 2: **680274677 (recommended)**
|
||||
- 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
|
||||
|
||||
@@ -1,91 +0,0 @@
|
||||
- [README 中文](./README_zh.md)
|
||||
- [README English](./README.md)
|
||||
|
||||
# HybridCLR
|
||||
|
||||
[](https://github.com/focus-creative-games/hybridclr/blob/main/LICENSE)
|
||||
|
||||

|
||||
|
||||
<br/>
|
||||
<br/>
|
||||
|
||||
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/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/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"混合运行方式。
|
||||
|
||||

|
||||
|
||||
更具体地说,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全系列LTS版本。`2023.2.0ax`版本也已支持,但未对外发布。
|
||||
- 支持所有il2cpp支持的平台
|
||||
|
||||
## 稳定性状况
|
||||
|
||||
HybridCLR已经被广泛验证是非常高效、稳定的Unity热更新解决方案。
|
||||
|
||||
当前发布了**极其稳定**的1.x、2.x、3.x正式版本,足以满足大中型商业项目的稳定性要求。
|
||||
目前至少有上千个商业游戏项目完成接入,其中有几百款已经双端上线,上线的项目中包括MMORPG、重度卡牌、重度塔防之类的游戏。**绝大多数头部游戏公司**(如腾讯、网易)都已经在使用HybridCLR。
|
||||
|
||||
可查看我们已知的头部公司中使用HybridCLR并且已经上线的[项目列表](https://hybridclr.doc.code-philosophy.com/docs/other/businesscase)。
|
||||
|
||||
|
||||
## 支持与联系
|
||||
|
||||
- 官方1群:651188171(满)
|
||||
- 新手1群:428404198(满)
|
||||
- 新手2群:**680274677(推荐)**
|
||||
- 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
|
||||
+23
-496
@@ -1,520 +1,47 @@
|
||||
# 发布日志
|
||||
|
||||
## 5.3.0
|
||||
|
||||
发布日期 2024.4.22.
|
||||
|
||||
### Runtime
|
||||
|
||||
- [fix] 修复WebGL平台MachineState::CollectFramesWithoutDuplicates错误地使用hybridclr::metadata::IsInterpreterMethod移除热更新函数,导致补充元数据函数没有移除,StackFrames列表越来越长,打印Stack时死循环的bug。调整实现,统一使用il2cpp::vm::StackTrace::PushFrame及PopFrame实现完美的解释器栈打印。缺点是调用解释器函数增加了维护栈的开销
|
||||
- [fix] 修复StringUtils::Utf16ToUtf8未正确处理maxinumSize==0,导致InterpreterImage::ConvertConstValue中转换长度为0的string时巨幅溢出的严重bug
|
||||
- [fix] 修复__ReversePInvokeMethod_XXX函数未设置Il2CppThreadContext,导致从native线程回调时获取Thread变量崩溃的bug
|
||||
- [merge] 合并 2021.3.34-2021.3.37f1 il2cpp改动
|
||||
- [merge] 合并 2022.3.19-2022.3.23f1 il2cpp改动
|
||||
|
||||
### Editor
|
||||
|
||||
- [fix] 修复导出tvOS工程时未修改xcode工程设置,导致打包失败的bug
|
||||
- [fix] 修复构建tvOS目标时未复制裁剪AOT dll,导致生成桥接函数失败的bug
|
||||
- [fix] 解决StripAOTDllCommand生成的临时项目的locationPathName不规范导致与某些插件如Embeded Browser不兼容的问题
|
||||
- [fix] 修复团结引擎1.1.0起删除TUANJIE_2022宏导致没有复制裁剪后的AOT程序集的bug
|
||||
- [fix] 修复__ReversePInvokeMethod_XXX函数未设置Il2CppThreadContext,导致从native线程回调时获取Thread变量崩溃的bug
|
||||
- [fix] 修复iOS平台开启development build选项时出现mono相关头文件找不到的bug
|
||||
|
||||
## 5.2.1
|
||||
|
||||
发布日期 2024.4.7.
|
||||
|
||||
### Runtime
|
||||
|
||||
- [fix] 修复WebGL平台不打印堆栈日志的bug
|
||||
- [fix] 修复RuntimeConfig::GetRuntimeOption获取InterpreterThreadExceptionFlowSize错误返回s_threadFrameStackSize的bug
|
||||
|
||||
### Editor
|
||||
|
||||
- [opt] LoadModule中设置 mod.EnableTypeDefFindCache = true,计算桥接函数的时间缩短为原来的1/3
|
||||
- [fix] 修复团结引擎导出iOS平台xcode工程文件名改名为Tuanjie-iPhone.xcodeproj导致构建xcode工程失败的bug
|
||||
|
||||
## 5.2.0
|
||||
|
||||
发布日期 2024.3.25.
|
||||
|
||||
### Runtime
|
||||
|
||||
- [new] 支持团结引擎
|
||||
- [new] 支持函数指针,支持IL2CPP_TYPE_FNPTR类型
|
||||
- [fix] 修复SetMdArrElementVarVar_ref指令未SetWriteBarrier的bug
|
||||
- [fix] InvokeSingleDelegate当调用一个未补充元数据的泛型函数时,发生崩溃的bug
|
||||
- [fix] 修复InterpreterDelegateInvoke调用delegate时,如果delegate指向未补充元数据的泛型函数,发生崩溃的bug
|
||||
- [fix] 修复当BlobStream为空时, RawImage::GetBlobFromRawIndex断言index < _streamBlobHeap.size失败的bug
|
||||
- [change] 重构metadata index设计,允许分配最多3个64M dll,16个16M dll,64个4M dll,255个1M dll
|
||||
|
||||
### Editor
|
||||
|
||||
- [new] 支持团结引擎
|
||||
- [fix] 修复GenericArgumentContext不支持ElementType.FnPtr的bug
|
||||
- [change] 为RuntimeApi添加[Preserve]特性,避免被裁剪
|
||||
|
||||
## 5.1.0
|
||||
|
||||
发布日期 2024.2.26.
|
||||
|
||||
### Runtime
|
||||
|
||||
- [fix] 修复2021未实现System.ByReference`1的.ctor及get_Value函数引发的运行错误的问题,il2cpp通过特殊的instrinct函数实现了正常运行
|
||||
- [opt] 优化元数据加载,将部分元数据改为延迟加载,大约减少30%的Assembly::Load的执行时间
|
||||
- [change] tempRet由Interpreter::Execute的局部变量改为CallDelegateInvoke_xxx的局部变量,减少嵌套过深时栈溢出的可能性
|
||||
|
||||
## 5.0.0
|
||||
|
||||
发布日期 2024.1.26.
|
||||
|
||||
### Runtime
|
||||
|
||||
- [new] 恢复对2019支持
|
||||
- [fix] 修复未按依赖顺序加载dll,由于在创建Image时缓存了当时的程序集列表,如果被依赖的程序集在本程序集后加载,延迟访问时由于不在缓存程序集列表而出现TypeLoadedException的bug
|
||||
|
||||
|
||||
### Editor
|
||||
|
||||
- [new] 恢复对2019支持
|
||||
- [new] 支持2019版本在iOS平台以源码形式构建
|
||||
- [new] 新增 AOTAssemblyMetadataStripper用于剔除AOT dll中非泛型函数元数据
|
||||
- [new] 新增 MissingMetadataChecker检查裁剪类型或者函数丢失的问题
|
||||
- [opt] 优化 AOTReference计算,如果泛型的所有泛型参数都是class约束,则不加入到需要补充元数据的集合
|
||||
- [change] 为了支持团结引擎而作了一些调整(注意,支持团结引擎的il2cpp_plus分支并未公开)
|
||||
|
||||
## 4.0.15
|
||||
|
||||
发布日期 2024.1.2.
|
||||
|
||||
### Runtime
|
||||
|
||||
- [fix] 修复计算未完全实例化的泛型类时将VAR和MVAR类型参数大小计算成sizeof(void*),导致计算出无效且过大的instance,在执行LayoutFieldsLocked过程中调用UpdateInstanceSizeForGenericClass错误地使用泛型基类instance覆盖设置了实例类型的instance值的严重bug
|
||||
- [change] 支持打印热更新栈,虽然顺序不太正确
|
||||
- [change] 使用HYBRIDCLR_MALLOC之类分配函数替换IL2CPP_MALLOC
|
||||
- [refactor] 重构Config接口,统一通过GetRuntimeOption和SetRuntimeOption获取和设置选项
|
||||
- [opt] 删除NewValueTypeVar和NewValueTypeInterpVar指令不必要的对结构memset操作
|
||||
|
||||
### Editor
|
||||
|
||||
- [fix] 修复Additional Compiler Arguments中输入 -nullable:enable 之后,Editor抛出InvalidCastException的bug。来自报告 https://github.com/focus-creative-games/hybridclr/issues/116
|
||||
- [fix] 修复某些情况下报错:BuildFailedException: Build path contains a project previously built without the "Create Visual Studio Solution"
|
||||
- [opt] 优化桥接函数生成,将同构的struct映射到同一个结构,减少了30-35%的桥接函数数量
|
||||
- [change] StripAOTDllCommand导出时不再设置BuildScriptsOnly选项
|
||||
- [change] 调整Installer窗口的显示内容
|
||||
- [refactor] RuntimeApi中设置hybridclr参数的功能统一通过GetRuntimeOption和SetRuntimeOption函数
|
||||
|
||||
## 4.0.14
|
||||
|
||||
发布日期 2023.12.11.
|
||||
|
||||
### Runtime
|
||||
|
||||
- [fix] 修复优化 box; brtrue|brfalse序列时,当类型为class或nullable类型时,无条件转换为无条件branch语句的bug
|
||||
- [fix] 修复 ClassFieldLayoutCalculator未释放 _classMap的每个key-value对中value对象,造成内存泄露的bug
|
||||
- [fix] 修复计算 ExplicitLayout的struct的native_size的bug
|
||||
- [fix] 修复当出现签名完全相同的虚函数与虚泛型函数时,计算override未考虑泛型签名,错误地返回了不匹配的函数,导致虚表错误的bug
|
||||
- [fix][2021] 修复开启faster(smaller) build选项后某些情况下完全泛型共享AOT函数未使用补充元数据来设置函数指针,导致调用时出错的bug
|
||||
|
||||
## 4.0.13
|
||||
|
||||
发布日期 2023.11.27.
|
||||
|
||||
### Runtime
|
||||
|
||||
- [fix] 修复ConvertInvokeArgs有可能传递了非对齐args,导致CopyStackObject在armv7这种要求内存对齐的平台发生崩溃的bug
|
||||
- [fix] 修复通过StructLayout指定size时,计算ClassFieldLayout的严重bug
|
||||
- [fix] 修复bgt之类指令未取双重取反进行判断,导致当浮点数与Nan比较时由于不满足对称性执行了错误的分支的bug
|
||||
- [fix] 修复Class::FromGenericParameter错误地设置了thread_static_fields_size=-1,导致为其分配ThreadStatic内存的严重bug
|
||||
- [opt] Il2CppGenericInst分配统一使用MetadataCache::GetGenericInst分配唯一池对象,优化内存分配
|
||||
- [opt] 由于Interpreter部分Il2CppGenericInst统一使用MetadataCache::GetGenericInst,比较 Il2CppGenericContext时直接比较 class_inst和method_inst指针
|
||||
|
||||
### Editor
|
||||
|
||||
- [fix] 修复裁剪aot dll中出现netstandard时,生成桥接函数异常的bug
|
||||
- [fix] 修复当出现非常规字段名时生成的桥接函数代码文件有编译错误的bug
|
||||
- [change] 删除不必要的Datas~/Templates目录,直接以原始文件为模板
|
||||
- [refactor] 重构 AssemblyCache和 AssemblyReferenceDeepCollector,消除冗余代码
|
||||
|
||||
## 4.0.12
|
||||
|
||||
发布日期 2023.11.02.
|
||||
|
||||
### Editor
|
||||
|
||||
- [fix] 修复BashUtil.RemoveDir的bug导致Installer安装失败的bug
|
||||
|
||||
## 4.0.11
|
||||
|
||||
发布日期 2023.11.02.
|
||||
|
||||
### Runtime
|
||||
|
||||
- [fix] 修复开启完全泛型共享后, 对于某些MethodInfo,由于methodPointer与virtualMethodPointer使用补充元数据后的解释器函数,而invoker_method仍然为支持完全泛型共享的调用形式,导致invoker_method与methodPointer及virtualMethodPointer不匹配的bug
|
||||
- [fix] 修复Il2CppGenericContextCompare比较时仅仅对比inst指针的bug,造成热更新模块大量泛型函数重复
|
||||
- [fix] 修复完全泛型共享时未正确设置MethodInfo的bug
|
||||
|
||||
### Editor
|
||||
|
||||
- [new] 检查当前安装的libil2cpp版本是否与package版本匹配,避免升级package后未重新install的问题
|
||||
- [new] Generate支持 netstandard
|
||||
- [fix] 修复 ReversePInvokeWrap生成不必要地解析referenced dll,导致如果有aot dll引用了netstandard会出现解析错误的bug
|
||||
- [fix] 修复BashUtil.RemoveDir在偶然情况下出现删除目录失败的问题。新增多次重试
|
||||
- [fix] 修复桥接函数计算时未归结函数参数类型,导致出现多个同名签名的bug
|
||||
|
||||
|
||||
## 4.0.10
|
||||
|
||||
发布日期 2023.10.12.
|
||||
|
||||
### Runtime
|
||||
|
||||
- [merge][il2cpp] 合并2022.3.10-2022.3.11f1的il2cpp改动,修复2022.3.11版本不兼容的问题
|
||||
|
||||
## 4.0.9
|
||||
|
||||
发布日期 2023.10.11.
|
||||
|
||||
### Runtime
|
||||
|
||||
- [merge][il2cpp][fix] 合并2021.3.29-2021.3.31f1的il2cpp改动,修复在2021.3.31版本的不兼容问题
|
||||
- [merge][il2cpp] 合并2022.3.7-2022.3.10f1的il2cpp改动
|
||||
|
||||
### Editor
|
||||
|
||||
- [fix] 修复2022版本iOS平台AddLil2cppSourceCodeToXcodeproj2022OrNewer的编译错误
|
||||
|
||||
## 4.0.8
|
||||
|
||||
发布日期 2023.10.10.
|
||||
|
||||
### Runtime
|
||||
|
||||
- [fix] 修复计算值类型泛型桥接函数签名时,错误地将值类型泛型参数类型也换成签名,导致与Editor计算的签名不一致的bug
|
||||
- [fix][refactor] RuntimeApi相关函数由PInvoke改为InternalCall,解决Android平台调用RuntimeApi时触发重新加载libil2cpp.a的问题
|
||||
|
||||
### Editor
|
||||
|
||||
- [refactor] RuntimeApi相关函数由PInvoke改为InternalCall
|
||||
- [refactor] 调整HybridCLR.Editor模块一些不规范的命名空间
|
||||
|
||||
## 4.0.7
|
||||
|
||||
发布日期 2023.10.09.
|
||||
|
||||
### Runtime
|
||||
|
||||
- [fix] 修复initobj调用了CopyN,但CopyN未考虑对象的内存对齐的情况,在32位这种的平台可能发生未对齐访问异常的bug
|
||||
- [fix] 修复计算未完全实例化的泛型函数的桥接函数签名时崩溃的bug
|
||||
- [fix] 修复Il2cpp代码生成选项为faster(smaller)时,2021和2022版本GenericMethod::CreateMethodLocked的bug
|
||||
- [remove] 移除所有array相关指令中index为int64_t的指令,简化代码
|
||||
- [remove] 移除ldfld_xxx_ref系列指令
|
||||
|
||||
### Editor
|
||||
|
||||
- [fix] 修复生成桥接函数时,如果热更新程序集未包含任何代码直接引用了某个aot程序集,则没有为该aot程序集生成桥接函数,导致出现NotSupportNative2Managed异常的bug
|
||||
- [fix] 修复mac下面路径过长导致拷贝文件失败的bug
|
||||
- [fix] 修复发布PS5目标时未处理ScriptingAssemblies.json的bug
|
||||
- [change] 打包时清空裁减aot dll目录
|
||||
|
||||
## 4.0.6
|
||||
|
||||
发布日期 2023.09.26.
|
||||
|
||||
### Runtime
|
||||
|
||||
- [fix] 修复2021和2022版本开启完全泛型共享后的bug
|
||||
- [fix] 修复加载PlaceHolder Assembly后未增加assemblyVersion导致Assembly::GetAssemblies()错误地获得了旧程序集列表的bug
|
||||
|
||||
## 4.0.5
|
||||
|
||||
发布日期 2023.09.25.
|
||||
|
||||
### Runtime
|
||||
|
||||
- [fix] 修复Transform中未析构pendingFlows造成内存泄露的bug
|
||||
- [fix] 修复多维数组SetMdArrElement未区分带ref与不带ref结构的bug
|
||||
- [fix] 修复CpobjVarVAr_WriteBarrier_n_4未设置size的bug
|
||||
- [fix] 修复计算interface成员函数slot时未考虑到static之类函数的bug
|
||||
- [fix] 修复2022版本ExplicitLayout未设置layout.alignment,导致计算出size==0的bug
|
||||
- [fix] 修复InterpreterInvoke在完全泛型共享时,class类型的methodPointer与virtualMethodPointer有可能不一致,导致失误对this指针+1的bug
|
||||
- [fix] ldobj当T为byte之类size<4的类型时,未将数据展开为int的bug
|
||||
- [fix] 修复CopySize未考虑到内存对齐的问题
|
||||
- [opt] 优化stelem当元素为size较大的struct时统一当作含ref结构的问题
|
||||
- [opt] TemporaryMemoryArena默认内存块大小由1M调整8K
|
||||
- [opt] 将Image::Image中Assembly::GetAllAssemblies()换成Assembly::GetAllAssemblies(AssemblyVector&),避免创建assembly快照而造成不必要的内存泄露
|
||||
|
||||
### Editor
|
||||
|
||||
- [fix] 修复StandaloneLinux平台DllImport的dllName和裁剪dll路径的错误
|
||||
- [change] 对于小版本不兼容的Unity版本,不再禁止安装,而是提示警告
|
||||
- [fix] 修复桥接函数计算中MetaUtil.ToShareTypeSig将Ptr和ByRef计算成IntPtr的bug,正确应该是UIntPtr
|
||||
|
||||
## 4.0.4
|
||||
|
||||
发布日期 2023.09.11。
|
||||
|
||||
### Runtime
|
||||
|
||||
- [new][platform] 彻底支持所有平台,包括UWP和PS5
|
||||
- [fix][严重] 修复计算interpreter部分enum类型的桥接函数签名的bug
|
||||
- [fix] 修复在某些平台下有编译错误的问题
|
||||
- [fix] 修复转换STOBJ指令未正确处理增量式GC的bug
|
||||
- [fix] [fix] 修复 StindVarVar_ref指令未正确设置WriteBarrier的bug
|
||||
- [fix] 修复2020 GenericMethod::CreateMethodLocked调用vm::MetadataAllocGenericMethod()未持有s_GenericMethodMutex锁的线程安全问题
|
||||
|
||||
### Editor
|
||||
|
||||
- [fix] 修复AddLil2cppSourceCodeToXcodeproj2021OrOlder在Unity 2020下偶然同时包含了不同目录的两个ThreadPool.cpp文件导致出现编译错误的问题
|
||||
- [fix] 修复不正确地从EditorUserBuildSettings.selectedBuildTargetGroup获得BuildGroupTarget的bug
|
||||
- [fix] StripAOTDllCommand生成AOT dll时的BuildOption采用当前Player的设置,避免当打包开启development时,StripAOTDllCommand生成Release aot dll,而打包生成debug aot dll,产生补充元数据及桥接函数生成不匹配的严重错误
|
||||
- [change] 为了更好地支持全平台,调整了RuntimeApi.cs中dllName的实现,默认取 __Internal
|
||||
- [change] 为了更好地支持全平台,自2021起裁剪AOT dll全都通过MonoHook复制
|
||||
|
||||
## 4.0.3
|
||||
|
||||
发布日期 2023.08.31。
|
||||
|
||||
### Editor
|
||||
|
||||
- [fix] 修复桥接函数计算的bug
|
||||
|
||||
## 4.0.2
|
||||
|
||||
发布日期 2023.08.29。
|
||||
|
||||
### Runtime
|
||||
|
||||
- [fix][严重] 修复LdobjVarVar_ref指令的bug。此bug由增量式GC代码引入
|
||||
- [fix] 修复未处理ResolveField获得的Field为nullptr时情形导致崩溃的bug
|
||||
- [fix] 修复未正确处理AOT及interpreter interface中显式实现父接口函数的bug
|
||||
|
||||
## 4.0.1
|
||||
|
||||
发布日期 2023.08.28。
|
||||
|
||||
### Runtime
|
||||
|
||||
- [fix] 修复2020版本开启增量式GC后出现编译错误的问题
|
||||
|
||||
## 4.0.0
|
||||
|
||||
发布日期 2023.08.28。
|
||||
|
||||
### Runtime
|
||||
|
||||
- [new] 支持增量式GC
|
||||
- [refactor] 重构桥接函数,彻底支持所有il2cpp支持的平台
|
||||
- [opt] 大幅优化Native2Managed方向的传参
|
||||
|
||||
### Editor
|
||||
|
||||
- [change] 删除增量式GC选项检查
|
||||
- [refactor] 重构桥接函数生成
|
||||
|
||||
## 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
|
||||
|
||||
- [new] 支持2022.3.0
|
||||
|
||||
## 3.0.0
|
||||
|
||||
### Runtime
|
||||
|
||||
- [fix] 修复不支持访问CustomData字段及值的bug
|
||||
- [remove] 移除对2019及2020版本支持
|
||||
|
||||
### Editor
|
||||
|
||||
- 包名更改为com.code-philosophy.hybridclr
|
||||
- 移除UnityFS插件
|
||||
- 移除Zip插件
|
||||
- HybridCLR菜单位置调整
|
||||
|
||||
## 2.4.2
|
||||
|
||||
### Runtime
|
||||
### 改动
|
||||
|
||||
- [version] 支持 2020.3.48,最后一个2020LTS版本
|
||||
- [version] 支持 2021.3.25
|
||||
- 支持 2020.3.48,最后一个2020LTS版本
|
||||
- 支持 2021.3.25
|
||||
- hybridclr 升级到 v2.3.1
|
||||
- il2cpp_plus 升级到 v2020-2.2.1 、v2021-2.2.1
|
||||
|
||||
## 2.4.1
|
||||
|
||||
### Runtime
|
||||
### 修复
|
||||
|
||||
### Editor
|
||||
|
||||
- [fix] 修复遗漏 RELEASELOG.md.meta 文件的问题
|
||||
- 修复遗漏 RELEASELOG.md.meta 文件的问题
|
||||
|
||||
## 2.4.0
|
||||
|
||||
### Runtime
|
||||
### 改动
|
||||
|
||||
### Editor
|
||||
- CheckSettings中检查ScriptingBackend及ApiCompatibleLevel,切换为正确的值
|
||||
- hybridclr 升级到v2.3.0版本
|
||||
- il2cpp_plus 升级到v2019-2.2.0、v2020-2.2.0、v2021-2.2.0版本
|
||||
|
||||
- [new] CheckSettings中检查ScriptingBackend及ApiCompatibleLevel,切换为正确的值
|
||||
- [new] 新增 MsvcStdextWorkaround.cs 解决2020 vs下stdext编译错误的问题
|
||||
- [fix] 修复当struct只包含一个float或double字段时,在arm64上计算桥接函数签名错误的bug
|
||||
### 修复
|
||||
|
||||
- 新增 MsvcStdextWorkaround.cs 解决2020 vs下stdext编译错误的问题
|
||||
- 修复当struct只包含一个float或double字段时,在arm64上计算桥接函数签名错误的bug
|
||||
|
||||
## 2.3.1
|
||||
|
||||
### Runtime
|
||||
|
||||
### Editor
|
||||
|
||||
- [fix] 修复本地复制libil2cpp却仍然从仓库下载安装的bug
|
||||
### 修复
|
||||
- 修复本地复制libil2cpp却仍然从仓库下载安装的bug
|
||||
|
||||
## 2.3.0
|
||||
|
||||
### Runtime
|
||||
### 改动
|
||||
|
||||
### Editor
|
||||
- Installer支持从本地目录复制改造后的libil2cpp
|
||||
|
||||
### 修复
|
||||
|
||||
- 修复2019版本MonoBleedingEdge的子目录中包含了过长路径的文件导致Installer复制文件出错的问题
|
||||
|
||||
- [new] Installer支持从本地目录复制改造后的libil2cpp
|
||||
- [fix] 修复2019版本MonoBleedingEdge的子目录中包含了过长路径的文件导致Installer复制文件出错的问题
|
||||
|
||||
|
||||
|
||||
+33
-53
@@ -1,97 +1,77 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using UnityEngine.Scripting;
|
||||
|
||||
namespace HybridCLR
|
||||
{
|
||||
[Preserve]
|
||||
public static class RuntimeApi
|
||||
{
|
||||
#if UNITY_STANDALONE_WIN
|
||||
private const string dllName = "GameAssembly";
|
||||
#elif UNITY_IOS || UNITY_STANDALONE_OSX || UNITY_WEBGL
|
||||
private const string dllName = "__Internal";
|
||||
#else
|
||||
private const string dllName = "il2cpp";
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// 加载补充元数据assembly
|
||||
/// </summary>
|
||||
/// <param name="dllBytes"></param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="NotSupportedException"></exception>
|
||||
#if UNITY_EDITOR
|
||||
public static unsafe LoadImageErrorCode LoadMetadataForAOTAssembly(byte[] dllBytes, HomologousImageMode mode)
|
||||
{
|
||||
#if UNITY_EDITOR
|
||||
return LoadImageErrorCode.OK;
|
||||
}
|
||||
#else
|
||||
[MethodImpl(MethodImplOptions.InternalCall)]
|
||||
public static extern LoadImageErrorCode LoadMetadataForAOTAssembly(byte[] dllBytes, HomologousImageMode mode);
|
||||
fixed(byte* data = dllBytes)
|
||||
{
|
||||
return (LoadImageErrorCode)LoadMetadataForAOTAssembly(data, dllBytes.Length, (int)mode);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 加载补充元数据assembly
|
||||
/// </summary>
|
||||
/// <param name="dllBytes"></param>
|
||||
/// <param name="dllSize"></param>
|
||||
/// <returns></returns>
|
||||
[DllImport(dllName, EntryPoint = "RuntimeApi_LoadMetadataForAOTAssembly")]
|
||||
public static extern unsafe int LoadMetadataForAOTAssembly(byte* dllBytes, int dllSize, int mode);
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 获取解释器线程栈的最大StackObject个数(size*8 为最终占用的内存大小)
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static int GetInterpreterThreadObjectStackSize()
|
||||
{
|
||||
return GetRuntimeOption(RuntimeOptionId.InterpreterThreadObjectStackSize);
|
||||
}
|
||||
[DllImport(dllName, EntryPoint = "RuntimeApi_GetInterpreterThreadObjectStackSize")]
|
||||
public static extern int GetInterpreterThreadObjectStackSize();
|
||||
|
||||
/// <summary>
|
||||
/// 设置解释器线程栈的最大StackObject个数(size*8 为最终占用的内存大小)
|
||||
/// </summary>
|
||||
/// <param name="size"></param>
|
||||
public static void SetInterpreterThreadObjectStackSize(int size)
|
||||
{
|
||||
SetRuntimeOption(RuntimeOptionId.InterpreterThreadObjectStackSize, size);
|
||||
}
|
||||
|
||||
[DllImport(dllName, EntryPoint = "RuntimeApi_SetInterpreterThreadObjectStackSize")]
|
||||
public static extern void SetInterpreterThreadObjectStackSize(int size);
|
||||
|
||||
/// <summary>
|
||||
/// 获取解释器线程函数帧数量(sizeof(InterpreterFrame)*size 为最终占用的内存大小)
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static int GetInterpreterThreadFrameStackSize()
|
||||
{
|
||||
return GetRuntimeOption(RuntimeOptionId.InterpreterThreadFrameStackSize);
|
||||
}
|
||||
[DllImport(dllName, EntryPoint = "RuntimeApi_GetInterpreterThreadFrameStackSize")]
|
||||
public static extern int GetInterpreterThreadFrameStackSize();
|
||||
|
||||
/// <summary>
|
||||
/// 设置解释器线程函数帧数量(sizeof(InterpreterFrame)*size 为最终占用的内存大小)
|
||||
/// </summary>
|
||||
/// <param name="size"></param>
|
||||
public static void SetInterpreterThreadFrameStackSize(int size)
|
||||
{
|
||||
SetRuntimeOption(RuntimeOptionId.InterpreterThreadFrameStackSize, size);
|
||||
}
|
||||
|
||||
|
||||
#if UNITY_EDITOR
|
||||
|
||||
private static readonly Dictionary<RuntimeOptionId, int> s_runtimeOptions = new Dictionary<RuntimeOptionId, int>();
|
||||
|
||||
public static void SetRuntimeOption(RuntimeOptionId optionId, int value)
|
||||
{
|
||||
s_runtimeOptions[optionId] = value;
|
||||
}
|
||||
#else
|
||||
[MethodImpl(MethodImplOptions.InternalCall)]
|
||||
public static extern void SetRuntimeOption(RuntimeOptionId optionId, int value);
|
||||
#endif
|
||||
|
||||
#if UNITY_EDITOR
|
||||
public static int GetRuntimeOption(RuntimeOptionId optionId)
|
||||
{
|
||||
if (s_runtimeOptions.TryGetValue(optionId, out var value))
|
||||
{
|
||||
return value;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
#else
|
||||
[MethodImpl(MethodImplOptions.InternalCall)]
|
||||
public static extern int GetRuntimeOption(RuntimeOptionId optionId);
|
||||
#endif
|
||||
[DllImport(dllName, EntryPoint = "RuntimeApi_SetInterpreterThreadFrameStackSize")]
|
||||
public static extern void SetInterpreterThreadFrameStackSize(int size);
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user