Compare commits

...

12 Commits

Author SHA1 Message Date
walon 019412fa81 [version] Release v7.4.0 2025-01-17 21:40:09 +08:00
walon 84bf6d59db [change] removed unnecessary field initialization in the HybridCLRSettings class. 2025-01-08 16:28:12 +08:00
walon 82163d2e50 [new] support preserve UnityEngine core types when GenerateLinkXml 2025-01-08 16:20:39 +08:00
walon 208372e6af [new] add MethodBridge.cpp.tpl. MethodBridgeGeneratorCommand doesn't generate and override from same file 2025-01-08 15:26:48 +08:00
walon dd8d812641 [change] add UnityVersion.h.tpl and AssemblyManifest.cpp.tpl, Il2CppDefGenerator doesn't generates and override code file from same one 2025-01-08 15:21:43 +08:00
walon c19b34542e [fix] fixed the bug where StripAOTDllCommand did not set BuildPlayerOptions.subtarget in Unity 2021+ versions, causing failure when publishing dedicated buildTarget. 2025-01-08 15:00:54 +08:00
walon e30306d7e1 [fix] fixed the bug in AOTAssemblyMetadataStripper::Strip where ModuleWriterOptions MetadataFlags.PreserveRids was not used. 2025-01-07 16:19:11 +08:00
walon 20f34c9b14 [fix] fix bug of computing CallingConvention of calli 2025-01-03 12:23:04 +08:00
walon 45749ffb5c [new] add Managed2NativeFunctionPointer MethodBridge functions 2025-01-02 22:22:59 +08:00
walon b176d63d93 [version] Release v7.3.0 2024-12-31 12:49:10 +08:00
walon 0c99afd58e [fix] fix the bug where MissingMetadataChecker can't detect references to newly added AOT assemblies. 2024-12-18 18:21:37 +08:00
walon 2458c9a9ba [fix] fix the issue in Unity 6000 where the modification of the trimmed AOT DLL output directory for the visionOS build target caused CopyStrippedAOTAssemblies::GetStripAssembliesDir2021 to fail in copying AOT DLLs. 2024-12-16 19:22:56 +08:00
23 changed files with 424 additions and 69 deletions
+12
View File
@@ -0,0 +1,12 @@
#include "../Il2CppCompatibleDef.h"
namespace hybridclr
{
const char* g_placeHolderAssemblies[] =
{
//!!!{{PLACE_HOLDER
//!!!}}PLACE_HOLDER
nullptr,
};
}
+32
View File
@@ -0,0 +1,32 @@
#include <codegen/il2cpp-codegen-metadata.h>
#if HYBRIDCLR_UNITY_2023_OR_NEW
#include <codegen/il2cpp-codegen.h>
#elif HYBRIDCLR_UNITY_2022
#include <codegen/il2cpp-codegen-il2cpp.h>
#elif HYBRIDCLR_UNITY_2020 || HYBRIDCLR_UNITY_2021
#include <codegen/il2cpp-codegen-common-big.h>
#else
#include <codegen/il2cpp-codegen-common.h>
#endif
#include "vm/ClassInlines.h"
#include "vm/Object.h"
#include "vm/Class.h"
#include "vm/ScopedThreadAttacher.h"
#include "../metadata/MetadataUtil.h"
#include "../interpreter/InterpreterModule.h"
#include "../interpreter/MethodBridge.h"
#include "../interpreter/Interpreter.h"
#include "../interpreter/MemoryUtil.h"
#include "../interpreter/InstrinctDef.h"
using namespace hybridclr::interpreter;
using namespace hybridclr::metadata;
//!!!{{CODE
//!!!}}CODE
+6
View File
@@ -0,0 +1,6 @@
#pragma once
//!!!{{UNITY_VERSION
//!!!}}UNITY_VERSION
+14 -14
View File
@@ -2,38 +2,38 @@
"versions": [
{
"unity_version":"2019",
"hybridclr" : { "branch":"v7.2.0"},
"il2cpp_plus": { "branch":"v2019-7.0.0"}
"hybridclr" : { "branch":"v7.4.0"},
"il2cpp_plus": { "branch":"v2019-7.4.0"}
},
{
"unity_version":"2020",
"hybridclr" : { "branch":"v7.2.0"},
"il2cpp_plus": { "branch":"v2020-7.0.0"}
"hybridclr" : { "branch":"v7.4.0"},
"il2cpp_plus": { "branch":"v2020-7.4.0"}
},
{
"unity_version":"2021",
"hybridclr" : { "branch":"v7.2.0"},
"il2cpp_plus": { "branch":"v2021-7.0.0"}
"hybridclr" : { "branch":"v7.4.0"},
"il2cpp_plus": { "branch":"v2021-7.4.0"}
},
{
"unity_version":"2022",
"hybridclr" : { "branch":"v7.2.0"},
"il2cpp_plus": { "branch":"v2022-7.2.0"}
"hybridclr" : { "branch":"v7.4.0"},
"il2cpp_plus": { "branch":"v2022-7.4.0"}
},
{
"unity_version":"2022-tuanjie",
"hybridclr" : { "branch":"v7.2.0"},
"il2cpp_plus": { "branch":"v2022-tuanjie-7.1.0"}
"hybridclr" : { "branch":"v7.4.0"},
"il2cpp_plus": { "branch":"v2022-tuanjie-7.4.0"}
},
{
"unity_version":"2023",
"hybridclr" : { "branch":"v6.2.0"},
"il2cpp_plus": { "branch":"v2023-6.0.0"}
"hybridclr" : { "branch":"v7.4.0"},
"il2cpp_plus": { "branch":"v2023-7.4.0"}
},
{
"unity_version":"6000",
"hybridclr" : { "branch":"v7.2.0"},
"il2cpp_plus": { "branch":"v6000-7.2.0"}
"hybridclr" : { "branch":"v7.4.0"},
"il2cpp_plus": { "branch":"v6000-7.4.0"}
}
]
}
+2 -2
View File
@@ -31,8 +31,8 @@ namespace HybridCLR.Editor.AOT
}
var writer = new System.IO.MemoryStream();
var options = new ModuleWriterOptions(mod);
options.MetadataOptions.Flags |= MetadataFlags.PreserveAll;
mod.Write(writer);
options.MetadataOptions.Flags |= MetadataFlags.PreserveRids;
mod.Write(writer, options);
writer.Flush();
return writer.ToArray();
}
@@ -47,10 +47,15 @@ namespace HybridCLR.Editor.BuildProcessors
#if UNITY_TVOS
case BuildTarget.tvOS:
#endif
return $"{projectDir}/Library/Bee/artifacts/iOS/ManagedStripped";
#if UNITY_VISIONOS
case BuildTarget.VisionOS:
#if UNITY_6000_0_OR_NEWER
return $"{projectDir}/Library/Bee/artifacts/VisionOS/ManagedStripped";
#else
return $"{projectDir}/Library/Bee/artifacts/iOS/ManagedStripped";
#endif
#endif
return $"{projectDir}/Library/Bee/artifacts/iOS/ManagedStripped";
case BuildTarget.WebGL:
return $"{projectDir}/Library/Bee/artifacts/WebGL/ManagedStripped";
case BuildTarget.StandaloneOSX:
+4 -2
View File
@@ -20,8 +20,10 @@ namespace HybridCLR.Editor.Commands
{
UnityVersion = Application.unityVersion,
HotUpdateAssemblies = SettingsUtil.HotUpdateAssemblyNamesIncludePreserved,
OutputFile = $"{SettingsUtil.LocalIl2CppDir}/libil2cpp/hybridclr/generated/UnityVersion.h",
OutputFile2 = $"{SettingsUtil.LocalIl2CppDir}/libil2cpp/hybridclr/generated/AssemblyManifest.cpp",
UnityVersionTemplateFile = $"{SettingsUtil.TemplatePathInPackage}/UnityVersion.h.tpl",
UnityVersionOutputFile = $"{SettingsUtil.LocalIl2CppDir}/libil2cpp/hybridclr/generated/UnityVersion.h",
AssemblyManifestTemplateFile = $"{SettingsUtil.TemplatePathInPackage}/AssemblyManifest.cpp.tpl",
AssemblyManifestOutputFile = $"{SettingsUtil.LocalIl2CppDir}/libil2cpp/hybridclr/generated/AssemblyManifest.cpp",
EnableProfilerInReleaseBuild = HybridCLRSettings.Instance.enableProfilerInReleaseBuild,
EnableStraceTraceInWebGLReleaseBuild = HybridCLRSettings.Instance.enableStraceTraceInWebGLReleaseBuild,
};
+1 -1
View File
@@ -28,7 +28,7 @@ namespace HybridCLR.Editor.Commands
List<string> hotfixAssemblies = SettingsUtil.HotUpdateAssemblyNamesExcludePreserved;
var analyzer = new Analyzer(MetaUtil.CreateHotUpdateAndAOTAssemblyResolver(target, hotfixAssemblies));
var refTypes = analyzer.CollectRefs(hotfixAssemblies);
var refTypes = analyzer.CollectRefs(hotfixAssemblies, !ls.dontPreserveUnityEngineCoreTypesInLinkXml);
Debug.Log($"[LinkGeneratorCommand] hotfix assembly count:{hotfixAssemblies.Count}, ref type count:{refTypes.Count} output:{Application.dataPath}/{ls.outputLinkFile}");
var linkXmlWriter = new LinkXmlWriter();
@@ -31,15 +31,16 @@ namespace HybridCLR.Editor.Commands
Directory.Delete(il2cppBuildCachePath, true);
}
private static void GenerateMethodBridgeCppFile(IReadOnlyCollection<GenericMethod> genericMethods, List<RawReversePInvokeMethodInfo> reversePInvokeMethods, string outputFile)
private static void GenerateMethodBridgeCppFile(IReadOnlyCollection<GenericMethod> genericMethods, List<RawReversePInvokeMethodInfo> reversePInvokeMethods, IReadOnlyCollection<RawCalliMethodSignatureInfo> calliMethodSignatures, string tempFile, string outputFile)
{
string templateCode = File.ReadAllText(outputFile, Encoding.UTF8);
string templateCode = File.ReadAllText(tempFile, Encoding.UTF8);
var g = new Generator(new Generator.Options()
{
TemplateCode = templateCode,
OutputFile = outputFile,
GenericMethods = genericMethods,
ReversePInvokeMethods = reversePInvokeMethods,
CalliMethodSignatures = calliMethodSignatures,
Development = EditorUserBuildSettings.development,
});
@@ -80,9 +81,13 @@ namespace HybridCLR.Editor.Commands
var reversePInvokeAnalyzer = new ReversePInvokeWrap.Analyzer(cache, hotUpdateDlls);
reversePInvokeAnalyzer.Run();
var calliAnalyzer = new CalliAnalyzer(cache, hotUpdateDlls);
calliAnalyzer.Run();
string templateFile = $"{SettingsUtil.TemplatePathInPackage}/MethodBridge.cpp.tpl";
string outputFile = $"{SettingsUtil.GeneratedCppDir}/MethodBridge.cpp";
GenerateMethodBridgeCppFile(methodBridgeAnalyzer.GenericMethods, reversePInvokeAnalyzer.ReversePInvokeMethods, outputFile);
GenerateMethodBridgeCppFile(methodBridgeAnalyzer.GenericMethods, reversePInvokeAnalyzer.ReversePInvokeMethods, calliAnalyzer.CalliMethodSignatures, templateFile, outputFile);
CleanIl2CppBuildCache();
}
+3
View File
@@ -139,6 +139,9 @@ namespace HybridCLR.Editor.Commands
options = buildOptions,
target = target,
targetGroup = BuildPipeline.GetBuildTargetGroup(target),
#if UNITY_2021_1_OR_NEWER
subtarget = (int)EditorUserBuildSettings.standaloneBuildSubtarget,
#endif
};
var report = BuildPipeline.BuildPlayer(buildPlayerOptions);
+12 -4
View File
@@ -13,17 +13,19 @@ namespace HybridCLR.Editor.HotUpdate
{
private readonly HashSet<string> _aotAssNames;
private readonly HashSet<string> _hotUpdateAssNames;
private readonly AssemblyCache _assCache;
public MissingMetadataChecker(string aotDllDir, IEnumerable<string> excludeDllNames)
public MissingMetadataChecker(string aotDllDir, IEnumerable<string> hotUpdateAssNames)
{
var excludeDllNameSet = new HashSet<string>(excludeDllNames ?? new List<string>());
_hotUpdateAssNames = new HashSet<string>(hotUpdateAssNames ?? new List<string>());
_aotAssNames = new HashSet<string>();
foreach (var aotFile in Directory.GetFiles(aotDllDir, "*.dll"))
{
string aotAssName = Path.GetFileNameWithoutExtension(aotFile);
if (excludeDllNameSet.Contains(aotAssName))
if (_hotUpdateAssNames.Contains(aotAssName))
{
continue;
}
@@ -34,6 +36,8 @@ namespace HybridCLR.Editor.HotUpdate
public bool Check(string hotUpdateDllPath)
{
bool anyMissing = false;
ModuleDef mod = ModuleDefMD.Load(File.ReadAllBytes(hotUpdateDllPath), _assCache.ModCtx);
foreach (var refass in mod.GetAssemblyRefs())
@@ -43,9 +47,13 @@ namespace HybridCLR.Editor.HotUpdate
{
_assCache.LoadModule(refass.Name, true);
}
else if (!_hotUpdateAssNames.Contains(refAssName))
{
UnityEngine.Debug.LogError($"Missing AOT Assembly: {refAssName}");
anyMissing = true;
}
}
bool anyMissing = false;
foreach (TypeRef typeRef in mod.GetTypeRefs())
{
+12 -8
View File
@@ -17,9 +17,13 @@ namespace HybridCLR.Editor.Il2CppDef
{
public List<string> HotUpdateAssemblies { get; set; }
public string OutputFile { get; set; }
public string UnityVersionTemplateFile { get; set; }
public string OutputFile2 { get; set; }
public string UnityVersionOutputFile { get; set; }
public string AssemblyManifestTemplateFile { get; set; }
public string AssemblyManifestOutputFile { get; set; }
public string UnityVersion { get; set; }
@@ -45,7 +49,7 @@ namespace HybridCLR.Editor.Il2CppDef
private void GenerateIl2CppConfig()
{
var frr = new FileRegionReplace(File.ReadAllText(_options.OutputFile));
var frr = new FileRegionReplace(File.ReadAllText(_options.UnityVersionTemplateFile));
List<string> lines = new List<string>();
@@ -93,13 +97,13 @@ namespace HybridCLR.Editor.Il2CppDef
frr.Replace("UNITY_VERSION", string.Join("\n", lines));
frr.Commit(_options.OutputFile);
Debug.Log($"[HybridCLR.Editor.Il2CppDef.Generator] output:{_options.OutputFile}");
frr.Commit(_options.UnityVersionOutputFile);
Debug.Log($"[HybridCLR.Editor.Il2CppDef.Generator] output:{_options.UnityVersionOutputFile}");
}
private void GeneratePlaceHolderAssemblies()
{
var frr = new FileRegionReplace(File.ReadAllText(_options.OutputFile2));
var frr = new FileRegionReplace(File.ReadAllText(_options.AssemblyManifestTemplateFile));
List<string> lines = new List<string>();
@@ -110,8 +114,8 @@ namespace HybridCLR.Editor.Il2CppDef
frr.Replace("PLACE_HOLDER", string.Join("\n", lines));
frr.Commit(_options.OutputFile2);
Debug.Log($"[HybridCLR.Editor.Il2CppDef.Generator] output:{_options.OutputFile2}");
frr.Commit(_options.AssemblyManifestOutputFile);
Debug.Log($"[HybridCLR.Editor.Il2CppDef.Generator] output:{_options.AssemblyManifestOutputFile}");
}
}
}
+35 -4
View File
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
@@ -21,12 +22,43 @@ namespace HybridCLR.Editor.Link
_resolver = resolver;
}
public HashSet<TypeRef> CollectRefs(List<string> rootAssemblies)
public HashSet<ITypeDefOrRef> CollectRefs(List<string> rootAssemblies, bool includeUnityEngineCoreTypes)
{
var typeRefs = new HashSet<ITypeDefOrRef>(TypeEqualityComparer.Instance);
CollectHotUpdateRefs(rootAssemblies, typeRefs);
if (includeUnityEngineCoreTypes)
{
CollectUnityEngineCoreTypes(typeRefs);
}
return typeRefs;
}
private void CollectUnityEngineCoreTypes(HashSet<ITypeDefOrRef> preservedTypes)
{
Debug.Log("CollectUnityEngineCoreTypes");
string unityEngineDllPath = $"{EditorApplication.applicationContentsPath}/Managed/UnityEngine";
var assCollector = new AssemblyCache(_resolver);
foreach (string unityEngineDll in Directory.GetFiles(unityEngineDllPath, "UnityEngine.*.dll", SearchOption.AllDirectories))
{
ModuleDefMD mod = assCollector.LoadModuleFromFileWithoutCache(unityEngineDll);
foreach (TypeDef type in mod.GetTypes())
{
if (type.Methods.Any(m => m.IsInternalCall || m.IsPinvokeImpl))
{
preservedTypes.Add(type);
}
}
}
}
public void CollectHotUpdateRefs(List<string> rootAssemblies, HashSet<ITypeDefOrRef> preservedTypes)
{
var assCollector = new AssemblyCache(_resolver);
var rootAssemblyNames = new HashSet<string>(rootAssemblies);
var typeRefs = new HashSet<TypeRef>(TypeEqualityComparer.Instance);
foreach (var rootAss in rootAssemblies)
{
var dnAss = assCollector.LoadModule(rootAss, false);
@@ -39,11 +71,10 @@ namespace HybridCLR.Editor.Link
}
if (!rootAssemblyNames.Contains(type.DefinitionAssembly.Name.ToString()))
{
typeRefs.Add(type);
preservedTypes.Add(type);
}
}
}
return typeRefs;
}
}
}
+1 -1
View File
@@ -11,7 +11,7 @@ namespace HybridCLR.Editor.Link
{
internal class LinkXmlWriter
{
public void Write(string outputLinkXmlFile, HashSet<TypeRef> refTypes)
public void Write(string outputLinkXmlFile, HashSet<ITypeDefOrRef> refTypes)
{
string parentDir = Directory.GetParent(outputLinkXmlFile).FullName;
Directory.CreateDirectory(parentDir);
+7
View File
@@ -71,6 +71,13 @@ namespace HybridCLR.Editor.Meta
return mod;
}
public ModuleDefMD LoadModuleFromFileWithoutCache(string dllPath)
{
ModuleDefMD mod = ModuleDefMD.Load(File.ReadAllBytes(dllPath), _modCtx);
mod.EnableTypeDefFindCache = true;
return mod;
}
private void LoadNetStandard()
{
string netstandardDllPath = _assemblyPathResolver.ResolveAssembly("netstandard", false);
+70
View File
@@ -0,0 +1,70 @@
using dnlib.DotNet;
using HybridCLR.Editor.Meta;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
namespace HybridCLR.Editor.MethodBridge
{
public class RawCalliMethodSignatureInfo
{
public MethodSig MethodSig { get; set; }
}
public class CalliAnalyzer
{
private readonly List<ModuleDefMD> _rootModules = new List<ModuleDefMD>();
private readonly List<RawCalliMethodSignatureInfo> _calliMethodSignatures = new List<RawCalliMethodSignatureInfo>();
public List<RawCalliMethodSignatureInfo> CalliMethodSignatures => _calliMethodSignatures;
public CalliAnalyzer(AssemblyCache cache, List<string> assemblyNames)
{
foreach (var assemblyName in assemblyNames)
{
_rootModules.Add(cache.LoadModule(assemblyName));
}
}
private void CollectCalli()
{
foreach (var mod in _rootModules)
{
Debug.Log($"ass:{mod.FullName} methodcount:{mod.Metadata.TablesStream.MethodTable.Rows}");
for (uint rid = 1, n = mod.Metadata.TablesStream.MethodTable.Rows; rid <= n; rid++)
{
var method = mod.ResolveMethod(rid);
//Debug.Log($"method:{method}");
if (!method.HasBody)
{
continue;
}
foreach (var il in method.Body.Instructions)
{
if (il.OpCode.Code == dnlib.DotNet.Emit.Code.Calli)
{
MethodSig methodSig = (MethodSig)il.Operand;
_calliMethodSignatures.Add(new RawCalliMethodSignatureInfo()
{
MethodSig = methodSig,
});
Debug.Log($"method:{method} calli method signature:{methodSig}");
}
}
}
}
}
public void Run()
{
CollectCalli();
}
}
}
+11
View File
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 6ce33c8e48da5a649b261ba3a60fd3b9
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
+143 -15
View File
@@ -15,7 +15,6 @@ using UnityEditor;
using UnityEngine;
using TypeInfo = HybridCLR.Editor.ABI.TypeInfo;
using CallingConvention = System.Runtime.InteropServices.CallingConvention;
using System.Security.Cryptography;
using TypeAttributes = dnlib.DotNet.TypeAttributes;
namespace HybridCLR.Editor.MethodBridge
@@ -32,13 +31,37 @@ namespace HybridCLR.Editor.MethodBridge
public List<RawReversePInvokeMethodInfo> ReversePInvokeMethods { get; set; }
public IReadOnlyCollection<RawCalliMethodSignatureInfo> CalliMethodSignatures { get; set; }
public bool Development { get; set; }
}
private class ABIReversePInvokeMethodInfo
{
public MethodDesc Method { get; set; }
public CallingConvention Callvention { get; set; }
public int Count { get; set; }
public string Signature { get; set; }
}
private class CalliMethodInfo
{
public MethodDesc Method { get; set; }
public CallingConvention Callvention { get; set; }
public string Signature { get; set; }
}
private readonly List<GenericMethod> _genericMethods;
private readonly List<RawReversePInvokeMethodInfo> _originalReversePInvokeMethods;
private readonly List<RawCalliMethodSignatureInfo> _originalCalliMethodSignatures;
private readonly string _templateCode;
private readonly string _outputFile;
@@ -55,13 +78,16 @@ namespace HybridCLR.Editor.MethodBridge
private List<ABIReversePInvokeMethodInfo> _reversePInvokeMethods;
private List<CalliMethodInfo> _callidMethods;
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();
_originalReversePInvokeMethods = options.ReversePInvokeMethods;
_originalCalliMethodSignatures = options.CalliMethodSignatures.ToList();
_templateCode = options.TemplateCode;
_outputFile = options.OutputFile;
_typeCreator = new TypeCreator();
@@ -114,6 +140,30 @@ namespace HybridCLR.Editor.MethodBridge
return mbs;
}
private MethodDesc CreateMethodDesc(TypeSig returnType, List<TypeSig> parameters)
{
var paramInfos = new List<ParamInfo>();
if (returnType.ContainsGenericParameter)
{
throw new Exception($"[PreservedMethod] method has generic parameters");
}
foreach (var paramInfo in parameters)
{
if (paramInfo.ContainsGenericParameter)
{
throw new Exception($"[PreservedMethod] method has generic parameters");
}
paramInfos.Add(new ParamInfo() { Type = GetSharedTypeInfo(paramInfo) });
}
var mbs = new MethodDesc()
{
MethodDef = null,
ReturnInfo = new ReturnInfo() { Type = returnType != null ? GetSharedTypeInfo(returnType) : TypeInfo.s_void },
ParamInfos = paramInfos,
};
return mbs;
}
private void AddManaged2NativeMethod(MethodDesc method)
{
method.Init();
@@ -422,11 +472,16 @@ namespace HybridCLR.Editor.MethodBridge
private static string MakeSignature(MethodDesc desc, CallingConvention CallingConventionention)
private static string MakeReversePInvokeSignature(MethodDesc desc, CallingConvention CallingConventionention)
{
string convStr = ((char)('A' + (int)CallingConventionention - 1)).ToString();
return $"{convStr}{desc.Sig}";
}
private static string MakeCalliSignature(MethodDesc desc, CallingConvention CallingConventionention)
{
string convStr = ((char)('A' + Math.Max((int)CallingConventionention - 1, 0))).ToString();
return $"{convStr}{desc.Sig}";
}
private static CallingConvention GetCallingConvention(MethodDef method)
{
@@ -479,7 +534,7 @@ namespace HybridCLR.Editor.MethodBridge
sharedMethod = ToIsomorphicMethod(sharedMethod);
CallingConvention callingConv = GetCallingConvention(method.Method);
string signature = MakeSignature(sharedMethod, callingConv);
string signature = MakeReversePInvokeSignature(sharedMethod, callingConv);
if (!methodsBySig.TryGetValue(signature, out var arm))
{
@@ -500,12 +555,46 @@ namespace HybridCLR.Editor.MethodBridge
return newMethods;
}
private List<CalliMethodInfo> BuildCalliMethods(List<RawCalliMethodSignatureInfo> rawMethods)
{
var methodsBySig = new Dictionary<string, CalliMethodInfo>();
foreach (var method in rawMethods)
{
var sharedMethod = new MethodDesc
{
MethodDef = null,
ReturnInfo = new ReturnInfo { Type = _typeCreator.CreateTypeInfo(method.MethodSig.RetType) },
ParamInfos = method.MethodSig.Params.Select(p => new ParamInfo { Type = _typeCreator.CreateTypeInfo(p) }).ToList(),
};
sharedMethod.Init();
sharedMethod = ToIsomorphicMethod(sharedMethod);
CallingConvention callingConv = (CallingConvention)((int)method.MethodSig.CallingConvention + 1);
string signature = MakeCalliSignature(sharedMethod, callingConv);
if (!methodsBySig.TryGetValue(signature, out var arm))
{
arm = new CalliMethodInfo()
{
Method = sharedMethod,
Signature = signature,
Callvention = callingConv,
};
methodsBySig.Add(signature, arm);
}
}
var newMethods = methodsBySig.Values.ToList();
newMethods.Sort((a, b) => string.CompareOrdinal(a.Signature, b.Signature));
return newMethods;
}
private void BuildOptimizedMethods()
{
_managed2NativeMethodList = ToUniqueOrderedList(_managed2NativeMethodList0);
_native2ManagedMethodList = ToUniqueOrderedList(_native2ManagedMethodList0);
_adjustThunkMethodList = ToUniqueOrderedList(_adjustThunkMethodList0);
_reversePInvokeMethods = BuildABIMethods(_originalReversePInvokeMethods);
_callidMethods = BuildCalliMethods(_originalCalliMethodSignatures);
}
private void OptimizationTypesAndMethods()
@@ -562,6 +651,13 @@ namespace HybridCLR.Editor.MethodBridge
GenerateReversePInvokeWrappers(_reversePInvokeMethods, lines);
foreach (var method in _callidMethods)
{
GenerateManaged2NativeFunctionPointerMethod(method, lines);
}
GenerateManaged2NativeFunctionPointerMethodStub(_callidMethods, lines);
frr.Replace("CODE", string.Join("\n", lines));
Directory.CreateDirectory(Path.GetDirectoryName(_outputFile));
@@ -778,9 +874,9 @@ const ReversePInvokeMethodData hybridclr::interpreter::g_reversePInvokeMethodStu
}
}
public const string SigOfObj = "u";
private const string SigOfObj = "u";
public static string ToFullName(TypeSig type)
private static string ToFullName(TypeSig type)
{
type = type.RemovePinnedAndModifiers();
switch (type.ElementType)
@@ -875,7 +971,7 @@ const ReversePInvokeMethodData hybridclr::interpreter::g_reversePInvokeMethodStu
return $"{Path.GetFileNameWithoutExtension(typeDef.Module.Name)}:{typeDef.FullName}";
}
public void GenerateStructureSignatureStub(List<TypeInfo> types, List<string> lines)
private void GenerateStructureSignatureStub(List<TypeInfo> types, List<string> lines)
{
lines.Add("const FullName2Signature hybridclr::interpreter::g_fullName2SignatureStub[] = {");
foreach (var type in types)
@@ -887,7 +983,7 @@ const ReversePInvokeMethodData hybridclr::interpreter::g_reversePInvokeMethodStu
lines.Add("};");
}
public void GenerateManaged2NativeStub(List<MethodDesc> methods, List<string> lines)
private void GenerateManaged2NativeStub(List<MethodDesc> methods, List<string> lines)
{
lines.Add($@"
const Managed2NativeMethodInfo hybridclr::interpreter::g_managed2nativeStub[] =
@@ -903,7 +999,7 @@ const Managed2NativeMethodInfo hybridclr::interpreter::g_managed2nativeStub[] =
lines.Add("};");
}
public void GenerateNative2ManagedStub(List<MethodDesc> methods, List<string> lines)
private void GenerateNative2ManagedStub(List<MethodDesc> methods, List<string> lines)
{
lines.Add($@"
const Native2ManagedMethodInfo hybridclr::interpreter::g_native2managedStub[] =
@@ -919,7 +1015,7 @@ const Native2ManagedMethodInfo hybridclr::interpreter::g_native2managedStub[] =
lines.Add("};");
}
public void GenerateAdjustThunkStub(List<MethodDesc> methods, List<string> lines)
private void GenerateAdjustThunkStub(List<MethodDesc> methods, List<string> lines)
{
lines.Add($@"
const NativeAdjustThunkMethodInfo hybridclr::interpreter::g_adjustThunkStub[] =
@@ -945,7 +1041,7 @@ const NativeAdjustThunkMethodInfo hybridclr::interpreter::g_adjustThunkStub[] =
return type.NeedExpandValue() ? $"(uint64_t)({varName})" : $"N2MAsUint64ValueOrAddress<{type.GetTypeName()}>({varName})";
}
public void GenerateManaged2NativeMethod(MethodDesc method, List<string> lines)
private 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" }));
@@ -959,7 +1055,7 @@ static void __M2N_{method.CreateCallSigName()}(const MethodInfo* method, uint16_
");
}
public string GenerateArgumentSizeAndOffset(List<ParamInfo> paramInfos)
private string GenerateArgumentSizeAndOffset(List<ParamInfo> paramInfos)
{
StringBuilder s = new StringBuilder();
int index = 0;
@@ -973,7 +1069,7 @@ static void __M2N_{method.CreateCallSigName()}(const MethodInfo* method, uint16_
return s.ToString();
}
public string GenerateCopyArgumentToInterpreterStack(List<ParamInfo> paramInfos)
private string GenerateCopyArgumentToInterpreterStack(List<ParamInfo> paramInfos)
{
StringBuilder s = new StringBuilder();
int index = 0;
@@ -1014,14 +1110,46 @@ static {method.ReturnInfo.Type.GetTypeName()} __N2M_{(adjustorThunk ? "AdjustorT
");
}
public void GenerateNative2ManagedMethod(MethodDesc method, List<string> lines)
private void GenerateNative2ManagedMethod(MethodDesc method, List<string> lines)
{
GenerateNative2ManagedMethod0(method, false, lines);
}
public void GenerateAdjustThunkMethod(MethodDesc method, List<string> lines)
private void GenerateAdjustThunkMethod(MethodDesc method, List<string> lines)
{
GenerateNative2ManagedMethod0(method, true, lines);
}
private void GenerateManaged2NativeFunctionPointerMethod(CalliMethodInfo methodInfo, List<string> lines)
{
MethodDesc method = methodInfo.Method;
string paramListStr = string.Join(", ", method.ParamInfos.Select(p => $"{p.Type.GetTypeName()} __arg{p.Index}"));
string paramNameListStr = string.Join(", ", method.ParamInfos.Select(p => GetManaged2NativePassParam(p.Type, $"localVarBase+argVarIndexs[{p.Index}]")));
string il2cppCallConventionName = GetIl2cppCallConventionName(methodInfo.Callvention);
lines.Add($@"
static void __M2NF_{methodInfo.Signature}(const void* methodPointer, uint16_t* argVarIndexs, StackObject* localVarBase, void* ret)
{{
typedef {method.ReturnInfo.Type.GetTypeName()} ({il2cppCallConventionName} *NativeMethod)({paramListStr});
{(!method.ReturnInfo.IsVoid ? $"*({method.ReturnInfo.Type.GetTypeName()}*)ret = " : "")}((NativeMethod)(methodPointer))({paramNameListStr});
}}
");
}
private void GenerateManaged2NativeFunctionPointerMethodStub(List<CalliMethodInfo> calliMethodSignatures, List<string> lines)
{
lines.Add(@"
const Managed2NativeFunctionPointerCallData hybridclr::interpreter::g_managed2NativeFunctionPointerCallStub[]
{
");
foreach (var method in calliMethodSignatures)
{
lines.Add($"\t{{\"{method.Signature}\", __M2NF_{method.Signature}}},");
}
lines.Add(@"
{nullptr, nullptr},
};
");
}
}
}
-11
View File
@@ -18,17 +18,6 @@ namespace HybridCLR.Editor.ReversePInvokeWrap
public CustomAttribute GenerationAttribute { get; set; }
}
public class ABIReversePInvokeMethodInfo
{
public MethodDesc Method { get; set; }
public CallingConvention Callvention { get; set; }
public int Count { get; set; }
public string Signature { get; set; }
}
public class Analyzer
{
@@ -21,6 +21,7 @@ namespace HybridCLR.Editor.Settings
private SerializedProperty _externalHotUpdateAssembliyDirs;
private SerializedProperty _strippedAOTDllOutputRootDir;
private SerializedProperty _patchAOTAssemblies;
private SerializedProperty _dontPreserveUnityEngineCoreTypesInLinkXml;
private SerializedProperty _outputLinkFile;
private SerializedProperty _outputAOTGenericReferenceFile;
private SerializedProperty _maxGenericReferenceIteration;
@@ -51,6 +52,7 @@ namespace HybridCLR.Editor.Settings
_externalHotUpdateAssembliyDirs = _serializedObject.FindProperty("externalHotUpdateAssembliyDirs");
_strippedAOTDllOutputRootDir = _serializedObject.FindProperty("strippedAOTDllOutputRootDir");
_patchAOTAssemblies = _serializedObject.FindProperty("patchAOTAssemblies");
_dontPreserveUnityEngineCoreTypesInLinkXml = _serializedObject.FindProperty("dontPreserveUnityEngineCoreTypesInLinkXml");
_outputLinkFile = _serializedObject.FindProperty("outputLinkFile");
_outputAOTGenericReferenceFile = _serializedObject.FindProperty("outputAOTGenericReferenceFile");
_maxGenericReferenceIteration = _serializedObject.FindProperty("maxGenericReferenceIteration");
@@ -140,6 +142,7 @@ namespace HybridCLR.Editor.Settings
EditorGUILayout.PropertyField(_externalHotUpdateAssembliyDirs);
EditorGUILayout.PropertyField(_strippedAOTDllOutputRootDir);
EditorGUILayout.PropertyField(_patchAOTAssemblies);
EditorGUILayout.PropertyField(_dontPreserveUnityEngineCoreTypesInLinkXml);
EditorGUILayout.PropertyField(_outputLinkFile);
EditorGUILayout.PropertyField(_outputAOTGenericReferenceFile);
EditorGUILayout.PropertyField(_maxGenericReferenceIteration);
+5 -2
View File
@@ -39,6 +39,9 @@ namespace HybridCLR.Editor.Settings
[Tooltip("supplementary metadata assembly names(without .dll suffix)")]
public string[] patchAOTAssemblies;
[Tooltip("don't preserve UnityEngine core types in link.xml")]
public bool dontPreserveUnityEngineCoreTypesInLinkXml;
[Tooltip("output file of automatic generated link.xml by scanning hot update assemblies")]
public string outputLinkFile = "HybridCLRGenerate/link.xml";
@@ -52,9 +55,9 @@ namespace HybridCLR.Editor.Settings
public int maxMethodBridgeGenericIteration = 10;
[Tooltip("enable profiler support when publishing in release mode")]
public bool enableProfilerInReleaseBuild = false;
public bool enableProfilerInReleaseBuild;
[Tooltip("enable StraceTrace support when publishing to the WebGL platform in release mode")]
public bool enableStraceTraceInWebGLReleaseBuild = false;
public bool enableStraceTraceInWebGLReleaseBuild;
}
}
+36
View File
@@ -1,5 +1,41 @@
# ReleaseLog
## 7.4.0
Release Date: 2025-01-17.
### Runtime
- [new] calli supports call both native function pointer and managed method
### Editor
- [new] add Managed2NativeFunctionPointer MethodBridge functions
- [new] support preserve UnityEngine core types when GenerateLinkXml
- [fix] fixed the bug in AOTAssemblyMetadataStripper::Strip where ModuleWriterOptions MetadataFlags.PreserveRids was not used.
- [fix] fixed the bug where StripAOTDllCommand did not set BuildPlayerOptions.subtarget in Unity 2021+ versions, causing failure when publishing dedicated buildTarget.
- [change] add UnityVersion.h.tpl and AssemblyManifest.cpp.tpl, Il2CppDefGenerator doesn't generates and override code file from same one
- [change] add MethodBridge.cpp.tpl. MethodBridgeGeneratorCommand doesn't generate and override from same file
## 7.3.0
Release Date: 2024-12-31.
### Runtime
- [fix] fix bug that Image::ReadRuntimeHandleFromMemberRef didn't inflate parent type when read field of GenericType
- [fix] fix an issue occurred in InterpreterImage::GenerateCustomAttributesCacheInternal where HYBRIDCLR_METADATA_MALLOC was incorrectly used to allocate the cache. When occasional contention occurs, releasing memory using HYBRIDCLR_FREE causes a crash.
- [fix] fixed a potential deadlock issue in Unity 2019 and 2020 versions within InterpreterImage::GenerateCustomAttributesCacheInternal, where il2cpp::vm::g_MetadataLock was held before running ConstructCustomAttribute.
- [fix] fixed a bug in Unity 2019 and 2020 within InterpreterImage::GenerateCustomAttributesCacheInternal, where cache memory leaks occurred under multithreading contention.
- [fix] fix the bug that InterpreterImage::ConstructCustomAttribute doesn't set write barrier for field
- [fix] fix the bug that `InterpreterImage::InitTypeDefs_2` runs after `InitClassLayouts`, causing the `packingSize` field to be incorrectly initialized.
- [fix] fix the bug in ClassFieldLayoutCalculator::LayoutFields where the alignment calculation incorrectly considers naturalAlignment, resulting in field offsets that are inconsistent with the actual field offsets in AOT. This bug originates from IL2CPP itself and only occurs in Unity 2021 and earlier versions.
### Editor
- [fix] fix the issue in Unity 6000 where the modification of the trimmed AOT DLL output directory for the visionOS build target caused CopyStrippedAOTAssemblies::GetStripAssembliesDir2021 to fail in copying AOT DLLs.
- [fix] fix the bug where MissingMetadataChecker can't detect references to newly added AOT assemblies.
## 7.2.0
Release Date: 2024-12-9.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "com.code-philosophy.hybridclr",
"version": "7.2.0",
"version": "7.4.0",
"displayName": "HybridCLR",
"description": "HybridCLR is a fully featured, zero-cost, high-performance, low-memory solution for Unity's all-platform native c# hotupdate.",
"category": "Runtime",