mirror of
https://github.com/focus-creative-games/hybridclr_unity.git
synced 2026-11-20 07:22:39 +08:00
Compare commits
186 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 86e6407a35 | |||
| 44057b0107 | |||
| d17a727fac | |||
| d91835ac31 | |||
| 6ecc0a9728 | |||
| fd32708e7f | |||
| a0e0b502c6 | |||
| a93ca3dc27 | |||
| b700ae679c | |||
| 6e635f78bf | |||
| ca7f87b6a7 | |||
| e4def761d6 | |||
| f0be76c0ce | |||
| 4feac30cb2 | |||
| fc3d9dcd7d | |||
| 6a320c556f | |||
| 03083ad8f9 | |||
| c6d53bff82 | |||
| 77d4aec034 | |||
| 4df417e56a | |||
| 213d44bd12 | |||
| c138a58c4d | |||
| fcef6dfe8e | |||
| 478caea644 | |||
| 2534dea381 | |||
| 391cd04cdf | |||
| 01754c8fb4 | |||
| 1934d90f27 | |||
| 814572e1a1 | |||
| d505624c78 | |||
| e36bbb9022 | |||
| 0642726469 | |||
| d86572db37 | |||
| b5944ea834 | |||
| 73654e76d2 | |||
| 1537690bb5 | |||
| 7f158f814a | |||
| ee7af5c592 | |||
| ab41cd0144 | |||
| 59a3c3974a | |||
| c9ff293dfe | |||
| 56486b8a76 | |||
| 8e27e8d41b | |||
| fca130bbfa | |||
| c21dbcc60a | |||
| 7f2fa52f37 | |||
| da46e71534 | |||
| 804418fddb | |||
| 7a0032934b | |||
| b301b44cd3 | |||
| ddc3332958 | |||
| 52f25bdb2a | |||
| 31be818bb6 | |||
| 213a11ff25 | |||
| 585be97be9 | |||
| 361873803f | |||
| 46f308ed5e | |||
| 34406b1c13 | |||
| e5b52922f7 | |||
| e44fa663db | |||
| 903cf9faa2 | |||
| 3fe41a8cba | |||
| 603b0ccb24 | |||
| 9429a4d24d | |||
| ea592ba20c | |||
| 8d1280a1bd | |||
| 528240b52b | |||
| 4768c039d2 | |||
| 10dc749d7a | |||
| 0c5ef00c12 | |||
| 1553582ec1 | |||
| 756b906a21 | |||
| 355e24fbe8 | |||
| 9e4946aa45 | |||
| 8e571d594d | |||
| b8dd2be1e4 | |||
| de7b60695a | |||
| a11ebecf93 | |||
| 019412fa81 | |||
| 84bf6d59db | |||
| 82163d2e50 | |||
| 208372e6af | |||
| dd8d812641 | |||
| c19b34542e | |||
| e30306d7e1 | |||
| 20f34c9b14 | |||
| 45749ffb5c | |||
| b176d63d93 | |||
| 0c99afd58e | |||
| 2458c9a9ba | |||
| 4d0fef095b | |||
| 642d2cd644 | |||
| e54ce36b0e | |||
| ac8b649d50 | |||
| 9ca9cd5aa7 | |||
| 37dafd7b3c | |||
| f58d12c2cb | |||
| d5eaa350c5 | |||
| 1f0053a3c9 | |||
| 15dccc7427 | |||
| 7d287a2293 | |||
| f19ba3eb30 | |||
| 4e172129d8 | |||
| 2414e77fef | |||
| 77517a9814 | |||
| 162f21f6a5 | |||
| bd7c3293bc | |||
| e25be945c7 | |||
| 925921c27c | |||
| 64a6d26fa3 | |||
| c24617d864 | |||
| 59bc259cc8 | |||
| c413cd6143 | |||
| c614cdcf4e | |||
| 08f493ab3e | |||
| 3705ca6e1f | |||
| 34df279943 | |||
| b85ed1aa92 | |||
| faf4a328af | |||
| 53f4f33bf0 | |||
| 48c91f497b | |||
| 9afbe3bd84 | |||
| 2d5f71f6b7 | |||
| 5747458bf2 | |||
| 0b455eb882 | |||
| e086228d90 | |||
| 909e96ca7c | |||
| 75b24345f6 | |||
| 88e20505f8 | |||
| b4b486944c | |||
| 360ba38805 | |||
| e5a6952777 | |||
| 9330cf682c | |||
| 16a7d5d529 | |||
| 303c6c7b35 | |||
| e4cf9e9086 | |||
| b977a85b23 | |||
| 0fcb51a369 | |||
| d61511924d | |||
| aca7dd0a67 | |||
| fc685a99ca | |||
| d431aeb019 | |||
| 63d0aaa6e6 | |||
| d45974c6b4 | |||
| 3de931a3af | |||
| b96d6fc10d | |||
| ef1b78caae | |||
| 47622bf49c | |||
| 846d7103a3 | |||
| 170f13082e | |||
| 60016d7481 | |||
| 97dae7fed2 | |||
| f935127cd3 | |||
| ec5f2ef05e | |||
| 6d0ceaa4f5 | |||
| 95922aec1e | |||
| 3259c11828 | |||
| 74bab1d935 | |||
| fd81edb495 | |||
| 12bafb897f | |||
| a6befb1312 | |||
| a36e3fe72d | |||
| d9776d1793 | |||
| 2697eb5a90 | |||
| 4879bb7f44 | |||
| 24f85780a2 | |||
| 6c679cc3ab | |||
| 20a06f1ec5 | |||
| 5446bd937c | |||
| ae88dd0eec | |||
| a5c006d67c | |||
| 67c487f521 | |||
| 6ffb977ef3 | |||
| f59ba2623a | |||
| 4b57138935 | |||
| 276cd0a4a8 | |||
| 22a9793b9d | |||
| 1b7947b196 | |||
| 188fdc9430 | |||
| ff0f225423 | |||
| 36ca398543 | |||
| f30e2f5b33 | |||
| a531a213c2 | |||
| 2b42376505 | |||
| ef103d8351 | |||
| db87b92f78 |
@@ -1,19 +1,24 @@
|
||||
{
|
||||
"versions": [
|
||||
{
|
||||
"unity_version":"2020",
|
||||
"hybridclr" : { "branch":"v4.0.10"},
|
||||
"il2cpp_plus": { "branch":"v2020-4.0.8"}
|
||||
"unity_version":"2022.3.x",
|
||||
"hybridclr" : { "tag":"v9.0.0"},
|
||||
"il2cpp_plus": { "tag":"v2022.3.x-9.0.0"}
|
||||
},
|
||||
{
|
||||
"unity_version":"2021",
|
||||
"hybridclr" : { "branch":"v4.0.10"},
|
||||
"il2cpp_plus": { "branch":"v2021-4.0.8"}
|
||||
"unity_version":"2022.3.x-tuanjie",
|
||||
"hybridclr" : { "tag":"v9.0.0"},
|
||||
"il2cpp_plus": { "tag":"v2022.3.x-tuanjie-9.0.0"}
|
||||
},
|
||||
{
|
||||
"unity_version":"2022",
|
||||
"hybridclr" : { "branch":"v4.0.10"},
|
||||
"il2cpp_plus": { "branch":"v2022-4.0.8"}
|
||||
"unity_version":"6000.0.x",
|
||||
"hybridclr" : { "tag":"v9.0.0"},
|
||||
"il2cpp_plus": { "tag":"v6000.0.x-9.0.0"}
|
||||
},
|
||||
{
|
||||
"unity_version":"6000.3.x",
|
||||
"hybridclr" : { "tag":"v6000.3.x-9.0.0"},
|
||||
"il2cpp_plus": { "tag":"v6000.3.x-9.0.0"}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,9 +1,5 @@
|
||||
using DotNetDetour;
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
using System.Linq;
|
||||
|
||||
namespace MonoHook
|
||||
{
|
||||
@@ -11,16 +7,16 @@ namespace MonoHook
|
||||
{
|
||||
public bool isValid { get; protected set; }
|
||||
|
||||
protected void* _pTarget, _pReplace, _pProxy;
|
||||
protected int _jmpCodeSize;
|
||||
protected byte[] _targetHeaderBackup;
|
||||
protected void* _pTarget, _pReplace, _pProxy;
|
||||
protected int _jmpCodeSize;
|
||||
protected byte[] _targetHeaderBackup;
|
||||
|
||||
public CodePatcher(IntPtr target, IntPtr replace, IntPtr proxy, int jmpCodeSize)
|
||||
{
|
||||
_pTarget = target.ToPointer();
|
||||
_pReplace = replace.ToPointer();
|
||||
_pProxy = proxy.ToPointer();
|
||||
_jmpCodeSize = jmpCodeSize;
|
||||
_pTarget = target.ToPointer();
|
||||
_pReplace = replace.ToPointer();
|
||||
_pProxy = proxy.ToPointer();
|
||||
_jmpCodeSize = jmpCodeSize;
|
||||
}
|
||||
|
||||
public void ApplyPatch()
|
||||
@@ -47,7 +43,7 @@ namespace MonoHook
|
||||
if (_targetHeaderBackup != null)
|
||||
return;
|
||||
|
||||
uint requireSize = LDasm.SizeofMinNumByte(_pTarget, _jmpCodeSize);
|
||||
uint requireSize = LDasm.SizeofMinNumByte(_pTarget, _jmpCodeSize);
|
||||
_targetHeaderBackup = new byte[requireSize];
|
||||
|
||||
fixed (void* ptr = _targetHeaderBackup)
|
||||
@@ -76,8 +72,8 @@ namespace MonoHook
|
||||
HookUtils.MemCpy_Jit(_pProxy, _targetHeaderBackup);
|
||||
|
||||
// jmp to target's new position
|
||||
long jmpFrom = (long)_pProxy + _targetHeaderBackup.Length;
|
||||
long jmpTo = (long)_pTarget + _targetHeaderBackup.Length;
|
||||
long jmpFrom = (long)_pProxy + _targetHeaderBackup.Length;
|
||||
long jmpTo = (long)_pTarget + _targetHeaderBackup.Length;
|
||||
|
||||
byte[] buff = GenJmpCode((void*)jmpFrom, (void*)jmpTo);
|
||||
HookUtils.MemCpy_Jit((void*)jmpFrom, buff);
|
||||
@@ -121,7 +117,7 @@ namespace MonoHook
|
||||
byte[] ret = new byte[s_jmpCode.Length];
|
||||
int val = (int)jmpTo - (int)jmpFrom - 5;
|
||||
|
||||
fixed(void * p = &ret[0])
|
||||
fixed (void* p = &ret[0])
|
||||
{
|
||||
byte* ptr = (byte*)p;
|
||||
*ptr = 0xE9;
|
||||
|
||||
@@ -1,11 +1,7 @@
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Reflection;
|
||||
using UnityEngine;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
#if UNITY_EDITOR
|
||||
using UnityEditor;
|
||||
#endif
|
||||
|
||||
namespace MonoHook
|
||||
@@ -60,7 +56,7 @@ namespace MonoHook
|
||||
var list = _hooks.Values.ToList();
|
||||
foreach (var hook in list)
|
||||
{
|
||||
if(hook.tag == tag)
|
||||
if (hook.tag == tag)
|
||||
hook.Uninstall();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ namespace MonoHook
|
||||
|
||||
static DelegateFlushICache flush_icache;
|
||||
private static readonly long _Pagesize;
|
||||
|
||||
|
||||
static HookUtils()
|
||||
{
|
||||
PropertyInfo p_SystemPageSize = typeof(Environment).GetProperty("SystemPageSize");
|
||||
@@ -50,7 +50,7 @@ namespace MonoHook
|
||||
if (ptr == IntPtr.Zero)
|
||||
return;
|
||||
|
||||
#if UNITY_STANDALONE_WIN || UNITY_EDITOR_WIN
|
||||
#if UNITY_EDITOR_WIN || (!UNITY_EDITOR && UNITY_STANDALONE_WIN)
|
||||
uint oldProtect;
|
||||
bool ret = VirtualProtect(ptr, (uint)size, Protection.PAGE_EXECUTE_READWRITE, out oldProtect);
|
||||
UnityEngine.Debug.Assert(ret);
|
||||
@@ -73,9 +73,9 @@ namespace MonoHook
|
||||
|
||||
public static KeyValuePair<long, long> GetPageAlignedAddr(long code, int size)
|
||||
{
|
||||
long pagesize = _Pagesize;
|
||||
long startPage = (code) & ~(pagesize - 1);
|
||||
long endPage = (code + size + pagesize - 1) & ~(pagesize - 1);
|
||||
long pagesize = _Pagesize;
|
||||
long startPage = (code) & ~(pagesize - 1);
|
||||
long endPage = (code + size + pagesize - 1) & ~(pagesize - 1);
|
||||
return new KeyValuePair<long, long>(startPage, endPage);
|
||||
}
|
||||
|
||||
@@ -110,14 +110,14 @@ namespace MonoHook
|
||||
count++;
|
||||
}
|
||||
}
|
||||
END:;
|
||||
END:;
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
static void SetupFlushICacheFunc()
|
||||
{
|
||||
string processorType = SystemInfo.processorType;
|
||||
if (processorType.Contains("Intel") || processorType.Contains("AMD"))
|
||||
string processorType = SystemInfo.processorType.ToLowerInvariant();
|
||||
if (processorType.Contains("intel") || processorType.Contains("amd"))
|
||||
return;
|
||||
|
||||
if (IntPtr.Size == 4)
|
||||
@@ -223,7 +223,7 @@ namespace MonoHook
|
||||
};
|
||||
|
||||
|
||||
#if UNITY_STANDALONE_WIN || UNITY_EDITOR_WIN
|
||||
#if UNITY_EDITOR_WIN || (!UNITY_EDITOR && UNITY_STANDALONE_WIN)
|
||||
[Flags]
|
||||
public enum Protection
|
||||
{
|
||||
|
||||
@@ -16,7 +16,11 @@ namespace MonoHook
|
||||
|
||||
static HookUtils()
|
||||
{
|
||||
jit_write_protect_supported = pthread_jit_write_protect_supported_np() != 0;
|
||||
try
|
||||
{
|
||||
jit_write_protect_supported = pthread_jit_write_protect_supported_np() != 0;
|
||||
}
|
||||
catch { }
|
||||
|
||||
PropertyInfo p_SystemPageSize = typeof(Environment).GetProperty("SystemPageSize");
|
||||
if (p_SystemPageSize == null)
|
||||
@@ -35,6 +39,16 @@ namespace MonoHook
|
||||
|
||||
public static void MemCpy_Jit(void* pDst, byte[] src)
|
||||
{
|
||||
if (!jit_write_protect_supported)
|
||||
{
|
||||
fixed(void * pSrc = &src[0])
|
||||
{
|
||||
MemCpy(pDst, pSrc, src.Length);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
fixed(void * p = &src[0])
|
||||
{
|
||||
memcpy_jit(new IntPtr(pDst), new IntPtr(p), src.Length);
|
||||
|
||||
@@ -1,57 +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_2021_1_OR_NEWER && UNITY_WEBGL
|
||||
[InitializeOnLoad]
|
||||
public class PatchScriptingAssembliesJsonHook
|
||||
{
|
||||
private static MethodHook _hook;
|
||||
|
||||
static PatchScriptingAssembliesJsonHook()
|
||||
{
|
||||
if (_hook == null)
|
||||
{
|
||||
Type type = typeof(UnityEditor.EditorApplication);
|
||||
MethodInfo miTarget = type.GetMethod("BuildMainWindowTitle", BindingFlags.Static | BindingFlags.NonPublic);
|
||||
|
||||
MethodInfo miReplacement = new Func<string>(BuildMainWindowTitle).Method;
|
||||
MethodInfo miProxy = new Func<string>(BuildMainWindowTitleProxy).Method;
|
||||
|
||||
_hook = new MethodHook(miTarget, miReplacement, miProxy);
|
||||
_hook.Install();
|
||||
}
|
||||
}
|
||||
|
||||
private static string BuildMainWindowTitle()
|
||||
{
|
||||
string tempJsonPath = $"{Application.dataPath}/../Library/PlayerDataCache/WebGL/Data/ScriptingAssemblies.json";
|
||||
if (File.Exists(tempJsonPath))
|
||||
{
|
||||
var patcher = new PatchScriptingAssemblyList();
|
||||
patcher.PathScriptingAssembilesFile(Path.GetDirectoryName(tempJsonPath));
|
||||
}
|
||||
string newTitle = BuildMainWindowTitleProxy();
|
||||
return newTitle;
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.NoOptimization)]
|
||||
private static string BuildMainWindowTitleProxy()
|
||||
{
|
||||
// 为满足MonoHook要求的最小代码长度而特地加入的无用填充代码,
|
||||
UnityEngine.Debug.Log(12345.ToString());
|
||||
return string.Empty;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -631,7 +631,7 @@ namespace DotNetDetour
|
||||
|
||||
code = (void*)((ulong)code + Length);
|
||||
|
||||
} while (Length>0);
|
||||
} while (Length > 0);
|
||||
|
||||
return Result;
|
||||
}
|
||||
@@ -639,7 +639,7 @@ namespace DotNetDetour
|
||||
static bool? s_isArm;
|
||||
public static bool IsARM()
|
||||
{
|
||||
if(s_isArm.HasValue)
|
||||
if (s_isArm.HasValue)
|
||||
return s_isArm.Value;
|
||||
|
||||
var arch = RuntimeInformation.ProcessArchitecture;
|
||||
@@ -661,7 +661,7 @@ namespace DotNetDetour
|
||||
static bool? s_isiOS;
|
||||
public static bool IsiOS()
|
||||
{
|
||||
if(s_isiOS.HasValue)
|
||||
if (s_isiOS.HasValue)
|
||||
return s_isiOS.Value;
|
||||
|
||||
s_isiOS = UnityEngine.SystemInfo.operatingSystem.ToLower().Contains("ios");
|
||||
@@ -692,7 +692,7 @@ namespace DotNetDetour
|
||||
|
||||
public static bool IsThumb(IntPtr code)
|
||||
{
|
||||
return IsArm32() && ((long)code & 0x1) == 0x1;
|
||||
return IsArm32() && ((long)code & 0x1) == 0x1;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -733,14 +733,14 @@ namespace DotNetDetour
|
||||
s = rexw = pr_66 = pr_67 = 0;
|
||||
|
||||
/* dummy check */
|
||||
if ((int)code==0)
|
||||
if ((int)code == 0)
|
||||
return 0;
|
||||
|
||||
/* init output data */
|
||||
//memset(ld, 0, sizeof(ldasm_data));
|
||||
|
||||
/* phase 1: parse prefixies */
|
||||
while ((cflags(*p) & OP_PREFIX)!=0)
|
||||
while ((cflags(*p) & OP_PREFIX) != 0)
|
||||
{
|
||||
if (*p == 0x66)
|
||||
pr_66 = 1;
|
||||
@@ -783,19 +783,20 @@ namespace DotNetDetour
|
||||
op = *p++; s++;
|
||||
ld.opcd_size++;
|
||||
f = cflags_ex(op);
|
||||
if ((f & OP_INVALID)!=0)
|
||||
if ((f & OP_INVALID) != 0)
|
||||
{
|
||||
ld.flags |= F_INVALID;
|
||||
return s;
|
||||
}
|
||||
/* for SSE instructions */
|
||||
if ((f & OP_EXTENDED)!=0)
|
||||
if ((f & OP_EXTENDED) != 0)
|
||||
{
|
||||
op = *p++; s++;
|
||||
ld.opcd_size++;
|
||||
}
|
||||
}
|
||||
else {
|
||||
else
|
||||
{
|
||||
f = cflags(op);
|
||||
/* pr_66 = pr_67 for opcodes A0-A3 */
|
||||
if (op >= 0xA0 && op <= 0xA3)
|
||||
@@ -803,7 +804,7 @@ namespace DotNetDetour
|
||||
}
|
||||
|
||||
/* phase 3: parse ModR/M, SIB and DISP */
|
||||
if ((f & OP_MODRM)!=0)
|
||||
if ((f & OP_MODRM) != 0)
|
||||
{
|
||||
byte mod = (byte)(*p >> 6);
|
||||
byte ro = (byte)((*p & 0x38) >> 3);
|
||||
@@ -819,7 +820,7 @@ namespace DotNetDetour
|
||||
f |= OP_DATA_I16_I32_I64;
|
||||
|
||||
/* is SIB byte exist? */
|
||||
if (mod != 3 && rm == 4 && !(!is64 && pr_67!=0))
|
||||
if (mod != 3 && rm == 4 && !(!is64 && pr_67 != 0))
|
||||
{
|
||||
ld.sib = *p++; s++;
|
||||
ld.flags |= F_SIB;
|
||||
@@ -833,40 +834,41 @@ namespace DotNetDetour
|
||||
|
||||
switch (mod)
|
||||
{
|
||||
case 0:
|
||||
case 0:
|
||||
if (is64)
|
||||
{
|
||||
if (rm == 5)
|
||||
{
|
||||
ld.disp_size = 4;
|
||||
if (is64)
|
||||
{
|
||||
if (rm == 5)
|
||||
{
|
||||
ld.disp_size = 4;
|
||||
if (is64)
|
||||
ld.flags |= F_RELATIVE;
|
||||
}
|
||||
}
|
||||
else if (pr_67!=0)
|
||||
{
|
||||
if (rm == 6)
|
||||
ld.disp_size = 2;
|
||||
}
|
||||
else {
|
||||
if (rm == 5)
|
||||
ld.disp_size = 4;
|
||||
}
|
||||
break;
|
||||
case 1:
|
||||
ld.disp_size = 1;
|
||||
break;
|
||||
case 2:
|
||||
if (is64)
|
||||
ld.disp_size = 4;
|
||||
else if (pr_67!=0)
|
||||
ld.disp_size = 2;
|
||||
else
|
||||
ld.disp_size = 4;
|
||||
break;
|
||||
ld.flags |= F_RELATIVE;
|
||||
}
|
||||
}
|
||||
else if (pr_67 != 0)
|
||||
{
|
||||
if (rm == 6)
|
||||
ld.disp_size = 2;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (rm == 5)
|
||||
ld.disp_size = 4;
|
||||
}
|
||||
break;
|
||||
case 1:
|
||||
ld.disp_size = 1;
|
||||
break;
|
||||
case 2:
|
||||
if (is64)
|
||||
ld.disp_size = 4;
|
||||
else if (pr_67 != 0)
|
||||
ld.disp_size = 2;
|
||||
else
|
||||
ld.disp_size = 4;
|
||||
break;
|
||||
}
|
||||
|
||||
if (ld.disp_size>0)
|
||||
if (ld.disp_size > 0)
|
||||
{
|
||||
ld.disp_offset = (byte)(p - (byte*)code);
|
||||
p += ld.disp_size;
|
||||
@@ -876,20 +878,20 @@ namespace DotNetDetour
|
||||
}
|
||||
|
||||
/* phase 4: parse immediate data */
|
||||
if (rexw!=0 && (f & OP_DATA_I16_I32_I64)!=0)
|
||||
if (rexw != 0 && (f & OP_DATA_I16_I32_I64) != 0)
|
||||
ld.imm_size = 8;
|
||||
else if ((f & OP_DATA_I16_I32)!=0 || (f & OP_DATA_I16_I32_I64)!=0)
|
||||
else if ((f & OP_DATA_I16_I32) != 0 || (f & OP_DATA_I16_I32_I64) != 0)
|
||||
ld.imm_size = (byte)(4 - (pr_66 << 1));
|
||||
|
||||
/* if exist, add OP_DATA_I16 and OP_DATA_I8 size */
|
||||
ld.imm_size += (byte)(f & 3);
|
||||
|
||||
if ((ld.imm_size)!=0)
|
||||
if ((ld.imm_size) != 0)
|
||||
{
|
||||
s += ld.imm_size;
|
||||
ld.imm_offset = (byte)(p - (byte*)code);
|
||||
ld.flags |= F_IMM;
|
||||
if ((f & OP_RELATIVE)!=0)
|
||||
if ((f & OP_RELATIVE) != 0)
|
||||
ld.flags |= F_RELATIVE;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2018 Misaka Mikoto
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 9298d9b76a5b2074da06bd90eb3bb6fd
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -6,15 +6,11 @@
|
||||
|
||||
using DotNetDetour;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
using Unity.Collections.LowLevel.Unsafe;
|
||||
#if UNITY_EDITOR
|
||||
using UnityEditor;
|
||||
#endif
|
||||
using UnityEngine;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
|
||||
/*
|
||||
@@ -110,9 +106,9 @@ namespace MonoHook
|
||||
/// <param name="proxyMethod">如果还需要调用原始目标方法,可以通过此参数的方法调用,如果不需要可以填 null</param>
|
||||
public MethodHook(MethodBase targetMethod, MethodBase replacementMethod, MethodBase proxyMethod, string data = "")
|
||||
{
|
||||
this.targetMethod = targetMethod;
|
||||
this.replacementMethod = replacementMethod;
|
||||
this.proxyMethod = proxyMethod;
|
||||
this.targetMethod = targetMethod;
|
||||
this.replacementMethod = replacementMethod;
|
||||
this.proxyMethod = proxyMethod;
|
||||
this.tag = data;
|
||||
|
||||
CheckMethod();
|
||||
@@ -219,8 +215,8 @@ namespace MonoHook
|
||||
private void CreateCodePatcher()
|
||||
{
|
||||
long addrOffset = Math.Abs(_targetPtr.ToInt64() - _proxyPtr.ToInt64());
|
||||
|
||||
if(_proxyPtr != IntPtr.Zero)
|
||||
|
||||
if (_proxyPtr != IntPtr.Zero)
|
||||
addrOffset = Math.Max(addrOffset, Math.Abs(_targetPtr.ToInt64() - _proxyPtr.ToInt64()));
|
||||
|
||||
if (LDasm.IsARM())
|
||||
@@ -238,7 +234,7 @@ namespace MonoHook
|
||||
{
|
||||
if (IntPtr.Size == 8)
|
||||
{
|
||||
if(addrOffset < 0x7fffffff) // 2G
|
||||
if (addrOffset < 0x7fffffff) // 2G
|
||||
_codePatcher = new CodePatcher_x64_near(_targetPtr, _replacementPtr, _proxyPtr);
|
||||
else
|
||||
_codePatcher = new CodePatcher_x64_far(_targetPtr, _replacementPtr, _proxyPtr);
|
||||
@@ -263,7 +259,7 @@ namespace MonoHook
|
||||
if (proxyMethod != null && _proxyPtr == null)
|
||||
return false;
|
||||
|
||||
if(_replacementPtr == _targetPtr)
|
||||
if (_replacementPtr == _targetPtr)
|
||||
{
|
||||
throw new Exception($"the addresses of target method {targetMethod.Name} and replacement method {replacementMethod.Name} can not be same");
|
||||
}
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace HybridCLR.Editor.ABI
|
||||
{
|
||||
public static class ABIUtil
|
||||
{
|
||||
public static string GetHybridCLRPlatformMacro(PlatformABI abi)
|
||||
{
|
||||
switch(abi)
|
||||
{
|
||||
case PlatformABI.Arm64: return "HYBRIDCLR_ABI_ARM_64";
|
||||
case PlatformABI.Universal64: return "HYBRIDCLR_ABI_UNIVERSAL_64";
|
||||
case PlatformABI.Universal32: return "HYBRIDCLR_ABI_UNIVERSAL_32";
|
||||
case PlatformABI.WebGL32: return "HYBRIDCLR_ABI_WEBGL32";
|
||||
default: throw new NotSupportedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace HybridCLR.Editor.ABI
|
||||
{
|
||||
|
||||
public class ParamInfo
|
||||
{
|
||||
public TypeInfo Type { get; set; }
|
||||
|
||||
public int Index { get; set; }
|
||||
|
||||
}
|
||||
|
||||
public class ReturnInfo
|
||||
{
|
||||
public TypeInfo Type { get; set; }
|
||||
|
||||
public bool IsVoid => Type.PorType == ParamOrReturnType.VOID;
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return Type.GetTypeName();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace HybridCLR.Editor.ABI
|
||||
{
|
||||
public enum ParamOrReturnType
|
||||
{
|
||||
VOID,
|
||||
I1,
|
||||
U1,
|
||||
I2,
|
||||
U2,
|
||||
I4,
|
||||
U4,
|
||||
I8,
|
||||
U8,
|
||||
R4,
|
||||
R8,
|
||||
I,
|
||||
U,
|
||||
TYPEDBYREF,
|
||||
STRUCT,
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
namespace HybridCLR.Editor.ABI
|
||||
{
|
||||
public enum PlatformABI
|
||||
{
|
||||
Universal32,
|
||||
Universal64,
|
||||
Arm64,
|
||||
WebGL32,
|
||||
}
|
||||
}
|
||||
@@ -1,102 +0,0 @@
|
||||
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.ABI
|
||||
{
|
||||
public class TypeCreator
|
||||
{
|
||||
private readonly Dictionary<TypeSig, TypeInfo> _typeInfoCache = new Dictionary<TypeSig, TypeInfo>(TypeEqualityComparer.Instance);
|
||||
|
||||
private int _nextStructId = 0;
|
||||
|
||||
public TypeInfo CreateTypeInfo(TypeSig type)
|
||||
{
|
||||
type = type.RemovePinnedAndModifiers();
|
||||
if (!_typeInfoCache.TryGetValue(type, out var typeInfo))
|
||||
{
|
||||
typeInfo = CreateTypeInfo0(type);
|
||||
_typeInfoCache.Add(type, typeInfo);
|
||||
}
|
||||
return typeInfo;
|
||||
}
|
||||
|
||||
TypeInfo CreateTypeInfo0(TypeSig type)
|
||||
{
|
||||
type = type.RemovePinnedAndModifiers();
|
||||
if (type.IsByRef)
|
||||
{
|
||||
return TypeInfo.s_u;
|
||||
}
|
||||
switch (type.ElementType)
|
||||
{
|
||||
case ElementType.Void: return TypeInfo.s_void;
|
||||
case ElementType.Boolean: return TypeInfo.s_u1;
|
||||
case ElementType.I1: return TypeInfo.s_i1;
|
||||
case ElementType.U1: return TypeInfo.s_u1;
|
||||
case ElementType.I2: return TypeInfo.s_i2;
|
||||
case ElementType.Char:
|
||||
case ElementType.U2: return TypeInfo.s_u2;
|
||||
case ElementType.I4: return TypeInfo.s_i4;
|
||||
case ElementType.U4: return TypeInfo.s_u4;
|
||||
case ElementType.I8: return TypeInfo.s_i8;
|
||||
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.String:
|
||||
case ElementType.Ptr:
|
||||
case ElementType.ByRef:
|
||||
case ElementType.Class:
|
||||
case ElementType.Array:
|
||||
case ElementType.SZArray:
|
||||
case ElementType.FnPtr:
|
||||
case ElementType.Object:
|
||||
case ElementType.Module:
|
||||
case ElementType.Var:
|
||||
case ElementType.MVar:
|
||||
return TypeInfo.s_u;
|
||||
case ElementType.TypedByRef: return TypeInfo.s_typedByRef;
|
||||
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 CreateTypeInfo(typeDef.GetEnumUnderlyingType());
|
||||
}
|
||||
return CreateValueType(type);
|
||||
}
|
||||
case ElementType.GenericInst:
|
||||
{
|
||||
GenericInstSig gis = (GenericInstSig)type;
|
||||
if (!gis.GenericType.IsValueType)
|
||||
{
|
||||
return TypeInfo.s_u;
|
||||
}
|
||||
TypeDef typeDef = gis.GenericType.ToTypeDefOrRef().ResolveTypeDef();
|
||||
if (typeDef.IsEnum)
|
||||
{
|
||||
return CreateTypeInfo(typeDef.GetEnumUnderlyingType());
|
||||
}
|
||||
return CreateValueType(type);
|
||||
}
|
||||
default: throw new NotSupportedException($"{type.ElementType}");
|
||||
}
|
||||
}
|
||||
|
||||
protected TypeInfo CreateValueType(TypeSig type)
|
||||
{
|
||||
return new TypeInfo(ParamOrReturnType.STRUCT, type, _nextStructId++);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,116 +0,0 @@
|
||||
using dnlib.DotNet;
|
||||
using HybridCLR.Editor.Meta;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Reflection;
|
||||
using UnityEngine;
|
||||
|
||||
namespace HybridCLR.Editor.ABI
|
||||
{
|
||||
public class TypeInfo : IEquatable<TypeInfo>
|
||||
{
|
||||
|
||||
public static readonly TypeInfo s_void = new TypeInfo(ParamOrReturnType.VOID);
|
||||
public static readonly TypeInfo s_i1 = new TypeInfo(ParamOrReturnType.I1);
|
||||
public static readonly TypeInfo s_u1 = new TypeInfo(ParamOrReturnType.U1);
|
||||
public static readonly TypeInfo s_i2 = new TypeInfo(ParamOrReturnType.I2);
|
||||
public static readonly TypeInfo s_u2 = new TypeInfo(ParamOrReturnType.U2);
|
||||
public static readonly TypeInfo s_i4 = new TypeInfo(ParamOrReturnType.I4);
|
||||
public static readonly TypeInfo s_u4 = new TypeInfo(ParamOrReturnType.U4);
|
||||
public static readonly TypeInfo s_i8 = new TypeInfo(ParamOrReturnType.I8);
|
||||
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 const string strTypedByRef = "typedbyref";
|
||||
|
||||
public TypeInfo(ParamOrReturnType portype, TypeSig klass = null, int typeId = 0)
|
||||
{
|
||||
PorType = portype;
|
||||
Klass = klass;
|
||||
_typeId = typeId;
|
||||
}
|
||||
|
||||
public ParamOrReturnType PorType { get; }
|
||||
|
||||
public TypeSig Klass { get; }
|
||||
|
||||
public bool IsStruct => PorType == ParamOrReturnType.STRUCT;
|
||||
|
||||
public bool IsPrimitiveType => PorType <= ParamOrReturnType.U;
|
||||
|
||||
private readonly int _typeId;
|
||||
|
||||
public int TypeId => _typeId;
|
||||
|
||||
public bool Equals(TypeInfo other)
|
||||
{
|
||||
return PorType == other.PorType && TypeEqualityComparer.Instance.Equals(Klass, other.Klass);
|
||||
}
|
||||
|
||||
public override bool Equals(object obj)
|
||||
{
|
||||
return Equals((TypeInfo)obj);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
public string CreateSigName()
|
||||
{
|
||||
switch (PorType)
|
||||
{
|
||||
case ParamOrReturnType.VOID: return "v";
|
||||
case ParamOrReturnType.I1: return "i1";
|
||||
case ParamOrReturnType.U1: return "u1";
|
||||
case ParamOrReturnType.I2: return "i2";
|
||||
case ParamOrReturnType.U2: return "u2";
|
||||
case ParamOrReturnType.I4: return "i4";
|
||||
case ParamOrReturnType.U4: return "u4";
|
||||
case ParamOrReturnType.I8: return "i8";
|
||||
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}";
|
||||
default: throw new NotSupportedException(PorType.ToString());
|
||||
};
|
||||
}
|
||||
|
||||
public string GetTypeName()
|
||||
{
|
||||
switch (PorType)
|
||||
{
|
||||
case ParamOrReturnType.VOID: return "void";
|
||||
case ParamOrReturnType.I1: return "int8_t";
|
||||
case ParamOrReturnType.U1: return "uint8_t";
|
||||
case ParamOrReturnType.I2: return "int16_t";
|
||||
case ParamOrReturnType.U2: return "uint16_t";
|
||||
case ParamOrReturnType.I4: return "int32_t";
|
||||
case ParamOrReturnType.U4: return "uint32_t";
|
||||
case ParamOrReturnType.I8: return "int64_t";
|
||||
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}__";
|
||||
default: throw new NotImplementedException(PorType.ToString());
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,181 +0,0 @@
|
||||
using dnlib.DotNet;
|
||||
using HybridCLR.Editor.Meta;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using UnityEngine;
|
||||
|
||||
namespace HybridCLR.Editor.ABI
|
||||
{
|
||||
public class ValueTypeSizeAligmentCalculator
|
||||
{
|
||||
public static ValueTypeSizeAligmentCalculator Caculator64 { get; } = new ValueTypeSizeAligmentCalculator(false);
|
||||
|
||||
public static ValueTypeSizeAligmentCalculator Caculator32 { get; } = new ValueTypeSizeAligmentCalculator(true);
|
||||
|
||||
public ValueTypeSizeAligmentCalculator(bool arch32)
|
||||
{
|
||||
_referenceSize = arch32 ? 4 : 8;
|
||||
}
|
||||
|
||||
private readonly int _referenceSize;
|
||||
|
||||
private static bool IsIgnoreField(FieldDef field)
|
||||
{
|
||||
var ignoreAttr = field.CustomAttributes.Where(a => a.AttributeType.FullName == "UnityEngine.Bindings.IgnoreAttribute").FirstOrDefault();
|
||||
if (ignoreAttr == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
CANamedArgument arg = ignoreAttr.GetProperty("DoesNotContributeToSize");
|
||||
if(arg != null && (bool)arg.Value)
|
||||
{
|
||||
//Debug.Log($"IgnoreField.DoesNotContributeToSize = true:{field}");
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private (int Size, int Aligment) SizeAndAligmentOfStruct(TypeSig type)
|
||||
{
|
||||
int totalSize = 0;
|
||||
int packAligment = 8;
|
||||
int maxAligment = 1;
|
||||
|
||||
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;
|
||||
if (sa != null && sa.PackingSize > 0)
|
||||
{
|
||||
packAligment = sa.PackingSize;
|
||||
}
|
||||
bool useSLSize = true;
|
||||
foreach (FieldDef field in typeDef.Fields)
|
||||
{
|
||||
if (field.IsStatic)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
TypeSig fieldType = ctx != null ? MetaUtil.Inflate(field.FieldType, ctx) : field.FieldType;
|
||||
var (fs, fa) = SizeAndAligmentOf(fieldType);
|
||||
fa = Math.Min(fa, packAligment);
|
||||
if (fa > maxAligment)
|
||||
{
|
||||
maxAligment = fa;
|
||||
}
|
||||
if (IsIgnoreField(field))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if (typeDef.Layout.HasFlag(dnlib.DotNet.TypeAttributes.ExplicitLayout))
|
||||
{
|
||||
int offset = (int)field.FieldOffset.Value;
|
||||
totalSize = Math.Max(totalSize, offset + fs);
|
||||
if (sa != null && offset > sa.ClassSize)
|
||||
{
|
||||
useSLSize = false;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (totalSize % fa != 0)
|
||||
{
|
||||
totalSize = (totalSize + fa - 1) / fa * fa;
|
||||
}
|
||||
totalSize += fs;
|
||||
if (sa != null && totalSize > sa.ClassSize)
|
||||
{
|
||||
useSLSize = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (totalSize == 0)
|
||||
{
|
||||
totalSize = maxAligment;
|
||||
}
|
||||
if (totalSize % maxAligment != 0)
|
||||
{
|
||||
totalSize = (totalSize + maxAligment - 1) / maxAligment * maxAligment;
|
||||
}
|
||||
if (sa != null && sa.ClassSize > 0)
|
||||
{
|
||||
if (/*sa.Value == LayoutKind.Explicit &&*/ useSLSize)
|
||||
{
|
||||
totalSize = (int)sa.ClassSize;
|
||||
while(totalSize % maxAligment != 0)
|
||||
{
|
||||
maxAligment /= 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
return (totalSize, maxAligment);
|
||||
}
|
||||
|
||||
public (int Size, int Aligment) SizeAndAligmentOf(TypeSig type)
|
||||
{
|
||||
type = type.RemovePinnedAndModifiers();
|
||||
if (type.IsByRef || !type.IsValueType || type.IsArray)
|
||||
return (_referenceSize, _referenceSize);
|
||||
|
||||
switch (type.ElementType)
|
||||
{
|
||||
case ElementType.Void: throw new NotSupportedException(type.ToString());
|
||||
case ElementType.Boolean:
|
||||
case ElementType.I1:
|
||||
case ElementType.U1: return (1, 1);
|
||||
case ElementType.Char:
|
||||
case ElementType.I2:
|
||||
case ElementType.U2: return (2, 2);
|
||||
case ElementType.I4:
|
||||
case ElementType.U4: return (4, 4);
|
||||
case ElementType.I8:
|
||||
case ElementType.U8: return (8, 8);
|
||||
case ElementType.R4: return (4, 4);
|
||||
case ElementType.R8: return (8, 8);
|
||||
case ElementType.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:
|
||||
case ElementType.Module: return (_referenceSize, _referenceSize);
|
||||
case ElementType.TypedByRef: return SizeAndAligmentOfStruct(type);
|
||||
case ElementType.ValueType:
|
||||
{
|
||||
TypeDef typeDef = type.ToTypeDefOrRef().ResolveTypeDef();
|
||||
if (typeDef.IsEnum)
|
||||
{
|
||||
return SizeAndAligmentOf(typeDef.GetEnumUnderlyingType());
|
||||
}
|
||||
return SizeAndAligmentOfStruct(type);
|
||||
}
|
||||
case ElementType.GenericInst:
|
||||
{
|
||||
GenericInstSig gis = (GenericInstSig)type;
|
||||
if (!gis.GenericType.IsValueType)
|
||||
{
|
||||
return (_referenceSize, _referenceSize);
|
||||
}
|
||||
TypeDef typeDef = gis.GenericType.ToTypeDefOrRef().ResolveTypeDef();
|
||||
if (typeDef.IsEnum)
|
||||
{
|
||||
return SizeAndAligmentOf(typeDef.GetEnumUnderlyingType());
|
||||
}
|
||||
return SizeAndAligmentOfStruct(type);
|
||||
}
|
||||
default: throw new NotSupportedException(type.ToString());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,254 +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
|
||||
using UnityEditor.Build;
|
||||
using UnityEditor.Callbacks;
|
||||
using UnityEditor.iOS.Xcode;
|
||||
using UnityEngine;
|
||||
|
||||
namespace HybridCLR.Editor.BuildProcessors
|
||||
{
|
||||
public static class AddLil2cppSourceCodeToXcodeproj2021OrOlder
|
||||
{
|
||||
//[MenuItem("Test/GenProj")]
|
||||
//public static void Modify()
|
||||
//{
|
||||
// OnPostProcessBuild(BuildTarget.iOS, $"{SettingsUtil.ProjectDir}/Build-iOS");
|
||||
//}
|
||||
|
||||
//[MenuItem("Test/CreateLumps")]
|
||||
//public static void CreateLumpsCmd()
|
||||
//{
|
||||
// CreateLumps($"{SettingsUtil.LocalIl2CppDir}/libil2cpp", $"{SettingsUtil.HybridCLRDataDir}/lumps");
|
||||
//}
|
||||
|
||||
[PostProcessBuild]
|
||||
public static void OnPostProcessBuild(BuildTarget target, string pathToBuiltProject)
|
||||
{
|
||||
if (target != BuildTarget.iOS || !HybridCLRSettings.Instance.enable)
|
||||
return;
|
||||
/*
|
||||
* 1. 生成lump,并且添加到工程
|
||||
3. 将libil2cpp目录复制到 Library/. 删除旧的. search paths里修改 libil2cpp/include为libil2cpp
|
||||
3. Libraries/bdwgc/include -> Libraries/external/bdwgc/include
|
||||
4. 将external目录复制到 Library/external。删除旧目录
|
||||
5. 将Library/external/baselib/Platforms/OSX改名为 IOS 全大写
|
||||
6. 将 external/zlib下c 文件添加到工程
|
||||
7. 移除libil2cpp.a
|
||||
8. Include path add libil2cpp/os/ClassLibraryPAL/brotli/include
|
||||
9. add external/xxHash
|
||||
*/
|
||||
|
||||
string pbxprojFile = $"{pathToBuiltProject}/Unity-iPhone.xcodeproj/project.pbxproj";
|
||||
string srcLibil2cppDir = $"{SettingsUtil.LocalIl2CppDir}/libil2cpp";
|
||||
string dstLibil2cppDir = $"{pathToBuiltProject}/Libraries/libil2cpp";
|
||||
string lumpDir = $"{pathToBuiltProject}/Libraries/lumps";
|
||||
string srcExternalDir = $"{SettingsUtil.LocalIl2CppDir}/external";
|
||||
string dstExternalDir = $"{pathToBuiltProject}/Libraries/external";
|
||||
//RemoveExternalLibil2cppOption(srcExternalDir, dstExternalDir);
|
||||
CopyLibil2cppToXcodeProj(srcLibil2cppDir, dstLibil2cppDir);
|
||||
CopyExternalToXcodeProj(srcExternalDir, dstExternalDir);
|
||||
var lumpFiles = CreateLumps(dstLibil2cppDir, lumpDir);
|
||||
var extraSources = GetExtraSourceFiles(dstExternalDir, dstLibil2cppDir);
|
||||
var cflags = new List<string>()
|
||||
{
|
||||
"-DIL2CPP_MONO_DEBUGGER_DISABLED",
|
||||
};
|
||||
ModifyPBXProject(pathToBuiltProject, pbxprojFile, lumpFiles, extraSources, cflags);
|
||||
}
|
||||
|
||||
private static string GetRelativePathFromProj(string path)
|
||||
{
|
||||
return path.Substring(path.IndexOf("Libraries", StringComparison.Ordinal)).Replace('\\', '/');
|
||||
}
|
||||
|
||||
private static void ModifyPBXProject(string pathToBuiltProject, string pbxprojFile, List<LumpFile> lumpFiles, List<string> extraFiles, List<string> cflags)
|
||||
{
|
||||
var proj = new PBXProject();
|
||||
proj.ReadFromFile(pbxprojFile);
|
||||
string targetGUID = proj.GetUnityFrameworkTargetGuid();
|
||||
// 移除旧的libil2cpp.a
|
||||
var libil2cppGUID = proj.FindFileGuidByProjectPath("Libraries/libil2cpp.a");
|
||||
if (!string.IsNullOrEmpty(libil2cppGUID))
|
||||
{
|
||||
proj.RemoveFileFromBuild(targetGUID, libil2cppGUID);
|
||||
proj.RemoveFile(libil2cppGUID);
|
||||
File.Delete(Path.Combine(pathToBuiltProject, "Libraries", "libil2cpp.a"));
|
||||
}
|
||||
|
||||
//var lumpGroupGuid = proj.AddFile("Lumps", $"Classes/Lumps", PBXSourceTree.Group);
|
||||
|
||||
foreach (var lumpFile in lumpFiles)
|
||||
{
|
||||
string lumpFileName = Path.GetFileName(lumpFile.lumpFile);
|
||||
string projPathOfFile = $"Classes/Lumps/{lumpFileName}";
|
||||
string relativePathOfFile = GetRelativePathFromProj(lumpFile.lumpFile);
|
||||
string lumpGuid = proj.FindFileGuidByProjectPath(projPathOfFile);
|
||||
if (!string.IsNullOrEmpty(lumpGuid))
|
||||
{
|
||||
proj.RemoveFileFromBuild(targetGUID, lumpGuid);
|
||||
proj.RemoveFile(lumpGuid);
|
||||
}
|
||||
lumpGuid = proj.AddFile(relativePathOfFile, projPathOfFile, PBXSourceTree.Source);
|
||||
proj.AddFileToBuild(targetGUID, lumpGuid);
|
||||
}
|
||||
|
||||
foreach (var extraFile in extraFiles)
|
||||
{
|
||||
string projPathOfFile = $"Classes/Extrals/{Path.GetFileName(extraFile)}";
|
||||
string extraFileGuid = proj.FindFileGuidByProjectPath(projPathOfFile);
|
||||
if (!string.IsNullOrEmpty(extraFileGuid))
|
||||
{
|
||||
proj.RemoveFileFromBuild(targetGUID, extraFileGuid);
|
||||
proj.RemoveFile(extraFileGuid);
|
||||
//Debug.LogWarning($"remove exist extra file:{projPathOfFile} guid:{extraFileGuid}");
|
||||
}
|
||||
var lumpGuid = proj.AddFile(GetRelativePathFromProj(extraFile), projPathOfFile, PBXSourceTree.Source);
|
||||
proj.AddFileToBuild(targetGUID, lumpGuid);
|
||||
}
|
||||
|
||||
foreach(var configName in proj.BuildConfigNames())
|
||||
{
|
||||
//Debug.Log($"build config:{bcn}");
|
||||
string configGuid = proj.BuildConfigByName(targetGUID, configName);
|
||||
string headerSearchPaths = "HEADER_SEARCH_PATHS";
|
||||
string hspProp = proj.GetBuildPropertyForConfig(configGuid, headerSearchPaths);
|
||||
//Debug.Log($"config guid:{configGuid} prop:{hspProp}");
|
||||
string newPro = hspProp.Replace("libil2cpp/include", "libil2cpp")
|
||||
.Replace("Libraries/bdwgc", "Libraries/external/bdwgc");
|
||||
|
||||
if (!newPro.Contains("Libraries/libil2cpp/os/ClassLibraryPAL/brotli/include"))
|
||||
{
|
||||
newPro += " $(SRCROOT)/Libraries/libil2cpp/os/ClassLibraryPAL/brotli/include";
|
||||
}
|
||||
if (!newPro.Contains("Libraries/external/xxHash"))
|
||||
{
|
||||
newPro += " $(SRCROOT)/Libraries/external/xxHash";
|
||||
}
|
||||
//Debug.Log($"config:{bcn} new prop:{newPro}");
|
||||
proj.SetBuildPropertyForConfig(configGuid, headerSearchPaths, newPro);
|
||||
|
||||
string cflagKey = "OTHER_CFLAGS";
|
||||
string cfProp = proj.GetBuildPropertyForConfig(configGuid, cflagKey);
|
||||
foreach (var flag in cflags)
|
||||
{
|
||||
if (!cfProp.Contains(flag))
|
||||
{
|
||||
cfProp += " " + flag;
|
||||
}
|
||||
}
|
||||
if (configName.Contains("Debug") && !cfProp.Contains("-DIL2CPP_DEBUG="))
|
||||
{
|
||||
cfProp += " -DIL2CPP_DEBUG=1 -DDEBUG=1";
|
||||
}
|
||||
proj.SetBuildPropertyForConfig(configGuid, cflagKey, cfProp);
|
||||
|
||||
}
|
||||
proj.WriteToFile(pbxprojFile);
|
||||
}
|
||||
|
||||
private static void CopyLibil2cppToXcodeProj(string srcLibil2cppDir, string dstLibil2cppDir)
|
||||
{
|
||||
BashUtil.RemoveDir(dstLibil2cppDir);
|
||||
BashUtil.CopyDir(srcLibil2cppDir, dstLibil2cppDir, true);
|
||||
}
|
||||
|
||||
|
||||
private static void CopyExternalToXcodeProj(string srcExternalDir, string dstExternalDir)
|
||||
{
|
||||
BashUtil.RemoveDir(dstExternalDir);
|
||||
BashUtil.CopyDir(srcExternalDir, dstExternalDir, true);
|
||||
|
||||
string baselibPlatfromsDir = $"{dstExternalDir}/baselib/Platforms";
|
||||
BashUtil.RemoveDir($"{baselibPlatfromsDir}/IOS");
|
||||
BashUtil.CopyDir($"{baselibPlatfromsDir}/OSX", $"{baselibPlatfromsDir}/IOS", true);
|
||||
}
|
||||
|
||||
class LumpFile
|
||||
{
|
||||
public List<string> cppFiles = new List<string>();
|
||||
|
||||
public readonly string lumpFile;
|
||||
|
||||
public readonly string il2cppConfigFile;
|
||||
|
||||
public LumpFile(string lumpFile, string il2cppConfigFile)
|
||||
{
|
||||
this.lumpFile = lumpFile;
|
||||
this.il2cppConfigFile = il2cppConfigFile;
|
||||
this.cppFiles.Add(il2cppConfigFile);
|
||||
}
|
||||
|
||||
public void SaveFile()
|
||||
{
|
||||
var lumpFileContent = new List<string>();
|
||||
foreach (var file in cppFiles)
|
||||
{
|
||||
lumpFileContent.Add($"#include \"{GetRelativePathFromProj(file)}\"");
|
||||
}
|
||||
File.WriteAllLines(lumpFile, lumpFileContent, Encoding.UTF8);
|
||||
Debug.Log($"create lump file:{lumpFile}");
|
||||
}
|
||||
}
|
||||
|
||||
private static List<LumpFile> CreateLumps(string libil2cppDir, string outputDir)
|
||||
{
|
||||
BashUtil.RecreateDir(outputDir);
|
||||
|
||||
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,48 +1,83 @@
|
||||
using HybridCLR.Editor.Installer;
|
||||
using HybridCLR.Editor.Settings;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using UnityEditor;
|
||||
using UnityEditor.Build;
|
||||
using UnityEditor.Callbacks;
|
||||
using UnityEngine;
|
||||
// Copyright 2026 Code Philosophy
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
#if UNITY_2022_2_OR_NEWER && UNITY_IOS
|
||||
#if UNITY_2022 && (UNITY_IOS || UNITY_TVOS || UNITY_VISIONOS)
|
||||
|
||||
namespace HybridCLR.Editor.BuildProcessors
|
||||
namespace HybridCLR.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 (target != BuildTarget.iOS || !HybridCLRSettings.Instance.enable)
|
||||
if (!HybridCLRSettings.Instance.enable)
|
||||
return;
|
||||
|
||||
string pbxprojFile = $"{pathToBuiltProject}/Unity-iPhone.xcodeproj/project.pbxproj";
|
||||
string pbxprojFile = BuildProcessorUtil.GetXcodeProjectFile(pathToBuiltProject);
|
||||
RemoveExternalLibil2cppOption(pbxprojFile);
|
||||
CopyLibil2cppToXcodeProj(pathToBuiltProject);
|
||||
}
|
||||
|
||||
private static string TryRemoveDunplicateShellScriptSegment(string pbxprojFile, string pbxprojContent)
|
||||
{
|
||||
// will appear duplicated Shell Script segment when append to existed xcode project.
|
||||
// This is unity bug.
|
||||
// we remove duplicated Shell Script to avoid build error.
|
||||
string copyFileComment = @"/\* CopyFiles \*/,\s+([A-Z0-9]{24}) /\* ShellScript \*/,\s+([A-Z0-9]{24}) /\* ShellScript \*/,";
|
||||
var m = Regex.Match(pbxprojContent, copyFileComment, RegexOptions.Multiline);
|
||||
if (!m.Success)
|
||||
{
|
||||
return pbxprojContent;
|
||||
}
|
||||
|
||||
if (m.Groups[1].Value != m.Groups[2].Value)
|
||||
{
|
||||
throw new BuildFailedException($"find invalid /* ShellScript */ segment");
|
||||
}
|
||||
|
||||
int startIndexOfDupShellScript = m.Groups[2].Index;
|
||||
int endIndexOfDupShellScript = pbxprojContent.IndexOf(",", startIndexOfDupShellScript);
|
||||
|
||||
pbxprojContent = pbxprojContent.Remove(startIndexOfDupShellScript, endIndexOfDupShellScript + 1 - startIndexOfDupShellScript);
|
||||
Debug.LogWarning($"[AddLil2cppSourceCodeToXcodeproj] remove duplicated '/* ShellScript */' from file '{pbxprojFile}'");
|
||||
return pbxprojContent;
|
||||
}
|
||||
|
||||
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))
|
||||
if (pbxprojContent.Contains(removeBuildOption))
|
||||
{
|
||||
//throw new BuildFailedException("modified project.pbxproj fail");
|
||||
Debug.LogError("[AddLil2cppSourceCodeToXcodeproj] modified project.pbxproj fail");
|
||||
return;
|
||||
pbxprojContent = pbxprojContent.Replace(removeBuildOption, "");
|
||||
Debug.Log($"[AddLil2cppSourceCodeToXcodeproj] remove il2cpp build option '{removeBuildOption}' from file '{pbxprojFile}'");
|
||||
}
|
||||
pbxprojContent = pbxprojContent.Replace(removeBuildOption, "");
|
||||
else
|
||||
{
|
||||
Debug.LogWarning($"[AddLil2cppSourceCodeToXcodeproj] project.pbxproj remove building option:'{removeBuildOption}' fail. This may occur when 'Append' to existing xcode project in building");
|
||||
}
|
||||
|
||||
pbxprojContent = TryRemoveDunplicateShellScriptSegment(pbxprojFile, pbxprojContent);
|
||||
|
||||
|
||||
File.WriteAllText(pbxprojFile, pbxprojContent, Encoding.UTF8);
|
||||
Debug.Log($"[AddLil2cppSourceCodeToXcodeproj] remove il2cpp build option '{removeBuildOption}' from file '{pbxprojFile}'");
|
||||
}
|
||||
|
||||
private static void CopyLibil2cppToXcodeProj(string pathToBuiltProject)
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
// Copyright 2026 Code Philosophy
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
#if UNITY_2023_1_OR_NEWER && (UNITY_IOS || UNITY_TVOS || UNITY_VISIONOS)
|
||||
|
||||
namespace HybridCLR.BuildProcessors
|
||||
{
|
||||
public static class AddLil2cppSourceCodeToXcodeproj2023OrNewer
|
||||
{
|
||||
|
||||
[PostProcessBuild]
|
||||
public static void OnPostProcessBuild(BuildTarget target, string pathToBuiltProject)
|
||||
{
|
||||
if (!HybridCLRSettings.Instance.enable)
|
||||
return;
|
||||
CopyLibil2cppToXcodeProj(pathToBuiltProject);
|
||||
}
|
||||
|
||||
private static void CopyLibil2cppToXcodeProj(string pathToBuiltProject)
|
||||
{
|
||||
string srcLibil2cppDir = $"{SettingsUtil.LocalIl2CppDir}/libil2cpp";
|
||||
string destLibil2cppDir = $"{pathToBuiltProject}/Il2CppOutputProject/IL2CPP/libil2cpp";
|
||||
BashUtil.RemoveDir(destLibil2cppDir);
|
||||
BashUtil.CopyDir(srcLibil2cppDir, destLibil2cppDir, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 2fa46135129b046a28014d58fdfd18ca
|
||||
@@ -1,21 +1,40 @@
|
||||
using HybridCLR.Editor.Settings;
|
||||
// Copyright 2026 Code Philosophy
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
using HybridCLR.Settings;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.IO;
|
||||
using System.Text.RegularExpressions;
|
||||
using UnityEditor;
|
||||
using UnityEditor.Build;
|
||||
using UnityEditor.Build.Reporting;
|
||||
using UnityEngine;
|
||||
using static UnityEngine.GraphicsBuffer;
|
||||
|
||||
namespace HybridCLR.Editor.BuildProcessors
|
||||
namespace HybridCLR.BuildProcessors
|
||||
{
|
||||
internal class CheckSettings : IPreprocessBuildWithReport
|
||||
{
|
||||
public int callbackOrder => 0;
|
||||
|
||||
public static bool DisableMethodBridgeDevelopmentFlagChecking { get; set; }
|
||||
|
||||
public void OnPreprocessBuild(BuildReport report)
|
||||
{
|
||||
HybridCLRSettings globalSettings = SettingsUtil.HybridCLRSettings;
|
||||
@@ -42,12 +61,21 @@ namespace HybridCLR.Editor.BuildProcessors
|
||||
return;
|
||||
}
|
||||
BuildTargetGroup buildTargetGroup = BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget);
|
||||
#if UNITY_6000_0_OR_NEWER
|
||||
NamedBuildTarget namedBuildTarget = NamedBuildTarget.FromBuildTargetGroup(buildTargetGroup);
|
||||
ScriptingImplementation curScriptingImplementation = PlayerSettings.GetScriptingBackend(namedBuildTarget);
|
||||
#else
|
||||
ScriptingImplementation curScriptingImplementation = PlayerSettings.GetScriptingBackend(buildTargetGroup);
|
||||
#endif
|
||||
ScriptingImplementation targetScriptingImplementation = ScriptingImplementation.IL2CPP;
|
||||
if (curScriptingImplementation != targetScriptingImplementation)
|
||||
{
|
||||
Debug.LogError($"[CheckSettings] current ScriptingBackend:{curScriptingImplementation},have been switched to:{targetScriptingImplementation} automatically");
|
||||
#if UNITY_6000_0_OR_NEWER
|
||||
PlayerSettings.SetScriptingBackend(namedBuildTarget, targetScriptingImplementation);
|
||||
#else
|
||||
PlayerSettings.SetScriptingBackend(buildTargetGroup, targetScriptingImplementation);
|
||||
#endif
|
||||
}
|
||||
|
||||
var installer = new Installer.InstallerController();
|
||||
@@ -67,6 +95,24 @@ namespace HybridCLR.Editor.BuildProcessors
|
||||
Debug.LogWarning("[CheckSettings] No hot update modules configured in HybridCLRSettings");
|
||||
}
|
||||
|
||||
if (!DisableMethodBridgeDevelopmentFlagChecking)
|
||||
{
|
||||
string methodBridgeFile = $"{SettingsUtil.GeneratedCppDir}/MethodBridge.inc";
|
||||
var match = Regex.Match(File.ReadAllText(methodBridgeFile), @"// DEVELOPMENT=(\d)");
|
||||
if (match.Success)
|
||||
{
|
||||
int developmentFlagInMethodBridge = int.Parse(match.Groups[1].Value);
|
||||
int developmentFlagInEditorSettings = EditorUserBuildSettings.development ? 1 : 0;
|
||||
if (developmentFlagInMethodBridge != developmentFlagInEditorSettings)
|
||||
{
|
||||
Debug.LogError($"[CheckSettings] MethodBridge.inc DEVELOPMENT flag:{developmentFlagInMethodBridge} is inconsistent with EditorUserBuildSettings.development:{developmentFlagInEditorSettings}. Please run 'HybridCLR/Generate/All' before building.");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.LogError("[CheckSettings] MethodBridge.inc DEVELOPMENT flag not found. Please run 'HybridCLR/Generate/All' before building.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,23 +1,36 @@
|
||||
using HybridCLR.Editor.Installer;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
// Copyright 2026 Code Philosophy
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
using HybridCLR.Utils;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using UnityEditor;
|
||||
using UnityEditor.Build;
|
||||
using UnityEditor.Build.Reporting;
|
||||
using UnityEditor.Il2Cpp;
|
||||
using UnityEditor.UnityLinker;
|
||||
using UnityEngine;
|
||||
#if !UNITY_2021_1_OR_NEWER
|
||||
using UnityEditor.Il2Cpp;
|
||||
#endif
|
||||
|
||||
namespace HybridCLR.Editor.BuildProcessors
|
||||
namespace HybridCLR.BuildProcessors
|
||||
{
|
||||
internal class CopyStrippedAOTAssemblies : IPostprocessBuildWithReport, IPreprocessBuildWithReport
|
||||
#if !UNITY_2021_1_OR_NEWER
|
||||
, IIl2CppProcessor
|
||||
#endif
|
||||
{
|
||||
|
||||
public int callbackOrder => 0;
|
||||
@@ -28,24 +41,52 @@ namespace HybridCLR.Editor.BuildProcessors
|
||||
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";
|
||||
default: return "";
|
||||
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.WSAPlayer:
|
||||
return $"{projectDir}/Library/Bee/artifacts/UWPPlayerBuildProgram/ManagedStripped";
|
||||
case BuildTarget.Android:
|
||||
return $"{projectDir}/Library/Bee/artifacts/Android/ManagedStripped";
|
||||
#if TUANJIE_2022_3_OR_NEWER
|
||||
case BuildTarget.HMIAndroid:
|
||||
return $"{projectDir}/Library/Bee/artifacts/HMIAndroid/ManagedStripped";
|
||||
#endif
|
||||
case BuildTarget.iOS:
|
||||
#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
|
||||
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.GameCoreXboxOne:
|
||||
case BuildTarget.GameCoreXboxSeries:
|
||||
return $"{projectDir}/Library/Bee/artifacts/GameCorePlayerBuildProgram/ManagedStripped";
|
||||
#if UNITY_WEIXINMINIGAME
|
||||
case BuildTarget.WeixinMiniGame:
|
||||
return $"{projectDir}/Library/Bee/artifacts/WeixinMiniGame/ManagedStripped";
|
||||
#endif
|
||||
#if UNITY_OPENHARMONY
|
||||
case BuildTarget.OpenHarmony:
|
||||
return $"{projectDir}/Library/Bee/artifacts/OpenHarmonyPlayerBuildProgram/ManagedStripped";
|
||||
#endif
|
||||
default: return "";
|
||||
}
|
||||
}
|
||||
#else
|
||||
@@ -58,9 +99,9 @@ namespace HybridCLR.Editor.BuildProcessors
|
||||
}
|
||||
|
||||
public void OnBeforeConvertRun(BuildReport report, Il2CppBuildPipelineData data)
|
||||
{
|
||||
// 此回调只在 2020中调用
|
||||
CopyStripDlls(GetStripAssembliesDir2020(data.target), data.target);
|
||||
{
|
||||
BuildTarget target = report.summary.platform;
|
||||
CopyStripDlls(GetStripAssembliesDir2020(target), target);
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -88,7 +129,7 @@ namespace HybridCLR.Editor.BuildProcessors
|
||||
public void OnPostprocessBuild(BuildReport report)
|
||||
{
|
||||
#if UNITY_2021_1_OR_NEWER
|
||||
BuildTarget target = EditorUserBuildSettings.activeBuildTarget;
|
||||
BuildTarget target = report.summary.platform;
|
||||
string srcStripDllPath = GetStripAssembliesDir2021(target);
|
||||
if (!string.IsNullOrEmpty(srcStripDllPath) && Directory.Exists(srcStripDllPath))
|
||||
{
|
||||
@@ -99,9 +140,9 @@ namespace HybridCLR.Editor.BuildProcessors
|
||||
|
||||
public void OnPreprocessBuild(BuildReport report)
|
||||
{
|
||||
BuildTarget target = EditorUserBuildSettings.activeBuildTarget;
|
||||
BuildTarget target = report.summary.platform;
|
||||
var dstPath = SettingsUtil.GetAssembliesPostIl2CppStripDir(target);
|
||||
BashUtil.RecreateDir(dstPath);
|
||||
DirectoryUtil.RecreateDir(dstPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,18 +1,37 @@
|
||||
using HybridCLR.Editor.Meta;
|
||||
// Copyright 2026 Code Philosophy
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
|
||||
using HybridCLR.Utils;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using UnityEditor;
|
||||
using UnityEditor.Build;
|
||||
using UnityEngine;
|
||||
|
||||
namespace HybridCLR.Editor.BuildProcessors
|
||||
namespace HybridCLR.BuildProcessors
|
||||
{
|
||||
/// <summary>
|
||||
/// 将热更新dll从Build过程中过滤,防止打包到主工程中
|
||||
/// Filter hot update assemblies from build process to prevent them from being packaged into the main project
|
||||
/// </summary>
|
||||
internal class FilterHotFixAssemblies : IFilterBuildAssemblies
|
||||
{
|
||||
@@ -27,9 +46,8 @@ namespace HybridCLR.Editor.BuildProcessors
|
||||
}
|
||||
List<string> allHotUpdateDllNames = SettingsUtil.HotUpdateAssemblyNamesExcludePreserved;
|
||||
|
||||
// 检查是否重复填写
|
||||
var hotUpdateDllSet = new HashSet<string>();
|
||||
foreach(var hotUpdateDll in allHotUpdateDllNames)
|
||||
foreach (var hotUpdateDll in allHotUpdateDllNames)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(hotUpdateDll))
|
||||
{
|
||||
@@ -42,17 +60,15 @@ namespace HybridCLR.Editor.BuildProcessors
|
||||
}
|
||||
|
||||
var assResolver = MetaUtil.CreateHotUpdateAssemblyResolver(EditorUserBuildSettings.activeBuildTarget, allHotUpdateDllNames);
|
||||
// 检查是否填写了正确的dll名称
|
||||
foreach (var hotUpdateDllName in allHotUpdateDllNames)
|
||||
{
|
||||
if (assemblies.Select(Path.GetFileNameWithoutExtension).All(ass => ass != hotUpdateDllName)
|
||||
if (assemblies.Select(Path.GetFileNameWithoutExtension).All(ass => ass != hotUpdateDllName)
|
||||
&& string.IsNullOrEmpty(assResolver.ResolveAssembly(hotUpdateDllName, false)))
|
||||
{
|
||||
throw new BuildFailedException($"hot update assembly:{hotUpdateDllName} doesn't exist");
|
||||
}
|
||||
}
|
||||
|
||||
// 将热更dll从打包列表中移除
|
||||
return assemblies.Where(ass =>
|
||||
{
|
||||
string assName = Path.GetFileNameWithoutExtension(ass);
|
||||
|
||||
+32
-14
@@ -1,18 +1,36 @@
|
||||
|
||||
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;
|
||||
// Copyright 2026 Code Philosophy
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
namespace HybridCLR.MonoHook
|
||||
|
||||
using MonoHook;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
|
||||
namespace HybridCLR.BuildProcessors.Hooks
|
||||
{
|
||||
#if UNITY_2021_1_OR_NEWER
|
||||
#if UNITY_2021_1_OR_NEWER && !UNITY_2023_1_OR_NEWER
|
||||
[InitializeOnLoad]
|
||||
public class CopyStrippedAOTAssembliesHook
|
||||
{
|
||||
@@ -43,7 +61,7 @@ namespace HybridCLR.MonoHook
|
||||
return false;
|
||||
}
|
||||
UnityEngine.Debug.Log($"== StripAssembliesTo outputDir:{outputFolder}");
|
||||
string outputStrippedDir = HybridCLR.Editor.SettingsUtil.GetAssembliesPostIl2CppStripDir(EditorUserBuildSettings.activeBuildTarget);
|
||||
string outputStrippedDir = HybridCLR.SettingsUtil.GetAssembliesPostIl2CppStripDir(EditorUserBuildSettings.activeBuildTarget);
|
||||
Directory.CreateDirectory(outputStrippedDir);
|
||||
foreach (var aotDll in Directory.GetFiles(outputFolder, "*.dll"))
|
||||
{
|
||||
+29
-13
@@ -1,18 +1,34 @@
|
||||
|
||||
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;
|
||||
// Copyright 2026 Code Philosophy
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
namespace HybridCLR.MonoHook
|
||||
|
||||
using MonoHook;
|
||||
using System;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
|
||||
namespace HybridCLR.BuildProcessors.Hooks
|
||||
{
|
||||
#if UNITY_2022
|
||||
#if UNITY_2022 || UNITY_2023_1_OR_NEWER
|
||||
[InitializeOnLoad]
|
||||
public class GetIl2CppFolderHook
|
||||
{
|
||||
@@ -0,0 +1,82 @@
|
||||
// Copyright 2026 Code Philosophy
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
namespace HybridCLR.BuildProcessors.Hooks
|
||||
{
|
||||
#if UNITY_2021_1_OR_NEWER && (UNITY_WEBGL || UNITY_WEIXINMINIGAME)
|
||||
[InitializeOnLoad]
|
||||
public class PatchScriptingAssembliesJsonHook
|
||||
{
|
||||
private static MethodHook _hook;
|
||||
|
||||
static PatchScriptingAssembliesJsonHook()
|
||||
{
|
||||
if (_hook == null)
|
||||
{
|
||||
Type type = typeof(UnityEditor.EditorApplication);
|
||||
MethodInfo miTarget = type.GetMethod("BuildMainWindowTitle", BindingFlags.Static | BindingFlags.NonPublic);
|
||||
|
||||
MethodInfo miReplacement = new Func<string>(BuildMainWindowTitle).Method;
|
||||
MethodInfo miProxy = new Func<string>(BuildMainWindowTitleProxy).Method;
|
||||
|
||||
_hook = new MethodHook(miTarget, miReplacement, miProxy);
|
||||
_hook.Install();
|
||||
}
|
||||
}
|
||||
|
||||
private static string BuildMainWindowTitle()
|
||||
{
|
||||
var cacheDir = $"{Application.dataPath}/../Library/PlayerDataCache";
|
||||
if (Directory.Exists(cacheDir))
|
||||
{
|
||||
foreach (var tempJsonPath in Directory.GetDirectories(cacheDir, "*", SearchOption.TopDirectoryOnly))
|
||||
{
|
||||
string dirName = Path.GetFileName(tempJsonPath);
|
||||
#if UNITY_WEIXINMINIGAME
|
||||
if (!dirName.Contains("WeixinMiniGame"))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
#else
|
||||
if (!dirName.Contains("WebGL"))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
#endif
|
||||
|
||||
var patcher = new PatchScriptingAssemblyList();
|
||||
patcher.PathScriptingAssembilesFile(tempJsonPath);
|
||||
}
|
||||
}
|
||||
|
||||
string newTitle = BuildMainWindowTitleProxy();
|
||||
return newTitle;
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.NoOptimization)]
|
||||
private static string BuildMainWindowTitleProxy()
|
||||
{
|
||||
// Padding added only to satisfy MonoHook minimum code length requirements
|
||||
UnityEngine.Debug.Log(12345.ToString());
|
||||
return string.Empty;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
#if UNITY_EDITOR
|
||||
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 int callbackOrder => 0;
|
||||
|
||||
public void OnPreprocessBuild(BuildReport report)
|
||||
{
|
||||
var clEnv = Environment.GetEnvironmentVariable("_CL_");
|
||||
|
||||
if (string.IsNullOrEmpty(clEnv))
|
||||
{
|
||||
Environment.SetEnvironmentVariable("_CL_", kWorkaroundFlag);
|
||||
}
|
||||
else if (!clEnv.Contains(kWorkaroundFlag))
|
||||
{
|
||||
clEnv += " " + kWorkaroundFlag;
|
||||
Environment.SetEnvironmentVariable("_CL_", clEnv);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif // UNITY_EDITOR
|
||||
@@ -1,11 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 8bff6cadf0b8db54b87ba51b24d080f6
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -1,27 +1,38 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using UnityEditor;
|
||||
// Copyright 2026 Code Philosophy
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
using System.IO;
|
||||
using UnityEditor.Android;
|
||||
using UnityEditor.Build;
|
||||
using UnityEditor.Build.Reporting;
|
||||
using UnityEditor.Il2Cpp;
|
||||
using UnityEditor.UnityLinker;
|
||||
using UnityEngine;
|
||||
|
||||
namespace HybridCLR.Editor.BuildProcessors
|
||||
namespace HybridCLR.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
|
||||
#endif
|
||||
|
||||
#if UNITY_PS5
|
||||
, IUnityLinkerProcessor
|
||||
@@ -32,9 +43,9 @@ namespace HybridCLR.Editor.BuildProcessors
|
||||
|
||||
public void OnPostGenerateGradleAndroidProject(string path)
|
||||
{
|
||||
// 如果直接打包apk,没有机会在PostprocessBuild中修改ScriptingAssemblies.json。
|
||||
// 因此需要在这个时机处理
|
||||
// Unity有bug,偶然情况下会传入apk的路径,导致替换失败
|
||||
// When building apk directly there is no chance to patch ScriptingAssemblies.json in PostprocessBuild.
|
||||
// Therefore patch it at this stage
|
||||
// Unity bug: sometimes an apk path is passed in and replacement fails
|
||||
if (Directory.Exists(path))
|
||||
{
|
||||
PathScriptingAssembilesFile(path);
|
||||
@@ -45,18 +56,27 @@ 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
|
||||
// For Android targets this was already handled in OnPostGenerateGradleAndroidProject,
|
||||
// so skip duplicate processing here
|
||||
#if !UNITY_ANDROID && !UNITY_WEBGL && !UNITY_OPENHARMONY
|
||||
PathScriptingAssembilesFile(report.summary.outputPath);
|
||||
#endif
|
||||
}
|
||||
|
||||
#if UNITY_PS5
|
||||
/// <summary>
|
||||
/// 打包模式如果是 Package 需要在这个阶段提前处理 .json , PC Hosted 和 GP5 模式不受影响
|
||||
/// For Package build mode, patch .json at this stage; PC Hosted and GP5 modes are unaffected
|
||||
/// </summary>
|
||||
|
||||
public string GenerateAdditionalLinkXmlFile(UnityEditor.Build.Reporting.BuildReport report, UnityEditor.UnityLinker.UnityLinkerBuildPipelineData data)
|
||||
@@ -82,19 +102,21 @@ namespace HybridCLR.Editor.BuildProcessors
|
||||
AddHotFixAssembliesToScriptingAssembliesJson(path);
|
||||
}
|
||||
|
||||
private const string scriptingAssembliesJsonFile = "ScriptingAssemblies.json";
|
||||
|
||||
private void AddHotFixAssembliesToScriptingAssembliesJson(string path)
|
||||
{
|
||||
Debug.Log($"[PatchScriptingAssemblyList]. path:{path}");
|
||||
/*
|
||||
* ScriptingAssemblies.json 文件中记录了所有的dll名称,此列表在游戏启动时自动加载,
|
||||
* 不在此列表中的dll在资源反序列化时无法被找到其类型
|
||||
* 因此 OnFilterAssemblies 中移除的条目需要再加回来
|
||||
* ScriptingAssemblies.json lists all dll names that are loaded automatically at startup;
|
||||
* dlls missing from this list cannot resolve types during asset deserialization
|
||||
* therefore entries removed by OnFilterAssemblies must be added back
|
||||
*/
|
||||
string[] jsonFiles = Directory.GetFiles(path, SettingsUtil.ScriptingAssembliesJsonFile, SearchOption.AllDirectories);
|
||||
string[] jsonFiles = Directory.GetFiles(path, scriptingAssembliesJsonFile, SearchOption.AllDirectories);
|
||||
|
||||
if (jsonFiles.Length == 0)
|
||||
{
|
||||
Debug.LogWarning($"can not find file {SettingsUtil.ScriptingAssembliesJsonFile}");
|
||||
Debug.LogWarning($"can not find file {scriptingAssembliesJsonFile}");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -106,12 +128,5 @@ namespace HybridCLR.Editor.BuildProcessors
|
||||
patcher.Save(file);
|
||||
}
|
||||
}
|
||||
|
||||
#if UNITY_WEBGL
|
||||
public void OnBeforeConvertRun(BuildReport report, Il2CppBuildPipelineData data)
|
||||
{
|
||||
PathScriptingAssembilesFile($"{SettingsUtil.ProjectDir}/Temp/StagingArea/Data");
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,29 @@
|
||||
// Copyright 2026 Code Philosophy
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
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
|
||||
namespace HybridCLR.BuildProcessors
|
||||
{
|
||||
public class ScriptingAssembliesJsonPatcher
|
||||
{
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 259c1cb7fe681f74eb435ab8f268890d
|
||||
guid: ce487ea0948f9a841a034185c1d536ee
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
@@ -0,0 +1,71 @@
|
||||
// Copyright 2026 Code Philosophy
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
using dnlib.DotNet;
|
||||
using dnlib.DotNet.Writer;
|
||||
using System.IO;
|
||||
|
||||
namespace HybridCLR.CodeGen.AOT
|
||||
{
|
||||
public class AOTAssemblyMetadataStripper
|
||||
{
|
||||
public static byte[] Strip(byte[] assemblyBytes)
|
||||
{
|
||||
var context = ModuleDef.CreateModuleContext();
|
||||
var readerOption = new ModuleCreationOptions(context)
|
||||
{
|
||||
Runtime = CLRRuntimeReaderKind.Mono
|
||||
};
|
||||
var mod = ModuleDefMD.Load(assemblyBytes, readerOption);
|
||||
// remove all resources
|
||||
mod.Resources.Clear();
|
||||
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.PreserveRids;
|
||||
mod.Write(writer, options);
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
fileFormatVersion: 2
|
||||
guid: edeb86f4b5b13ca4cb0fe9d87ce509bb
|
||||
guid: 7e9e6a048682dcb4fab806251411f29f
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
+61
-41
@@ -1,16 +1,35 @@
|
||||
using HybridCLR.Editor.Meta;
|
||||
// Copyright 2026 Code Philosophy
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
|
||||
using HybridCLR.CppCodeGen;
|
||||
using HybridCLR.Meta;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading.Tasks;
|
||||
using UnityEngine;
|
||||
|
||||
namespace HybridCLR.Editor.AOT
|
||||
namespace HybridCLR.CodeGen.AOT
|
||||
{
|
||||
public class GenericReferenceWriter
|
||||
public class AOTGenericReferenceWriter
|
||||
{
|
||||
private static readonly Dictionary<Type, string> _typeNameMapping = new Dictionary<Type, string>
|
||||
{
|
||||
@@ -33,13 +52,13 @@ namespace HybridCLR.Editor.AOT
|
||||
private readonly Regex _systemTypePattern;
|
||||
private readonly Regex _genericPattern = new Regex(@"`\d+");
|
||||
|
||||
public GenericReferenceWriter()
|
||||
public AOTGenericReferenceWriter()
|
||||
{
|
||||
foreach (var e in _typeNameMapping)
|
||||
{
|
||||
_typeSimpleNameMapping.Add(e.Key.FullName, e.Value);
|
||||
}
|
||||
_systemTypePattern = new Regex(string.Join("|", _typeSimpleNameMapping.Keys.Select (k => $@"\b{k}\b")));
|
||||
_systemTypePattern = new Regex(string.Join("|", _typeSimpleNameMapping.Keys.Select(k => $@"\b{Regex.Escape(k)}\b")));
|
||||
}
|
||||
|
||||
public string PrettifyTypeSig(string typeSig)
|
||||
@@ -63,47 +82,49 @@ namespace HybridCLR.Editor.AOT
|
||||
string parentDir = Directory.GetParent(outputFile).FullName;
|
||||
Directory.CreateDirectory(parentDir);
|
||||
|
||||
List<string> codes = new List<string>();
|
||||
codes.Add("using System.Collections.Generic;");
|
||||
codes.Add("public class AOTGenericReferences : UnityEngine.MonoBehaviour");
|
||||
codes.Add("{");
|
||||
var cw = new CodeWriter();
|
||||
cw.WriteLine("using System.Collections.Generic;");
|
||||
cw.WriteLine("public class AOTGenericReferences : UnityEngine.MonoBehaviour");
|
||||
cw.WriteLine("{");
|
||||
cw.IncreaseIndent();
|
||||
|
||||
codes.Add("");
|
||||
codes.Add("\t// {{ AOT assemblies");
|
||||
codes.Add("\tpublic static readonly IReadOnlyList<string> PatchedAOTAssemblyList = new List<string>");
|
||||
codes.Add("\t{");
|
||||
cw.WriteLine();
|
||||
cw.WriteLine("// {{ AOT assemblies");
|
||||
cw.WriteLine("public static readonly IReadOnlyList<string> PatchedAOTAssemblyList = new List<string>");
|
||||
cw.WriteLine("{");
|
||||
cw.IncreaseIndent();
|
||||
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}\",");
|
||||
cw.WriteLine($"\"{module.Name}\",");
|
||||
}
|
||||
codes.Add("\t};");
|
||||
codes.Add("\t// }}");
|
||||
cw.DecreaseIndent();
|
||||
cw.WriteLine("};");
|
||||
cw.WriteLine("// }}");
|
||||
|
||||
cw.WriteLine();
|
||||
cw.WriteLine("// {{ constraint implement type");
|
||||
cw.WriteLine("// }} ");
|
||||
|
||||
codes.Add("");
|
||||
codes.Add("\t// {{ constraint implement type");
|
||||
cw.WriteLine();
|
||||
cw.WriteLine("// {{ AOT generic types");
|
||||
|
||||
codes.Add("\t// }} ");
|
||||
|
||||
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)
|
||||
foreach (var typeName in typeNames)
|
||||
{
|
||||
codes.Add($"\t// {typeName}");
|
||||
cw.WriteLine($"// {typeName}");
|
||||
}
|
||||
|
||||
codes.Add("\t// }}");
|
||||
cw.WriteLine("// }}");
|
||||
|
||||
cw.WriteLine();
|
||||
cw.WriteLine("public void RefMethods()");
|
||||
cw.WriteLine("{");
|
||||
cw.IncreaseIndent();
|
||||
|
||||
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();
|
||||
@@ -122,18 +143,17 @@ namespace HybridCLR.Editor.AOT
|
||||
}
|
||||
return String.Compare(a.Item3, b.Item3, StringComparison.Ordinal);
|
||||
});
|
||||
foreach(var method in methodTypeAndNames)
|
||||
foreach (var method in methodTypeAndNames)
|
||||
{
|
||||
codes.Add($"\t\t// {PrettifyMethodSig(method.Item3)}");
|
||||
cw.WriteLine($"// {PrettifyMethodSig(method.Item3)}");
|
||||
}
|
||||
codes.Add("\t}");
|
||||
cw.DecreaseIndent();
|
||||
cw.WriteLine("}");
|
||||
|
||||
codes.Add("}");
|
||||
cw.DecreaseIndent();
|
||||
cw.WriteLine("}");
|
||||
|
||||
|
||||
var utf8WithoutBom = new System.Text.UTF8Encoding(false);
|
||||
File.WriteAllText(outputFile, string.Join("\n", codes), utf8WithoutBom);
|
||||
Debug.Log($"[GenericReferenceWriter] write {outputFile}");
|
||||
cw.Save(outputFile);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,28 +1,49 @@
|
||||
// Copyright 2026 Code Philosophy
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
using dnlib.DotNet;
|
||||
using HybridCLR.Editor.Meta;
|
||||
using System;
|
||||
using HybridCLR.Meta;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using UnityEngine;
|
||||
|
||||
namespace HybridCLR.Editor.AOT
|
||||
namespace HybridCLR.CodeGen.AOT
|
||||
{
|
||||
|
||||
public class Analyzer
|
||||
public class AOTReferenceAnalyzer
|
||||
{
|
||||
public class Options
|
||||
{
|
||||
public AssemblyReferenceDeepCollector Collector { get; set; }
|
||||
|
||||
public int MaxIterationCount { get; set; }
|
||||
|
||||
public bool ComputeAotAssembly { get; set; }
|
||||
}
|
||||
|
||||
private readonly int _maxInterationCount;
|
||||
|
||||
private readonly AssemblyReferenceDeepCollector _assemblyCollector;
|
||||
|
||||
private readonly bool _computeAotAssembly;
|
||||
|
||||
private readonly HashSet<GenericClass> _genericTypes = new HashSet<GenericClass>();
|
||||
private readonly HashSet<GenericMethod> _genericMethods = new HashSet<GenericMethod>();
|
||||
|
||||
@@ -43,10 +64,11 @@ namespace HybridCLR.Editor.AOT
|
||||
|
||||
public List<GenericMethod> AotGenericMethods { get; } = new List<GenericMethod>();
|
||||
|
||||
public Analyzer(Options options)
|
||||
public AOTReferenceAnalyzer(Options options)
|
||||
{
|
||||
_assemblyCollector = options.Collector;
|
||||
_maxInterationCount = options.MaxIterationCount;
|
||||
_computeAotAssembly = options.ComputeAotAssembly;
|
||||
_methodReferenceAnalyzer = new MethodReferenceAnalyzer(this.OnNewMethod);
|
||||
_hotUpdateAssemblyFiles = new HashSet<string>(options.Collector.GetRootAssemblyNames().Select(assName => assName + ".dll"));
|
||||
}
|
||||
@@ -71,7 +93,7 @@ namespace HybridCLR.Editor.AOT
|
||||
|
||||
private bool IsAotType(TypeDef type)
|
||||
{
|
||||
return !_hotUpdateAssemblyFiles.Contains(type.Module.Name);
|
||||
return _computeAotAssembly || !_hotUpdateAssemblyFiles.Contains(type.Module.Name);
|
||||
}
|
||||
|
||||
private bool IsAotGenericMethod(MethodDef method)
|
||||
@@ -81,7 +103,7 @@ namespace HybridCLR.Editor.AOT
|
||||
|
||||
private void OnNewMethod(MethodDef methodDef, List<TypeSig> klassGenericInst, List<TypeSig> methodGenericInst, GenericMethod method)
|
||||
{
|
||||
if(method == null)
|
||||
if (method == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
@@ -145,8 +167,8 @@ namespace HybridCLR.Editor.AOT
|
||||
|
||||
private void Prepare()
|
||||
{
|
||||
// 将所有非泛型函数全部加入函数列表,同时立马walk这些method。
|
||||
// 后续迭代中将只遍历MethodSpec
|
||||
// Add all non-generic methods to the list and walk them immediately.
|
||||
// Later iterations only walk MethodSpec entries
|
||||
foreach (var ass in _assemblyCollector.GetLoadedModulesOfRootAssemblies())
|
||||
{
|
||||
foreach (TypeDef typeDef in ass.GetTypes())
|
||||
@@ -191,11 +213,29 @@ 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 => IsAotType(type.Type)).Select(gc => cc.ApplyConstraints(gc)));
|
||||
AotGenericMethods.AddRange(_genericMethods.Where(method => IsAotGenericMethod(method.Method)).Select(gm => cc.ApplyConstraints(gm)));
|
||||
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)));
|
||||
}
|
||||
|
||||
public void Run()
|
||||
@@ -1,12 +1,29 @@
|
||||
using dnlib.DotNet;
|
||||
using HybridCLR.Editor.Meta;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
// Copyright 2026 Code Philosophy
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
namespace HybridCLR.Editor.AOT
|
||||
using dnlib.DotNet;
|
||||
using HybridCLR.Meta;
|
||||
using HybridCLR.Utils;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace HybridCLR.CodeGen.AOT
|
||||
{
|
||||
|
||||
public class ConstraintContext
|
||||
@@ -43,7 +60,7 @@ namespace HybridCLR.Editor.AOT
|
||||
}
|
||||
|
||||
private int ComputHash()
|
||||
{
|
||||
{
|
||||
int hash = 0;
|
||||
if (BaseType != null)
|
||||
{
|
||||
@@ -0,0 +1,94 @@
|
||||
// Copyright 2026 Code Philosophy
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace HybridCLR.CppCodeGen
|
||||
{
|
||||
public class CodeWriter
|
||||
{
|
||||
private readonly List<string> _lines = new List<string>();
|
||||
|
||||
private readonly int _indentSize;
|
||||
|
||||
private readonly char _indentChar;
|
||||
|
||||
private int _indentLevel = 0;
|
||||
|
||||
private string _indent = string.Empty;
|
||||
|
||||
public CodeWriter(int indentSize = 4, char indentChar = ' ')
|
||||
{
|
||||
if (indentSize < 0)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(indentSize));
|
||||
}
|
||||
_indentSize = indentSize;
|
||||
_indentChar = indentChar;
|
||||
}
|
||||
|
||||
public int IndentLevel => _indentLevel;
|
||||
|
||||
public void IncreaseIndent()
|
||||
{
|
||||
_indentLevel++;
|
||||
_indent = new string(_indentChar, _indentLevel * _indentSize);
|
||||
}
|
||||
|
||||
public void DecreaseIndent()
|
||||
{
|
||||
if (_indentLevel <= 0)
|
||||
{
|
||||
throw new InvalidOperationException("Indent level cannot be negative");
|
||||
}
|
||||
_indentLevel--;
|
||||
_indent = _indentLevel == 0 ? string.Empty : new string(_indentChar, _indentLevel * _indentSize);
|
||||
}
|
||||
|
||||
public void ResetIndent()
|
||||
{
|
||||
_indentLevel = 0;
|
||||
_indent = string.Empty;
|
||||
}
|
||||
|
||||
public void WriteLine(string line)
|
||||
{
|
||||
_lines.Add($"{_indent}{line}");
|
||||
}
|
||||
|
||||
public void WriteLine()
|
||||
{
|
||||
_lines.Add(string.Empty);
|
||||
}
|
||||
|
||||
public string GetContent(string newLine = "\n")
|
||||
{
|
||||
return string.Join(newLine, _lines);
|
||||
}
|
||||
|
||||
public void Save(string filePath)
|
||||
{
|
||||
System.IO.File.WriteAllText(filePath, GetContent() + "\n", new UTF8Encoding(false));
|
||||
UnityEngine.Debug.Log($"write file to {filePath}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b9f06ff0612105b4ea20e0309e759e24
|
||||
guid: e721876312c6e1b4997df2e900f1d754
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
@@ -0,0 +1,99 @@
|
||||
// Copyright 2026 Code Philosophy
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
using HybridCLR.CppCodeGen;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text.RegularExpressions;
|
||||
using UnityEngine;
|
||||
|
||||
namespace HybridCLR.CodeGen.Il2CppDef
|
||||
{
|
||||
public class Il2CppDefGenerator
|
||||
{
|
||||
public class Options
|
||||
{
|
||||
public List<string> HotUpdateAssemblies { get; set; }
|
||||
|
||||
public string UnityVersionOutputFile { get; set; }
|
||||
|
||||
public string AssemblyManifestOutputFile { get; set; }
|
||||
|
||||
public string UnityVersion { get; set; }
|
||||
}
|
||||
|
||||
private readonly Options _options;
|
||||
public Il2CppDefGenerator(Options options)
|
||||
{
|
||||
_options = options;
|
||||
}
|
||||
|
||||
|
||||
private static readonly Regex s_unityVersionPat = new Regex(@"(\d+)\.(\d+)\.(\d+)");
|
||||
|
||||
public void Generate()
|
||||
{
|
||||
GenerateUnityVersionInc();
|
||||
GenerateAssemblyManifestInc();
|
||||
}
|
||||
|
||||
private void GenerateUnityVersionInc()
|
||||
{
|
||||
var cw = new CodeWriter();
|
||||
|
||||
var match = s_unityVersionPat.Matches(_options.UnityVersion)[0];
|
||||
int majorVer = int.Parse(match.Groups[1].Value);
|
||||
int minorVer1 = int.Parse(match.Groups[2].Value);
|
||||
int minorVer2 = int.Parse(match.Groups[3].Value);
|
||||
|
||||
cw.WriteLine($"#define HYBRIDCLR_UNITY_VERSION {majorVer}{minorVer1.ToString("D2")}{minorVer2.ToString("D2")}");
|
||||
|
||||
#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);
|
||||
cw.WriteLine($"#define HYBRIDCLR_TUANJIE_VERSION {tuanjieMajorVer}{tuanjieMinorVer1.ToString("D2")}{tuanjieMinorVer2.ToString("D2")}");
|
||||
#elif TUANJIE_2022_3_OR_NEWER
|
||||
cw.WriteLine($"#define HYBRIDCLR_TUANJIE_VERSION 10000");
|
||||
#endif
|
||||
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(_options.UnityVersionOutputFile));
|
||||
cw.Save(_options.UnityVersionOutputFile);
|
||||
Debug.Log($"[HybridCLR.Il2CppDef.Generator] output:{_options.UnityVersionOutputFile}");
|
||||
}
|
||||
|
||||
private void GenerateAssemblyManifestInc()
|
||||
{
|
||||
var cw = new CodeWriter();
|
||||
// Included inside g_placeHolderAssemblies initializer (4-space indent).
|
||||
cw.IncreaseIndent();
|
||||
|
||||
foreach (var ass in _options.HotUpdateAssemblies)
|
||||
{
|
||||
cw.WriteLine($"\"{ass}\",");
|
||||
}
|
||||
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(_options.AssemblyManifestOutputFile));
|
||||
cw.Save(_options.AssemblyManifestOutputFile);
|
||||
Debug.Log($"[HybridCLR.Il2CppDef.Generator] output:{_options.AssemblyManifestOutputFile}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
// Copyright 2026 Code Philosophy
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
using dnlib.DotNet;
|
||||
using HybridCLR.Mod;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
using IAssemblyResolver = HybridCLR.Mod.IAssemblyResolver;
|
||||
|
||||
namespace HybridCLR.CodeGen.Link
|
||||
{
|
||||
public class LinkAnalyzer
|
||||
{
|
||||
private readonly IAssemblyResolver _resolver;
|
||||
|
||||
public LinkAnalyzer(IAssemblyResolver resolver)
|
||||
{
|
||||
_resolver = resolver;
|
||||
}
|
||||
|
||||
public List<LinkTypePreserveInfo> CollectRefs(List<string> rootAssemblies, LinkPreserveLevel preserveLevel)
|
||||
{
|
||||
var assCollector = new AssemblyCache(_resolver);
|
||||
var rootAssemblyNames = new HashSet<string>(rootAssemblies);
|
||||
var types = new Dictionary<(string Assembly, string Type), LinkTypePreserveInfo>();
|
||||
|
||||
foreach (var rootAss in rootAssemblies)
|
||||
{
|
||||
var dnAss = assCollector.LoadModule(rootAss, false);
|
||||
CollectTypeRefs(dnAss, rootAssemblyNames, preserveLevel, types);
|
||||
if (preserveLevel == LinkPreserveLevel.PreserveExactMember)
|
||||
{
|
||||
CollectMemberRefs(dnAss, rootAssemblyNames, types);
|
||||
}
|
||||
}
|
||||
|
||||
var result = new List<LinkTypePreserveInfo>(types.Values);
|
||||
result.Sort((a, b) =>
|
||||
{
|
||||
int c = string.Compare(a.AssemblyName, b.AssemblyName, StringComparison.Ordinal);
|
||||
if (c != 0)
|
||||
{
|
||||
return c;
|
||||
}
|
||||
return string.Compare(a.TypeFullName, b.TypeFullName, StringComparison.Ordinal);
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void CollectTypeRefs(ModuleDefMD dnAss, HashSet<string> rootAssemblyNames,
|
||||
LinkPreserveLevel preserveLevel, Dictionary<(string, string), LinkTypePreserveInfo> types)
|
||||
{
|
||||
foreach (var type in dnAss.GetTypeRefs())
|
||||
{
|
||||
if (type.DefinitionAssembly == null)
|
||||
{
|
||||
Debug.LogWarning($"assembly:{dnAss.Name} TypeRef {type.FullName} has no DefinitionAssembly");
|
||||
continue;
|
||||
}
|
||||
string assName = type.DefinitionAssembly.Name.ToString();
|
||||
if (rootAssemblyNames.Contains(assName))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var info = GetOrCreateTypeInfo(types, assName, type.FullName);
|
||||
if (preserveLevel == LinkPreserveLevel.PreserveAllOfDeclaringType)
|
||||
{
|
||||
info.PreserveAll = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void CollectMemberRefs(ModuleDefMD dnAss, HashSet<string> rootAssemblyNames,
|
||||
Dictionary<(string, string), LinkTypePreserveInfo> types)
|
||||
{
|
||||
foreach (IMethodDefOrRef memberRef in dnAss.GetMemberRefs())
|
||||
{
|
||||
ITypeDefOrRef declaringType = memberRef.DeclaringType;
|
||||
if (declaringType?.DefinitionAssembly == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
string assName = declaringType.DefinitionAssembly.Name.ToString();
|
||||
if (rootAssemblyNames.Contains(assName))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
TypeSig declaringTypeSig = declaringType.ToTypeSig();
|
||||
if (declaringTypeSig != null &&
|
||||
(declaringTypeSig.ElementType == ElementType.Array || declaringTypeSig.ElementType == ElementType.SZArray))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
string typeFullName = GetLinkTypeFullName(declaringType);
|
||||
if (string.IsNullOrEmpty(typeFullName))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var info = GetOrCreateTypeInfo(types, assName, typeFullName);
|
||||
string memberName = memberRef.Name;
|
||||
|
||||
if (memberRef.IsField)
|
||||
{
|
||||
info.Fields.Add(memberName);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!memberRef.IsMethod)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (TryGetPropertyName(memberName, out string propertyName))
|
||||
{
|
||||
info.Properties.Add(propertyName);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (TryGetEventName(memberName, out string eventName))
|
||||
{
|
||||
info.Events.Add(eventName);
|
||||
continue;
|
||||
}
|
||||
|
||||
info.Methods.Add(memberName);
|
||||
}
|
||||
}
|
||||
|
||||
private static LinkTypePreserveInfo GetOrCreateTypeInfo(
|
||||
Dictionary<(string, string), LinkTypePreserveInfo> types, string assemblyName, string typeFullName)
|
||||
{
|
||||
var key = (assemblyName, typeFullName);
|
||||
if (!types.TryGetValue(key, out var info))
|
||||
{
|
||||
info = new LinkTypePreserveInfo
|
||||
{
|
||||
AssemblyName = assemblyName,
|
||||
TypeFullName = typeFullName,
|
||||
};
|
||||
types.Add(key, info);
|
||||
}
|
||||
return info;
|
||||
}
|
||||
|
||||
private static string GetLinkTypeFullName(ITypeDefOrRef type)
|
||||
{
|
||||
if (type is TypeSpec typeSpec)
|
||||
{
|
||||
if (typeSpec.TypeSig is GenericInstSig genericInst)
|
||||
{
|
||||
return genericInst.GenericType.FullName;
|
||||
}
|
||||
return typeSpec.FullName;
|
||||
}
|
||||
return type.FullName;
|
||||
}
|
||||
|
||||
private static bool TryGetPropertyName(string methodName, out string propertyName)
|
||||
{
|
||||
propertyName = null;
|
||||
// Skip explicit interface implementations (contain '.').
|
||||
if (methodName.IndexOf('.') >= 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (methodName.StartsWith("get_", StringComparison.Ordinal) && methodName.Length > 4)
|
||||
{
|
||||
propertyName = methodName.Substring(4);
|
||||
return true;
|
||||
}
|
||||
if (methodName.StartsWith("set_", StringComparison.Ordinal) && methodName.Length > 4)
|
||||
{
|
||||
propertyName = methodName.Substring(4);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool TryGetEventName(string methodName, out string eventName)
|
||||
{
|
||||
eventName = null;
|
||||
if (methodName.IndexOf('.') >= 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (methodName.StartsWith("add_", StringComparison.Ordinal) && methodName.Length > 4)
|
||||
{
|
||||
eventName = methodName.Substring(4);
|
||||
return true;
|
||||
}
|
||||
if (methodName.StartsWith("remove_", StringComparison.Ordinal) && methodName.Length > 7)
|
||||
{
|
||||
eventName = methodName.Substring(7);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// Copyright 2026 Code Philosophy
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
namespace HybridCLR.CodeGen.Link
|
||||
{
|
||||
/// <summary>
|
||||
/// Preserve level used when generating link.xml from hot update assembly references.
|
||||
/// </summary>
|
||||
public enum LinkPreserveLevel
|
||||
{
|
||||
/// <summary>
|
||||
/// Preserve the entire declaring type of each referenced type.
|
||||
/// Safer against future member usage, but may increase build size.
|
||||
/// </summary>
|
||||
PreserveAllOfDeclaringType = 0,
|
||||
|
||||
/// <summary>
|
||||
/// Preserve only the exact members referenced by hot update code
|
||||
/// (fields, methods, properties, events).
|
||||
/// </summary>
|
||||
PreserveExactMember = 1,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 6c7a2b75b4c05e13ab1128274336e1d5
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,43 @@
|
||||
// Copyright 2026 Code Philosophy
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace HybridCLR.CodeGen.Link
|
||||
{
|
||||
public class LinkTypePreserveInfo
|
||||
{
|
||||
public string AssemblyName { get; set; }
|
||||
|
||||
public string TypeFullName { get; set; }
|
||||
|
||||
public bool PreserveAll { get; set; }
|
||||
|
||||
public SortedSet<string> Fields { get; } = new SortedSet<string>(System.StringComparer.Ordinal);
|
||||
|
||||
public SortedSet<string> Methods { get; } = new SortedSet<string>(System.StringComparer.Ordinal);
|
||||
|
||||
public SortedSet<string> Properties { get; } = new SortedSet<string>(System.StringComparer.Ordinal);
|
||||
|
||||
public SortedSet<string> Events { get; } = new SortedSet<string>(System.StringComparer.Ordinal);
|
||||
|
||||
public bool HasExactMembers => Fields.Count > 0 || Methods.Count > 0 || Properties.Count > 0 || Events.Count > 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 03cdedb09fc930d2f1d79689f124f68c
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,109 @@
|
||||
// Copyright 2026 Code Philosophy
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
using HybridCLR.CppCodeGen;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
|
||||
namespace HybridCLR.CodeGen.Link
|
||||
{
|
||||
public class LinkXmlWriter
|
||||
{
|
||||
public void Write(string outputLinkXmlFile, List<LinkTypePreserveInfo> preserveTypes)
|
||||
{
|
||||
string parentDir = Directory.GetParent(outputLinkXmlFile).FullName;
|
||||
Directory.CreateDirectory(parentDir);
|
||||
|
||||
var cw = new CodeWriter(2);
|
||||
cw.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
|
||||
cw.WriteLine("<linker>");
|
||||
cw.IncreaseIndent();
|
||||
|
||||
var typesByAssembly = preserveTypes.GroupBy(t => t.AssemblyName).ToList();
|
||||
typesByAssembly.Sort((a, b) => String.Compare(a.Key, b.Key, StringComparison.Ordinal));
|
||||
|
||||
foreach (var assembly in typesByAssembly)
|
||||
{
|
||||
cw.WriteLine($"<assembly fullname=\"{assembly.Key}\">");
|
||||
cw.IncreaseIndent();
|
||||
|
||||
List<LinkTypePreserveInfo> assTypes = assembly.ToList();
|
||||
assTypes.Sort((a, b) => string.CompareOrdinal(a.TypeFullName, b.TypeFullName));
|
||||
foreach (var typeInfo in assTypes)
|
||||
{
|
||||
#if UNITY_2023_1_OR_NEWER
|
||||
// if preserve all of 'UnityEngine.Debug' type, unity will build failed on iOS platform because missing some icalls.
|
||||
// this is a known issue of Unity.
|
||||
if (typeInfo.TypeFullName == "UnityEngine.Debug")
|
||||
{
|
||||
continue;
|
||||
}
|
||||
#endif
|
||||
WriteType(cw, typeInfo);
|
||||
}
|
||||
|
||||
cw.DecreaseIndent();
|
||||
cw.WriteLine("</assembly>");
|
||||
}
|
||||
|
||||
cw.DecreaseIndent();
|
||||
cw.WriteLine("</linker>");
|
||||
cw.Save(outputLinkXmlFile);
|
||||
}
|
||||
|
||||
private static void WriteType(CodeWriter cw, LinkTypePreserveInfo typeInfo)
|
||||
{
|
||||
if (typeInfo.PreserveAll)
|
||||
{
|
||||
cw.WriteLine($"<type fullname=\"{typeInfo.TypeFullName}\" preserve=\"all\" />");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!typeInfo.HasExactMembers)
|
||||
{
|
||||
cw.WriteLine($"<type fullname=\"{typeInfo.TypeFullName}\" />");
|
||||
return;
|
||||
}
|
||||
|
||||
cw.WriteLine($"<type fullname=\"{typeInfo.TypeFullName}\">");
|
||||
cw.IncreaseIndent();
|
||||
foreach (var field in typeInfo.Fields)
|
||||
{
|
||||
cw.WriteLine($"<field name=\"{field}\" />");
|
||||
}
|
||||
foreach (var method in typeInfo.Methods)
|
||||
{
|
||||
cw.WriteLine($"<method name=\"{method}\" />");
|
||||
}
|
||||
foreach (var property in typeInfo.Properties)
|
||||
{
|
||||
cw.WriteLine($"<property name=\"{property}\" />");
|
||||
}
|
||||
foreach (var evt in typeInfo.Events)
|
||||
{
|
||||
cw.WriteLine($"<event name=\"{evt}\" />");
|
||||
}
|
||||
cw.DecreaseIndent();
|
||||
cw.WriteLine("</type>");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
// Copyright 2026 Code Philosophy
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
using dnlib.DotNet;
|
||||
|
||||
namespace HybridCLR.CodeGen.MethodBridge
|
||||
{
|
||||
public class CallNativeMethodSignatureInfo
|
||||
{
|
||||
public MethodSig MethodSig { get; set; }
|
||||
|
||||
public CallingConvention? Callvention { get; set; }
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b7af32bdf1cf55c42bfc449820d401cb
|
||||
guid: d2e4ca0a49975a84a8a72dbc70ec7795
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
@@ -0,0 +1,81 @@
|
||||
// Copyright 2026 Code Philosophy
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
using dnlib.DotNet;
|
||||
using HybridCLR.Mod;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace HybridCLR.CodeGen.MethodBridge
|
||||
{
|
||||
|
||||
public class CalliAnalyzer
|
||||
{
|
||||
private readonly List<ModuleDefMD> _rootModules = new List<ModuleDefMD>();
|
||||
|
||||
private readonly List<CallNativeMethodSignatureInfo> _calliMethodSignatures = new List<CallNativeMethodSignatureInfo>();
|
||||
|
||||
public List<CallNativeMethodSignatureInfo> 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 CallNativeMethodSignatureInfo()
|
||||
{
|
||||
MethodSig = methodSig,
|
||||
});
|
||||
Debug.Log($"method:{method} calli method signature:{methodSig}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Run()
|
||||
{
|
||||
CollectCalli();
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 61948fcb1bc40ba47b8c10b0ae801ebb
|
||||
guid: 6ce33c8e48da5a649b261ba3a60fd3b9
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
File diff suppressed because it is too large
Load Diff
+32
-12
@@ -1,16 +1,36 @@
|
||||
// Copyright 2026 Code Philosophy
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
using dnlib.DotNet;
|
||||
using HybridCLR.Editor.Meta;
|
||||
using System;
|
||||
using HybridCLR.Meta;
|
||||
|
||||
using HybridCLR.Utils;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using UnityEngine;
|
||||
|
||||
namespace HybridCLR.Editor.MethodBridge
|
||||
namespace HybridCLR.CodeGen.MethodBridge
|
||||
{
|
||||
|
||||
public class Analyzer
|
||||
public class MethodBridgeAnalyzer
|
||||
{
|
||||
public class Options
|
||||
{
|
||||
@@ -41,7 +61,7 @@ namespace HybridCLR.Editor.MethodBridge
|
||||
|
||||
private readonly MethodReferenceAnalyzer _methodReferenceAnalyzer;
|
||||
|
||||
public Analyzer(Options options)
|
||||
public MethodBridgeAnalyzer(Options options)
|
||||
{
|
||||
_maxInterationCount = options.MaxIterationCount;
|
||||
_assemblyCollector = options.Collector;
|
||||
@@ -54,7 +74,7 @@ namespace HybridCLR.Editor.MethodBridge
|
||||
{
|
||||
return;
|
||||
}
|
||||
lock(_lock)
|
||||
lock (_lock)
|
||||
{
|
||||
gc = StandardizeClass(gc);
|
||||
if (_genericTypes.Add(gc))
|
||||
@@ -83,7 +103,7 @@ namespace HybridCLR.Editor.MethodBridge
|
||||
|
||||
private void OnNewMethod(MethodDef methodDef, List<TypeSig> klassGenericInst, List<TypeSig> methodGenericInst, GenericMethod method)
|
||||
{
|
||||
lock(_lock)
|
||||
lock (_lock)
|
||||
{
|
||||
method = StandardizeMethod(method);
|
||||
if (_genericMethods.Add(method))
|
||||
@@ -111,7 +131,7 @@ namespace HybridCLR.Editor.MethodBridge
|
||||
{
|
||||
var gm = StandardizeMethod(new GenericMethod(method, gc.KlassInst, null));
|
||||
//Debug.Log($"add method:{gm.Method} {gm.KlassInst}");
|
||||
|
||||
|
||||
if (_genericMethods.Add(gm))
|
||||
{
|
||||
if (method.HasBody && method.Body.Instructions != null)
|
||||
@@ -133,7 +153,7 @@ namespace HybridCLR.Editor.MethodBridge
|
||||
}
|
||||
foreach (var method in typeDef.Methods)
|
||||
{
|
||||
// 对于带泛型的参数,统一泛型共享为object
|
||||
// Share generic parameters as object
|
||||
var gm = StandardizeMethod(new GenericMethod(method, null, null));
|
||||
_genericMethods.Add(gm);
|
||||
}
|
||||
@@ -141,8 +161,8 @@ namespace HybridCLR.Editor.MethodBridge
|
||||
|
||||
private void Prepare()
|
||||
{
|
||||
// 将所有非泛型函数全部加入函数列表,同时立马walk这些method。
|
||||
// 后续迭代中将只遍历MethodSpec
|
||||
// Add all non-generic methods to the list and walk them immediately.
|
||||
// Later iterations only walk MethodSpec entries
|
||||
foreach (var ass in _assemblyCollector.GetLoadedModules())
|
||||
{
|
||||
foreach (TypeDef typeDef in ass.GetTypes())
|
||||
@@ -0,0 +1,94 @@
|
||||
// Copyright 2026 Code Philosophy
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
using dnlib.DotNet;
|
||||
using HybridCLR.Mod;
|
||||
using HybridCLR.Utils;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using UnityEngine;
|
||||
|
||||
namespace HybridCLR.CodeGen.MethodBridge
|
||||
{
|
||||
public class RawMonoPInvokeCallbackMethodInfo
|
||||
{
|
||||
public MethodDef Method { get; set; }
|
||||
|
||||
public CustomAttribute GenerationAttribute { get; set; }
|
||||
}
|
||||
|
||||
public class MonoPInvokeCallbackAnalyzer
|
||||
{
|
||||
|
||||
private readonly List<ModuleDefMD> _rootModules = new List<ModuleDefMD>();
|
||||
|
||||
private readonly List<RawMonoPInvokeCallbackMethodInfo> _reversePInvokeMethods = new List<RawMonoPInvokeCallbackMethodInfo>();
|
||||
|
||||
public List<RawMonoPInvokeCallbackMethodInfo> ReversePInvokeMethods => _reversePInvokeMethods;
|
||||
|
||||
public MonoPInvokeCallbackAnalyzer(AssemblyCache cache, List<string> assemblyNames)
|
||||
{
|
||||
foreach (var assemblyName in assemblyNames)
|
||||
{
|
||||
_rootModules.Add(cache.LoadModule(assemblyName));
|
||||
}
|
||||
}
|
||||
|
||||
private void CollectReversePInvokeMethods()
|
||||
{
|
||||
foreach (var mod in _rootModules)
|
||||
{
|
||||
Debug.Log($"ass:{mod.FullName} method count:{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.IsStatic || !method.HasCustomAttributes)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
CustomAttribute wa = method.CustomAttributes.FirstOrDefault(ca => ca.AttributeType.Name == "MonoPInvokeCallbackAttribute");
|
||||
if (wa == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if (!MetaUtil.IsSupportedPInvokeMethodSignature(method.MethodSig))
|
||||
{
|
||||
Debug.LogError($"MonoPInvokeCallback method {method.FullName} has unsupported parameter or return type. Please check the method signature.");
|
||||
}
|
||||
//foreach (var ca in method.CustomAttributes)
|
||||
//{
|
||||
// Debug.Log($"{ca.AttributeType.FullName} {ca.TypeFullName}");
|
||||
//}
|
||||
_reversePInvokeMethods.Add(new RawMonoPInvokeCallbackMethodInfo()
|
||||
{
|
||||
Method = method,
|
||||
GenerationAttribute = method.CustomAttributes.FirstOrDefault(ca => ca.AttributeType.FullName == "HybridCLR.ReversePInvokeWrapperGenerationAttribute"),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Run()
|
||||
{
|
||||
CollectReversePInvokeMethods();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,36 @@
|
||||
using HybridCLR.Editor.AOT;
|
||||
using HybridCLR.Editor.Meta;
|
||||
// Copyright 2026 Code Philosophy
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
using HybridCLR.CodeGen.AOT;
|
||||
using HybridCLR.Meta;
|
||||
|
||||
using HybridCLR.Utils;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
|
||||
namespace HybridCLR.Editor.Commands
|
||||
namespace HybridCLR.Commands
|
||||
{
|
||||
using Analyzer = HybridCLR.Editor.AOT.Analyzer;
|
||||
public static class AOTReferenceGeneratorCommand
|
||||
{
|
||||
|
||||
@@ -22,25 +42,102 @@ namespace HybridCLR.Editor.Commands
|
||||
GenerateAOTGenericReference(target);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Calculate generic references in hot update code
|
||||
/// </summary>
|
||||
/// <param name="target"></param>
|
||||
public static void GenerateAOTGenericReference(BuildTarget target)
|
||||
{
|
||||
var gs = SettingsUtil.HybridCLRSettings;
|
||||
List<string> hotUpdateDllNames = SettingsUtil.HotUpdateAssemblyNamesExcludePreserved;
|
||||
|
||||
using (AssemblyReferenceDeepCollector collector = new AssemblyReferenceDeepCollector(MetaUtil.CreateHotUpdateAndAOTAssemblyResolver(target, hotUpdateDllNames), hotUpdateDllNames))
|
||||
AssemblyReferenceDeepCollector collector = new AssemblyReferenceDeepCollector(MetaUtil.CreateHotUpdateAndAOTAssemblyResolver(target, hotUpdateDllNames), hotUpdateDllNames);
|
||||
var analyzer = new AOTReferenceAnalyzer(new AOTReferenceAnalyzer.Options
|
||||
{
|
||||
var analyzer = new Analyzer(new Analyzer.Options
|
||||
{
|
||||
MaxIterationCount = Math.Min(20, gs.maxGenericReferenceIteration),
|
||||
Collector = collector,
|
||||
});
|
||||
MaxIterationCount = Math.Min(20, gs.maxGenericReferenceIteration),
|
||||
Collector = collector,
|
||||
});
|
||||
|
||||
analyzer.Run();
|
||||
analyzer.Run();
|
||||
|
||||
var writer = new GenericReferenceWriter();
|
||||
writer.Write(analyzer.AotGenericTypes.ToList(), analyzer.AotGenericMethods.ToList(), $"{Application.dataPath}/{gs.outputAOTGenericReferenceFile}");
|
||||
AssetDatabase.Refresh();
|
||||
var writer = new AOTGenericReferenceWriter();
|
||||
writer.Write(analyzer.AotGenericTypes.ToList(), analyzer.AotGenericMethods.ToList(), $"{Application.dataPath}/{gs.outputAOTGenericReferenceFile}");
|
||||
AssetDatabase.Refresh();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Calculate generic references in hot update code, but exclude existing generic references in AOT
|
||||
/// </summary>
|
||||
/// <param name="target"></param>
|
||||
///
|
||||
public static void GeneratedAOTGenericReferenceExcludeExistsAOTClassAndMethods(BuildTarget target)
|
||||
{
|
||||
|
||||
var gs = SettingsUtil.HybridCLRSettings;
|
||||
List<string> hotUpdateDllNames = SettingsUtil.HotUpdateAssemblyNamesExcludePreserved;
|
||||
|
||||
AssemblyReferenceDeepCollector hotUpdateCollector = new AssemblyReferenceDeepCollector(MetaUtil.CreateHotUpdateAndAOTAssemblyResolver(target, hotUpdateDllNames), hotUpdateDllNames);
|
||||
var hotUpdateAnalyzer = new AOTReferenceAnalyzer(new AOTReferenceAnalyzer.Options
|
||||
{
|
||||
MaxIterationCount = Math.Min(10, gs.maxGenericReferenceIteration),
|
||||
Collector = hotUpdateCollector,
|
||||
});
|
||||
|
||||
hotUpdateAnalyzer.Run();
|
||||
|
||||
|
||||
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/AOTGenericReference`");
|
||||
}
|
||||
AssemblyReferenceDeepCollector aotCollector = new AssemblyReferenceDeepCollector(MetaUtil.CreateAOTAssemblyResolver(target), aotAssemblyNames);
|
||||
var aotAnalyzer = new AOTReferenceAnalyzer(new AOTReferenceAnalyzer.Options
|
||||
{
|
||||
MaxIterationCount = Math.Min(10, gs.maxGenericReferenceIteration),
|
||||
Collector = aotCollector,
|
||||
ComputeAotAssembly = true,
|
||||
});
|
||||
|
||||
aotAnalyzer.Run();
|
||||
|
||||
var (resultTypes, resultMethods) = ExcludeExistAOTGenericTypeAndMethodss(hotUpdateAnalyzer.AotGenericTypes.ToList(), hotUpdateAnalyzer.AotGenericMethods.ToList(), aotAnalyzer.AotGenericTypes.ToList(), aotAnalyzer.AotGenericMethods.ToList());
|
||||
var writer = new AOTGenericReferenceWriter();
|
||||
writer.Write(resultTypes, resultMethods, $"{Application.dataPath}/{gs.outputAOTGenericReferenceFile}");
|
||||
AssetDatabase.Refresh();
|
||||
}
|
||||
|
||||
|
||||
private static (List<GenericClass>, List<GenericMethod>) ExcludeExistAOTGenericTypeAndMethodss(List<GenericClass> hotUpdateTypes, List<GenericMethod> hotUpdateMethods, List<GenericClass> aotTypes, List<GenericMethod> aotMethods)
|
||||
{
|
||||
var types = new List<GenericClass>();
|
||||
|
||||
var typeSig2Type = hotUpdateTypes.ToDictionary(t => t.Type.DefinitionAssembly.Name + ":" + t.ToTypeSig(), t => t);
|
||||
foreach (var t in aotTypes)
|
||||
{
|
||||
string key = t.Type.DefinitionAssembly.Name + ":" + t.ToTypeSig();
|
||||
if (typeSig2Type.TryGetValue(key, out var removedType))
|
||||
{
|
||||
typeSig2Type.Remove(key);
|
||||
Debug.Log($"remove AOT type:{removedType.ToTypeSig()} ");
|
||||
}
|
||||
}
|
||||
|
||||
var methodSig2Method = hotUpdateMethods.ToDictionary(m => m.Method.DeclaringType.DefinitionAssembly.Name + ":" + m.ToMethodSpec().ToString(), m => m);
|
||||
foreach (var m in aotMethods)
|
||||
{
|
||||
string key = m.Method.DeclaringType.DefinitionAssembly.Name + ":" + m.ToMethodSpec().ToString();
|
||||
if (methodSig2Method.TryGetValue(key, out var removedMethod))
|
||||
{
|
||||
methodSig2Method.Remove(key);
|
||||
Debug.Log($"remove AOT method:{removedMethod.ToMethodSpec()} ");
|
||||
}
|
||||
}
|
||||
|
||||
return (typeSig2Type.Values.ToList(), methodSig2Method.Values.ToList());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,14 +1,29 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
// Copyright 2026 Code Philosophy
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
using System.IO;
|
||||
using UnityEditor;
|
||||
using UnityEditor.Build.Player;
|
||||
using UnityEngine;
|
||||
|
||||
namespace HybridCLR.Editor.Commands
|
||||
namespace HybridCLR.Commands
|
||||
{
|
||||
public class CompileDllCommand
|
||||
{
|
||||
@@ -25,10 +40,15 @@ namespace HybridCLR.Editor.Commands
|
||||
#if UNITY_2022
|
||||
UnityEditor.EditorUtility.ClearProgressBar();
|
||||
#endif
|
||||
Debug.Log("compile finish!!!");
|
||||
Debug.Log($"compile finish!!! buildDir:{buildDir} target:{target} development:{developmentBuild}");
|
||||
}
|
||||
|
||||
public static void CompileDll(BuildTarget target, bool developmentBuild = false)
|
||||
public static void CompileDll(BuildTarget target)
|
||||
{
|
||||
CompileDll(target, EditorUserBuildSettings.development);
|
||||
}
|
||||
|
||||
public static void CompileDll(BuildTarget target, bool developmentBuild)
|
||||
{
|
||||
CompileDll(SettingsUtil.GetHotUpdateDllsOutputDirByTarget(target), target, developmentBuild);
|
||||
}
|
||||
@@ -36,10 +56,16 @@ namespace HybridCLR.Editor.Commands
|
||||
[MenuItem("HybridCLR/CompileDll/ActiveBuildTarget", priority = 100)]
|
||||
public static void CompileDllActiveBuildTarget()
|
||||
{
|
||||
CompileDll(EditorUserBuildSettings.activeBuildTarget);
|
||||
CompileDll(EditorUserBuildSettings.activeBuildTarget, EditorUserBuildSettings.development);
|
||||
}
|
||||
|
||||
[MenuItem("HybridCLR/CompileDll/ActiveBuildTarget_Development", priority = 101)]
|
||||
[MenuItem("HybridCLR/CompileDll/ActiveBuildTarget_Release", priority = 102)]
|
||||
public static void CompileDllActiveBuildTargetRelease()
|
||||
{
|
||||
CompileDll(EditorUserBuildSettings.activeBuildTarget, false);
|
||||
}
|
||||
|
||||
[MenuItem("HybridCLR/CompileDll/ActiveBuildTarget_Development", priority = 104)]
|
||||
public static void CompileDllActiveBuildTargetDevelopment()
|
||||
{
|
||||
CompileDll(EditorUserBuildSettings.activeBuildTarget, true);
|
||||
|
||||
@@ -1,12 +1,28 @@
|
||||
using HybridCLR.Editor.Link;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
// Copyright 2026 Code Philosophy
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
using HybridCLR.CodeGen.Il2CppDef;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
|
||||
namespace HybridCLR.Editor.Commands
|
||||
namespace HybridCLR.Commands
|
||||
{
|
||||
|
||||
public static class Il2CppDefGeneratorCommand
|
||||
@@ -15,15 +31,15 @@ namespace HybridCLR.Editor.Commands
|
||||
[MenuItem("HybridCLR/Generate/Il2CppDef", priority = 104)]
|
||||
public static void GenerateIl2CppDef()
|
||||
{
|
||||
var options = new Il2CppDef.Il2CppDefGenerator.Options()
|
||||
var options = new Il2CppDefGenerator.Options()
|
||||
{
|
||||
UnityVersion = Application.unityVersion,
|
||||
HotUpdateAssemblies = SettingsUtil.HotUpdateAssemblyNamesIncludePreserved,
|
||||
OutputFile = $"{SettingsUtil.LocalIl2CppDir}/libil2cpp/hybridclr/generated/UnityVersion.h",
|
||||
OutputFile2 = $"{SettingsUtil.LocalIl2CppDir}/libil2cpp/hybridclr/generated/AssemblyManifest.cpp",
|
||||
UnityVersionOutputFile = $"{SettingsUtil.GeneratedCppDir}/UnityVersion.inc",
|
||||
AssemblyManifestOutputFile = $"{SettingsUtil.GeneratedCppDir}/AssemblyManifest.inc",
|
||||
};
|
||||
|
||||
var g = new Il2CppDef.Il2CppDefGenerator(options);
|
||||
var g = new Il2CppDefGenerator(options);
|
||||
g.Generate();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,32 @@
|
||||
using HybridCLR.Editor.Link;
|
||||
using HybridCLR.Editor.Meta;
|
||||
using System;
|
||||
// Copyright 2026 Code Philosophy
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
|
||||
using HybridCLR.CodeGen.Link;
|
||||
using HybridCLR.Utils;
|
||||
using System.Collections.Generic;
|
||||
using System.Reflection;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
|
||||
namespace HybridCLR.Editor.Commands
|
||||
namespace HybridCLR.Commands
|
||||
{
|
||||
using Analyzer = HybridCLR.Editor.Link.Analyzer;
|
||||
|
||||
public static class LinkGeneratorCommand
|
||||
{
|
||||
|
||||
@@ -27,12 +44,12 @@ namespace HybridCLR.Editor.Commands
|
||||
|
||||
List<string> hotfixAssemblies = SettingsUtil.HotUpdateAssemblyNamesExcludePreserved;
|
||||
|
||||
var analyzer = new Analyzer(MetaUtil.CreateHotUpdateAndAOTAssemblyResolver(target, hotfixAssemblies));
|
||||
var refTypes = analyzer.CollectRefs(hotfixAssemblies);
|
||||
var analyzer = new LinkAnalyzer(MetaUtil.CreateHotUpdateAndAOTAssemblyResolver(target, hotfixAssemblies));
|
||||
var preserveTypes = analyzer.CollectRefs(hotfixAssemblies, ls.linkPreserveLevel);
|
||||
|
||||
Debug.Log($"[LinkGeneratorCommand] hotfix assembly count:{hotfixAssemblies.Count}, ref type count:{refTypes.Count} output:{Application.dataPath}/{ls.outputLinkFile}");
|
||||
Debug.Log($"[LinkGeneratorCommand] hotfix assembly count:{hotfixAssemblies.Count}, preserve level:{ls.linkPreserveLevel}, type count:{preserveTypes.Count} output:{Application.dataPath}/{ls.outputLinkFile}");
|
||||
var linkXmlWriter = new LinkXmlWriter();
|
||||
linkXmlWriter.Write($"{Application.dataPath}/{ls.outputLinkFile}", refTypes);
|
||||
linkXmlWriter.Write($"{Application.dataPath}/{ls.outputLinkFile}", preserveTypes);
|
||||
AssetDatabase.Refresh();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,58 +1,61 @@
|
||||
using HybridCLR.Editor;
|
||||
using HybridCLR.Editor.ABI;
|
||||
using HybridCLR.Editor.Meta;
|
||||
using HybridCLR.Editor.MethodBridge;
|
||||
// Copyright 2026 Code Philosophy
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
using HybridCLR.Meta;
|
||||
using HybridCLR.CodeGen.MethodBridge;
|
||||
using HybridCLR.Mod;
|
||||
using HybridCLR.Utils;
|
||||
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 UnityEditor.Build;
|
||||
using UnityEngine;
|
||||
|
||||
namespace HybridCLR.Editor.Commands
|
||||
namespace HybridCLR.Commands
|
||||
{
|
||||
using Analyzer = HybridCLR.Editor.MethodBridge.Analyzer;
|
||||
public class MethodBridgeGeneratorCommand
|
||||
{
|
||||
|
||||
public static void CleanIl2CppBuildCache()
|
||||
public static void GenerateMethodBridgeCppFile(IReadOnlyCollection<GenericMethod> genericMethods, List<RawMonoPInvokeCallbackMethodInfo> reversePInvokeMethods, IReadOnlyCollection<CallNativeMethodSignatureInfo> calliMethodSignatures, string outputFile)
|
||||
{
|
||||
string il2cppBuildCachePath = SettingsUtil.Il2CppBuildCacheDir;
|
||||
if (!Directory.Exists(il2cppBuildCachePath))
|
||||
{
|
||||
return;
|
||||
}
|
||||
Debug.Log($"clean il2cpp build cache:{il2cppBuildCachePath}");
|
||||
Directory.Delete(il2cppBuildCachePath, true);
|
||||
}
|
||||
|
||||
private static void GenerateMethodBridgeCppFile(Analyzer analyzer, string outputFile)
|
||||
{
|
||||
string templateCode = File.ReadAllText(outputFile, Encoding.UTF8);
|
||||
var g = new Generator(new Generator.Options()
|
||||
{
|
||||
TemplateCode = templateCode,
|
||||
OutputFile = outputFile,
|
||||
GenericMethods = analyzer.GenericMethods,
|
||||
GenericMethods = genericMethods,
|
||||
ReversePInvokeMethods = reversePInvokeMethods,
|
||||
CalliMethodSignatures = calliMethodSignatures,
|
||||
Development = EditorUserBuildSettings.development,
|
||||
});
|
||||
|
||||
g.PrepareMethods();
|
||||
g.Generate();
|
||||
Debug.LogFormat("[MethodBridgeGeneratorCommand] output:{0}", outputFile);
|
||||
}
|
||||
|
||||
[MenuItem("HybridCLR/Generate/MethodBridge", priority = 101)]
|
||||
public static void CompileAndGenerateMethodBridge()
|
||||
[MenuItem("HybridCLR/Generate/MethodBridgeAndReversePInvokeWrapper", priority = 101)]
|
||||
public static void GenerateMethodBridgeAndReversePInvokeWrapper()
|
||||
{
|
||||
BuildTarget target = EditorUserBuildSettings.activeBuildTarget;
|
||||
GenerateMethodBridge(target);
|
||||
GenerateMethodBridgeAndReversePInvokeWrapper(target);
|
||||
}
|
||||
|
||||
public static void GenerateMethodBridge(BuildTarget target)
|
||||
public static void GenerateMethodBridgeAndReversePInvokeWrapper(BuildTarget target)
|
||||
{
|
||||
string aotDllDir = SettingsUtil.GetAssembliesPostIl2CppStripDir(target);
|
||||
List<string> aotAssemblyNames = Directory.Exists(aotDllDir) ?
|
||||
@@ -62,20 +65,29 @@ namespace HybridCLR.Editor.Commands
|
||||
{
|
||||
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))
|
||||
AssemblyReferenceDeepCollector collector = new AssemblyReferenceDeepCollector(MetaUtil.CreateAOTAssemblyResolver(target), aotAssemblyNames);
|
||||
|
||||
var methodBridgeAnalyzer = new MethodBridgeAnalyzer(new MethodBridgeAnalyzer.Options
|
||||
{
|
||||
var analyzer = new Analyzer(new Analyzer.Options
|
||||
{
|
||||
MaxIterationCount = Math.Min(20, SettingsUtil.HybridCLRSettings.maxMethodBridgeGenericIteration),
|
||||
Collector = collector,
|
||||
});
|
||||
MaxIterationCount = Math.Min(20, SettingsUtil.HybridCLRSettings.maxMethodBridgeGenericIteration),
|
||||
Collector = collector,
|
||||
});
|
||||
|
||||
analyzer.Run();
|
||||
string outputFile = $"{SettingsUtil.GeneratedCppDir}/MethodBridge.cpp";
|
||||
GenerateMethodBridgeCppFile(analyzer, outputFile);
|
||||
}
|
||||
methodBridgeAnalyzer.Run();
|
||||
|
||||
CleanIl2CppBuildCache();
|
||||
List<string> hotUpdateDlls = SettingsUtil.HotUpdateAssemblyNamesExcludePreserved;
|
||||
var cache = new AssemblyCache(MetaUtil.CreateHotUpdateAndAOTAssemblyResolver(target, hotUpdateDlls));
|
||||
|
||||
var reversePInvokeAnalyzer = new MonoPInvokeCallbackAnalyzer(cache, hotUpdateDlls);
|
||||
reversePInvokeAnalyzer.Run();
|
||||
|
||||
var calliAnalyzer = new CalliAnalyzer(cache, hotUpdateDlls);
|
||||
calliAnalyzer.Run();
|
||||
|
||||
string outputFile = $"{SettingsUtil.GeneratedCppDir}/MethodBridge.inc";
|
||||
|
||||
var callNativeMethodSignatures = calliAnalyzer.CalliMethodSignatures.ToList();
|
||||
GenerateMethodBridgeCppFile(methodBridgeAnalyzer.GenericMethods, reversePInvokeAnalyzer.ReversePInvokeMethods, callNativeMethodSignatures, outputFile);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,33 +1,53 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using UnityEditor;
|
||||
// Copyright 2026 Code Philosophy
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
namespace HybridCLR.Editor.Commands
|
||||
using UnityEditor;
|
||||
using UnityEditor.Build;
|
||||
|
||||
namespace HybridCLR.Commands
|
||||
{
|
||||
public static class PrebuildCommand
|
||||
{
|
||||
/// <summary>
|
||||
/// 按照必要的顺序,执行所有生成操作,适合打包前操作
|
||||
/// Execute all generation operations in the necessary order, suitable for pre-build operations
|
||||
/// </summary>
|
||||
[MenuItem("HybridCLR/Generate/All", priority = 200)]
|
||||
public static void GenerateAll()
|
||||
{
|
||||
var installer = new Installer.InstallerController();
|
||||
if (!installer.HasInstalledHybridCLR())
|
||||
{
|
||||
throw new BuildFailedException($"You have not initialized HybridCLR, please install it via menu 'HybridCLR/Installer'");
|
||||
}
|
||||
BuildTarget target = EditorUserBuildSettings.activeBuildTarget;
|
||||
CompileDllCommand.CompileDll(target);
|
||||
CompileDllCommand.CompileDll(target, EditorUserBuildSettings.development);
|
||||
Il2CppDefGeneratorCommand.GenerateIl2CppDef();
|
||||
|
||||
// 这几个生成依赖HotUpdateDlls
|
||||
// These generation depend on HotUpdateDlls
|
||||
LinkGeneratorCommand.GenerateLinkXml(target);
|
||||
|
||||
// 生成裁剪后的aot dll
|
||||
// Generate stripped aot dll
|
||||
StripAOTDllCommand.GenerateStripedAOTDlls(target);
|
||||
|
||||
// 桥接函数生成依赖于AOT dll,必须保证已经build过,生成AOT dll
|
||||
MethodBridgeGeneratorCommand.GenerateMethodBridge(target);
|
||||
ReversePInvokeWrapperGeneratorCommand.GenerateReversePInvokeWrapper(target);
|
||||
// Method bridge generation depends on AOT dll, must be built before generating AOT dll
|
||||
MethodBridgeGeneratorCommand.GenerateMethodBridgeAndReversePInvokeWrapper(target);
|
||||
AOTReferenceGeneratorCommand.GenerateAOTGenericReference(target);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
using HybridCLR.Editor.ABI;
|
||||
using HybridCLR.Editor.Link;
|
||||
using HybridCLR.Editor.Meta;
|
||||
using HybridCLR.Editor.ReversePInvokeWrap;
|
||||
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;
|
||||
|
||||
namespace HybridCLR.Editor.Commands
|
||||
{
|
||||
|
||||
public static class ReversePInvokeWrapperGeneratorCommand
|
||||
{
|
||||
|
||||
[MenuItem("HybridCLR/Generate/ReversePInvokeWrapper", priority = 103)]
|
||||
|
||||
public static void CompileAndGenerateReversePInvokeWrapper()
|
||||
{
|
||||
BuildTarget target = EditorUserBuildSettings.activeBuildTarget;
|
||||
CompileDllCommand.CompileDll(target);
|
||||
GenerateReversePInvokeWrapper(target);
|
||||
}
|
||||
|
||||
public static void GenerateReversePInvokeWrapper(BuildTarget target)
|
||||
{
|
||||
List<string> hotUpdateDlls = SettingsUtil.HotUpdateAssemblyNamesExcludePreserved;
|
||||
using (var cache = new AssemblyCache(MetaUtil.CreateHotUpdateAndAOTAssemblyResolver(target, hotUpdateDlls)))
|
||||
{
|
||||
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);
|
||||
}
|
||||
MethodBridgeGeneratorCommand.CleanIl2CppBuildCache();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 7db18e1736f593c4089c85d764cf8620
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -1,20 +1,35 @@
|
||||
using HybridCLR.Editor.Installer;
|
||||
// Copyright 2026 Code Philosophy
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
using HybridCLR.BuildProcessors;
|
||||
using HybridCLR.Utils;
|
||||
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
|
||||
namespace HybridCLR.Commands
|
||||
{
|
||||
public static class StripAOTDllCommand
|
||||
{
|
||||
[MenuItem("HybridCLR/Generate/AOTDlls", priority = 105)]
|
||||
[MenuItem("HybridCLR/Generate/StrippedAotDlls", priority = 105)]
|
||||
public static void GenerateStripedAOTDlls()
|
||||
{
|
||||
GenerateStripedAOTDlls(EditorUserBuildSettings.activeBuildTarget);
|
||||
@@ -53,108 +68,141 @@ namespace HybridCLR.Editor.Commands
|
||||
|
||||
private static string GetLocationPathName(string buildDir, BuildTarget target)
|
||||
{
|
||||
switch(target)
|
||||
switch (target)
|
||||
{
|
||||
case BuildTarget.StandaloneWindows:
|
||||
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;
|
||||
default: return buildDir;
|
||||
case BuildTarget.StandaloneWindows:
|
||||
case BuildTarget.StandaloneWindows64: return $"{buildDir}/{PlayerSettings.productName}.exe";
|
||||
case BuildTarget.StandaloneOSX: return buildDir;
|
||||
case BuildTarget.iOS: return buildDir;
|
||||
case BuildTarget.Android: return buildDir;
|
||||
case BuildTarget.StandaloneLinux64: return $"{buildDir}/{PlayerSettings.productName}";
|
||||
default: return buildDir;
|
||||
}
|
||||
}
|
||||
|
||||
public static void GenerateStripedAOTDlls(BuildTarget target)
|
||||
{
|
||||
string outputPath = $"{SettingsUtil.HybridCLRDataDir}/StrippedAOTDllsTempProj/{target}";
|
||||
BashUtil.RemoveDir(outputPath);
|
||||
string outputPath = $"Temp/HybridCLR/StrippedAOTDllsTempProj/{target}";
|
||||
DirectoryUtil.RemoveDir(outputPath);
|
||||
|
||||
var buildOptions = GetBuildPlayerOptions(target);
|
||||
#if UNITY_2021_2_OR_NEWER
|
||||
buildOptions |= BuildOptions.CleanBuildCache;
|
||||
#endif
|
||||
|
||||
bool oldExportAndroidProj = EditorUserBuildSettings.exportAsGoogleAndroidProject;
|
||||
#if UNITY_EDITOR_OSX
|
||||
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)
|
||||
try
|
||||
{
|
||||
CheckSettings.DisableMethodBridgeDevelopmentFlagChecking = true;
|
||||
EditorUserBuildSettings.buildScriptsOnly = true;
|
||||
|
||||
string location = GetLocationPathName(outputPath, target);
|
||||
EditorUserBuildSettings.SetBuildLocation(target, location);
|
||||
|
||||
switch (target)
|
||||
{
|
||||
case BuildTarget.StandaloneWindows:
|
||||
case BuildTarget.StandaloneWindows64:
|
||||
{
|
||||
#if UNITY_EDITOR_WIN
|
||||
UnityEditor.WindowsStandalone.UserBuildSettings.createSolution = true;
|
||||
#endif
|
||||
break;
|
||||
break;
|
||||
}
|
||||
case BuildTarget.StandaloneOSX:
|
||||
{
|
||||
#if UNITY_EDITOR_OSX
|
||||
UnityEditor.OSXStandalone.UserBuildSettings.createXcodeProject = true;
|
||||
UnityEditor.OSXStandalone.UserBuildSettings.createXcodeProject = true;
|
||||
#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,
|
||||
options = buildOptions,
|
||||
target = target,
|
||||
targetGroup = BuildPipeline.GetBuildTargetGroup(target),
|
||||
#if UNITY_SERVER
|
||||
subtarget = (int)StandaloneBuildSubtarget.Server,
|
||||
#endif
|
||||
};
|
||||
|
||||
var report = BuildPipeline.BuildPlayer(buildPlayerOptions);
|
||||
|
||||
|
||||
|
||||
if (report.summary.result != UnityEditor.Build.Reporting.BuildResult.Succeeded)
|
||||
{
|
||||
throw new Exception("GenerateStripedAOTDlls failed");
|
||||
}
|
||||
}
|
||||
|
||||
Debug.Log($"GenerateStripedAOTDlls build option:{buildOptions}");
|
||||
|
||||
BuildPlayerOptions buildPlayerOptions = new BuildPlayerOptions()
|
||||
finally
|
||||
{
|
||||
scenes = EditorBuildSettings.scenes.Where(s => s.enabled).Select(s => s.path).ToArray(),
|
||||
locationPathName = location,
|
||||
options = buildOptions,
|
||||
target = target,
|
||||
targetGroup = BuildPipeline.GetBuildTargetGroup(target),
|
||||
};
|
||||
CheckSettings.DisableMethodBridgeDevelopmentFlagChecking = false;
|
||||
EditorUserBuildSettings.buildScriptsOnly = oldBuildScriptsOnly;
|
||||
EditorUserBuildSettings.SetBuildLocation(target, oldBuildLocation);
|
||||
|
||||
var report = BuildPipeline.BuildPlayer(buildPlayerOptions);
|
||||
|
||||
EditorUserBuildSettings.buildScriptsOnly = oldBuildScriptsOnly;
|
||||
EditorUserBuildSettings.SetBuildLocation(target, oldBuildLocation);
|
||||
|
||||
switch (target)
|
||||
{
|
||||
switch (target)
|
||||
{
|
||||
case BuildTarget.StandaloneWindows:
|
||||
case BuildTarget.StandaloneWindows64:
|
||||
{
|
||||
{
|
||||
#if UNITY_EDITOR_WIN
|
||||
UnityEditor.WindowsStandalone.UserBuildSettings.createSolution = oldCreateSolution;
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case BuildTarget.StandaloneOSX:
|
||||
{
|
||||
{
|
||||
#if UNITY_EDITOR_OSX
|
||||
UnityEditor.OSXStandalone.UserBuildSettings.createXcodeProject = oldCreateSolution;
|
||||
UnityEditor.OSXStandalone.UserBuildSettings.createXcodeProject = oldCreateSolution;
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
#if TUANJIE_2022_3_OR_NEWER
|
||||
case BuildTarget.HMIAndroid:
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
case BuildTarget.Android:
|
||||
{
|
||||
EditorUserBuildSettings.exportAsGoogleAndroidProject = oldExportAndroidProj;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (report.summary.result != UnityEditor.Build.Reporting.BuildResult.Succeeded)
|
||||
{
|
||||
throw new Exception("GenerateStripedAOTDlls failed");
|
||||
#if TUANJIE_2022_3_OR_NEWER
|
||||
case BuildTarget.OpenHarmony:
|
||||
{
|
||||
EditorUserBuildSettings.exportAsOpenHarmonyProject = oldOpenHarmonyProj;
|
||||
break;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
Debug.Log($"GenerateStripedAOTDlls target:{target} path:{outputPath}");
|
||||
}
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
using dnlib.DotNet;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace HybridCLR.Editor
|
||||
{
|
||||
public static class HashUtil
|
||||
{
|
||||
public static int CombineHash(int hash1, int hash2)
|
||||
{
|
||||
return hash1 * 1566083941 + hash2;
|
||||
}
|
||||
|
||||
public static int ComputHash(List<TypeSig> sigs)
|
||||
{
|
||||
int hash = 135781321;
|
||||
TypeEqualityComparer tc = TypeEqualityComparer.Instance;
|
||||
foreach (var sig in sigs)
|
||||
{
|
||||
hash = hash * 1566083941 + tc.GetHashCode(sig);
|
||||
}
|
||||
return hash;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 9af6345cc5ab1ae4a81262ab4b537911
|
||||
guid: e60a8b17b0e23a94a8ae875716208030
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
@@ -0,0 +1,125 @@
|
||||
// Copyright 2026 Code Philosophy
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
using dnlib.DotNet;
|
||||
using HybridCLR.Mod;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
|
||||
namespace HybridCLR.HotUpdate
|
||||
{
|
||||
public class MissingMetadataChecker
|
||||
{
|
||||
private readonly HashSet<string> _aotAssNames;
|
||||
|
||||
private readonly HashSet<string> _hotUpdateAssNames;
|
||||
|
||||
private readonly AssemblyCache _assCache;
|
||||
|
||||
public MissingMetadataChecker(string aotDllDir, IEnumerable<string> hotUpdateAssNames)
|
||||
{
|
||||
|
||||
_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 (_hotUpdateAssNames.Contains(aotAssName))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
_aotAssNames.Add(aotAssName);
|
||||
}
|
||||
_assCache = new AssemblyCache(new PathAssemblyResolver(aotDllDir));
|
||||
}
|
||||
|
||||
public bool Check(string hotUpdateDllPath)
|
||||
{
|
||||
bool anyMissing = false;
|
||||
|
||||
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);
|
||||
}
|
||||
else if (!_hotUpdateAssNames.Contains(refAssName))
|
||||
{
|
||||
UnityEngine.Debug.LogError($"Missing AOT Assembly: {refAssName}");
|
||||
anyMissing = true;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
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 memberRef in mod.GetMemberRefs())
|
||||
{
|
||||
if (memberRef.DeclaringType.DefinitionAssembly == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
string defAssName = memberRef.DeclaringType.DefinitionAssembly.Name;
|
||||
if (!_aotAssNames.Contains(defAssName))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if (memberRef.IsField)
|
||||
{
|
||||
IField field = (IField)memberRef;
|
||||
if (field.ResolveFieldDef() == null)
|
||||
{
|
||||
UnityEngine.Debug.LogError($"Missing Field: {memberRef.FullName}");
|
||||
anyMissing = true;
|
||||
}
|
||||
}
|
||||
else if (memberRef.IsMethod)
|
||||
{
|
||||
TypeSig declaringTypeSig = memberRef.DeclaringType.ToTypeSig();
|
||||
if (memberRef.ResolveMethodDef() == null)
|
||||
{
|
||||
if (declaringTypeSig.ElementType == ElementType.Array || declaringTypeSig.ElementType == ElementType.SZArray)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
UnityEngine.Debug.LogError($"Missing Method: {memberRef.FullName}");
|
||||
anyMissing = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return !anyMissing;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: bdd260aca2a6deb44b20210f01faa86b
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "HybridCLR.Editor",
|
||||
"rootNamespace": "",
|
||||
"rootNamespace": "HybridCLR",
|
||||
"references": [
|
||||
"HybridCLR.Runtime"
|
||||
],
|
||||
|
||||
@@ -1,86 +0,0 @@
|
||||
using HybridCLR.Editor.ABI;
|
||||
using HybridCLR.Editor.Template;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading.Tasks;
|
||||
using UnityEngine;
|
||||
|
||||
namespace HybridCLR.Editor.Il2CppDef
|
||||
{
|
||||
public class Il2CppDefGenerator
|
||||
{
|
||||
public class Options
|
||||
{
|
||||
public List<string> HotUpdateAssemblies { get; set; }
|
||||
|
||||
public string OutputFile { get; set; }
|
||||
|
||||
public string OutputFile2 { get; set; }
|
||||
|
||||
public string UnityVersion { get; set; }
|
||||
}
|
||||
|
||||
private readonly Options _options;
|
||||
public Il2CppDefGenerator(Options options)
|
||||
{
|
||||
_options = options;
|
||||
}
|
||||
|
||||
|
||||
private static readonly Regex s_unityVersionPat = new Regex(@"(\d+)\.(\d+)\.(\d+)");
|
||||
|
||||
public void Generate()
|
||||
{
|
||||
GenerateIl2CppConfig();
|
||||
GeneratePlaceHolderAssemblies();
|
||||
}
|
||||
|
||||
private void GenerateIl2CppConfig()
|
||||
{
|
||||
var frr = new FileRegionReplace(File.ReadAllText(_options.OutputFile));
|
||||
|
||||
List<string> lines = new List<string>();
|
||||
|
||||
var match = s_unityVersionPat.Matches(_options.UnityVersion)[0];
|
||||
int majorVer = int.Parse(match.Groups[1].Value);
|
||||
int minorVer1 = int.Parse(match.Groups[2].Value);
|
||||
int minorVer2 = int.Parse(match.Groups[3].Value);
|
||||
|
||||
lines.Add($"#define HYBRIDCLR_UNITY_VERSION {majorVer}{minorVer1.ToString("D2")}{minorVer2.ToString("D2")}");
|
||||
lines.Add($"#define HYBRIDCLR_UNITY_{majorVer} 1");
|
||||
for (int ver = 2019; ver <= 2024; ver++)
|
||||
{
|
||||
if (majorVer >= ver)
|
||||
{
|
||||
lines.Add($"#define HYBRIDCLR_UNITY_{ver}_OR_NEW 1");
|
||||
}
|
||||
}
|
||||
|
||||
frr.Replace("UNITY_VERSION", string.Join("\n", lines));
|
||||
|
||||
frr.Commit(_options.OutputFile);
|
||||
Debug.Log($"[HybridCLR.Editor.Il2CppDef.Generator] output:{_options.OutputFile}");
|
||||
}
|
||||
|
||||
private void GeneratePlaceHolderAssemblies()
|
||||
{
|
||||
var frr = new FileRegionReplace(File.ReadAllText(_options.OutputFile2));
|
||||
|
||||
List<string> lines = new List<string>();
|
||||
|
||||
foreach (var ass in _options.HotUpdateAssemblies)
|
||||
{
|
||||
lines.Add($"\t\t\"{ass}\",");
|
||||
}
|
||||
|
||||
frr.Replace("PLACE_HOLDER", string.Join("\n", lines));
|
||||
|
||||
frr.Commit(_options.OutputFile2);
|
||||
Debug.Log($"[HybridCLR.Editor.Il2CppDef.Generator] output:{_options.OutputFile2}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,143 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace HybridCLR.Editor.Installer
|
||||
{
|
||||
public static class BashUtil
|
||||
{
|
||||
public static int RunCommand(string workingDir, string program, string[] args, bool log = true)
|
||||
{
|
||||
using (Process p = new Process())
|
||||
{
|
||||
p.StartInfo.WorkingDirectory = workingDir;
|
||||
p.StartInfo.FileName = program;
|
||||
p.StartInfo.UseShellExecute = false;
|
||||
p.StartInfo.CreateNoWindow = true;
|
||||
string argsStr = string.Join(" ", args.Select(arg => "\"" + arg + "\""));
|
||||
p.StartInfo.Arguments = argsStr;
|
||||
if (log)
|
||||
{
|
||||
UnityEngine.Debug.Log($"[BashUtil] run => {program} {argsStr}");
|
||||
}
|
||||
p.Start();
|
||||
p.WaitForExit();
|
||||
return p.ExitCode;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static (int ExitCode, string StdOut, string StdErr) RunCommand2(string workingDir, string program, string[] args, bool log = true)
|
||||
{
|
||||
using (Process p = new Process())
|
||||
{
|
||||
p.StartInfo.WorkingDirectory = workingDir;
|
||||
p.StartInfo.FileName = program;
|
||||
p.StartInfo.UseShellExecute = false;
|
||||
p.StartInfo.CreateNoWindow = true;
|
||||
p.StartInfo.RedirectStandardOutput = true;
|
||||
p.StartInfo.RedirectStandardError = true;
|
||||
string argsStr = string.Join(" ", args);
|
||||
p.StartInfo.Arguments = argsStr;
|
||||
if (log)
|
||||
{
|
||||
UnityEngine.Debug.Log($"[BashUtil] run => {program} {argsStr}");
|
||||
}
|
||||
p.Start();
|
||||
p.WaitForExit();
|
||||
|
||||
string stdOut = p.StandardOutput.ReadToEnd();
|
||||
string stdErr = p.StandardError.ReadToEnd();
|
||||
return (p.ExitCode, stdOut, stdErr);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static void RemoveDir(string dir, bool log = false)
|
||||
{
|
||||
if (log)
|
||||
{
|
||||
UnityEngine.Debug.Log($"[BashUtil] RemoveDir dir:{dir}");
|
||||
}
|
||||
|
||||
int maxTryCount = 5;
|
||||
for (int i = 0; i < maxTryCount; ++i)
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void RecreateDir(string dir)
|
||||
{
|
||||
if(Directory.Exists(dir))
|
||||
{
|
||||
RemoveDir(dir, true);
|
||||
}
|
||||
Directory.CreateDirectory(dir);
|
||||
}
|
||||
|
||||
private static void CopyWithCheckLongFile(string srcFile, string dstFile)
|
||||
{
|
||||
var maxPathLength = 255;
|
||||
#if UNITY_EDITOR_OSX
|
||||
maxPathLength = 1024;
|
||||
#endif
|
||||
if (srcFile.Length > maxPathLength)
|
||||
{
|
||||
UnityEngine.Debug.LogError($"srcFile:{srcFile} path is too long. copy ignore!");
|
||||
return;
|
||||
}
|
||||
if (dstFile.Length > maxPathLength)
|
||||
{
|
||||
UnityEngine.Debug.LogError($"dstFile:{dstFile} path is too long. copy ignore!");
|
||||
return;
|
||||
}
|
||||
File.Copy(srcFile, dstFile);
|
||||
}
|
||||
|
||||
public static void CopyDir(string src, string dst, bool log = false)
|
||||
{
|
||||
if (log)
|
||||
{
|
||||
UnityEngine.Debug.Log($"[BashUtil] CopyDir {src} => {dst}");
|
||||
}
|
||||
RemoveDir(dst);
|
||||
Directory.CreateDirectory(dst);
|
||||
foreach(var file in Directory.GetFiles(src))
|
||||
{
|
||||
CopyWithCheckLongFile(file, $"{dst}/{Path.GetFileName(file)}");
|
||||
}
|
||||
foreach(var subDir in Directory.GetDirectories(src))
|
||||
{
|
||||
CopyDir(subDir, $"{dst}/{Path.GetFileName(subDir)}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,38 @@
|
||||
// Copyright 2026 Code Philosophy
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
#if UNITY_6000_3_OR_NEWER && UNITY_EDITOR_OSX
|
||||
#define NEW_IL2CPP_PATH
|
||||
#endif
|
||||
using HybridCLR.Settings;
|
||||
using HybridCLR.Utils;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
using Debug = UnityEngine.Debug;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Linq;
|
||||
using HybridCLR.Editor.Settings;
|
||||
|
||||
namespace HybridCLR.Editor.Installer
|
||||
namespace HybridCLR.Installer
|
||||
{
|
||||
|
||||
public class InstallerController
|
||||
@@ -22,7 +45,6 @@ namespace HybridCLR.Editor.Installer
|
||||
|
||||
private readonly UnityVersion _curVersion;
|
||||
|
||||
private readonly HybridclrVersionManifest _versionManifest;
|
||||
private readonly HybridclrVersionInfo _curDefaultVersion;
|
||||
|
||||
public string PackageVersion { get; private set; }
|
||||
@@ -31,9 +53,10 @@ namespace HybridCLR.Editor.Installer
|
||||
|
||||
public InstallerController()
|
||||
{
|
||||
_curVersion = ParseUnityVersion(Application.unityVersion);
|
||||
_versionManifest = GetHybridCLRVersionManifest();
|
||||
_curDefaultVersion = _versionManifest.versions.FirstOrDefault(v => v.unity_version == _curVersion.major.ToString());
|
||||
_curVersion = UnityVersion.ParseUnityVersion(Application.unityVersion);
|
||||
HybridclrVersionManifest versionManifest = GetHybridCLRVersionManifest();
|
||||
|
||||
_curDefaultVersion = FindMatchedVersion(versionManifest.versions, _curVersion);
|
||||
PackageVersion = LoadPackageInfo().version;
|
||||
InstalledLibil2cppVersion = ReadLocalVersion();
|
||||
}
|
||||
@@ -50,6 +73,32 @@ namespace HybridCLR.Editor.Installer
|
||||
return JsonUtility.FromJson<PackageInfo>(File.ReadAllText(packageJson, Encoding.UTF8));
|
||||
}
|
||||
|
||||
private HybridclrVersionInfo FindMatchedVersion(List<HybridclrVersionInfo> versions, UnityVersion curVer)
|
||||
{
|
||||
HybridclrVersionInfo bestMatch = null;
|
||||
foreach (var v in versions)
|
||||
{
|
||||
string[] versionWithEngineParts = v.unity_version.Split('-');
|
||||
bool isTuanjieVersion = versionWithEngineParts.Length >= 2 && versionWithEngineParts[1] == "tuanjie";
|
||||
if (curVer.isTuanjieEngine != isTuanjieVersion)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
string[] versionParts = versionWithEngineParts[0].Split('.');
|
||||
if (int.Parse(versionParts[0]) == curVer.major && (versionParts.Length < 2 || int.Parse(versionParts[1]) == curVer.minor1))
|
||||
{
|
||||
bestMatch = v;
|
||||
}
|
||||
}
|
||||
if (bestMatch == null)
|
||||
{
|
||||
string compatibleVersions = string.Join(", ", versions.Select(v => v.unity_version));
|
||||
throw new NotSupportedException($"No compatible version found for Unity {curVer.major}.{curVer.minor1}.{curVer.minor2}, please use compatible version of Unity: {compatibleVersions}");
|
||||
}
|
||||
UnityEngine.Debug.Log($"bestMatch: {bestMatch.unity_version} {bestMatch.il2cpp_plus.tag} {bestMatch.hybridclr.tag} ");
|
||||
return bestMatch;
|
||||
}
|
||||
|
||||
[Serializable]
|
||||
class PackageInfo
|
||||
@@ -62,7 +111,7 @@ namespace HybridCLR.Editor.Installer
|
||||
[Serializable]
|
||||
class VersionDesc
|
||||
{
|
||||
public string branch;
|
||||
public string tag;
|
||||
|
||||
//public string hash;
|
||||
}
|
||||
@@ -83,83 +132,33 @@ namespace HybridCLR.Editor.Installer
|
||||
public List<HybridclrVersionInfo> versions;
|
||||
}
|
||||
|
||||
private class UnityVersion
|
||||
{
|
||||
public int major;
|
||||
public int minor1;
|
||||
public int minor2;
|
||||
|
||||
public override string ToString()
|
||||
public string HybridclrLocalVersion => _curDefaultVersion?.hybridclr?.tag;
|
||||
|
||||
public string Il2cppPlusLocalVersion => _curDefaultVersion?.il2cpp_plus?.tag;
|
||||
|
||||
public string ApplicationIl2cppPath
|
||||
{
|
||||
get
|
||||
{
|
||||
return $"{major}.{minor1}.{minor2}";
|
||||
Debug.Log($"application path:{EditorApplication.applicationPath} {EditorApplication.applicationContentsPath}");
|
||||
#if NEW_IL2CPP_PATH
|
||||
#if UNITY_IOS
|
||||
string platformDirName = "iOSSupport";
|
||||
#elif UNITY_TVOS
|
||||
string platformDirName = "AppleTVSupport";
|
||||
#elif UNITY_VISIONOS
|
||||
string platformDirName = "VisionOSPlayer";
|
||||
#else
|
||||
string platformDirName = "iOSSupport";
|
||||
#endif
|
||||
return $"{EditorApplication.applicationContentsPath}/../../PlaybackEngines/{platformDirName}/il2cpp";
|
||||
#else
|
||||
return $"{EditorApplication.applicationContentsPath}/il2cpp";
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
private static readonly Regex s_unityVersionPat = new Regex(@"(\d+)\.(\d+)\.(\d+)");
|
||||
|
||||
private UnityVersion ParseUnityVersion(string versionStr)
|
||||
{
|
||||
var matches = s_unityVersionPat.Matches(versionStr);
|
||||
if (matches.Count == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
Match match = matches[matches.Count - 1];
|
||||
int major = int.Parse(match.Groups[1].Value);
|
||||
int minor1 = int.Parse(match.Groups[2].Value);
|
||||
int minor2 = int.Parse(match.Groups[3].Value);
|
||||
return new UnityVersion { major = major, minor1 = minor1, minor2 = minor2 };
|
||||
}
|
||||
|
||||
public string GetCurrentUnityVersionMinCompatibleVersionStr()
|
||||
{
|
||||
return GetMinCompatibleVersion(MajorVersion);
|
||||
}
|
||||
|
||||
public string GetMinCompatibleVersion(int majorVersion)
|
||||
{
|
||||
switch(majorVersion)
|
||||
{
|
||||
case 2020: return $"2020.3.0";
|
||||
case 2021: return $"2021.3.0";
|
||||
case 2022: return $"2022.3.0";
|
||||
default: return $"2020.3.0";
|
||||
}
|
||||
}
|
||||
|
||||
public enum CompatibleType
|
||||
{
|
||||
Compatible,
|
||||
MaybeIncompatible,
|
||||
Incompatible,
|
||||
}
|
||||
|
||||
public CompatibleType GetCompatibleType()
|
||||
{
|
||||
UnityVersion version = _curVersion;
|
||||
if (version == null)
|
||||
{
|
||||
return CompatibleType.Incompatible;
|
||||
}
|
||||
if (version.minor1 != 3)
|
||||
{
|
||||
return CompatibleType.MaybeIncompatible;
|
||||
}
|
||||
return CompatibleType.Compatible;
|
||||
}
|
||||
|
||||
public string HybridclrLocalVersion => _curDefaultVersion?.hybridclr?.branch;
|
||||
|
||||
public string Il2cppPlusLocalVersion => _curDefaultVersion?.il2cpp_plus?.branch;
|
||||
|
||||
|
||||
private string GetIl2CppPathByContentPath(string contentPath)
|
||||
{
|
||||
return $"{contentPath}/il2cpp";
|
||||
}
|
||||
|
||||
public string ApplicationIl2cppPath => GetIl2CppPathByContentPath(EditorApplication.applicationContentsPath);
|
||||
|
||||
public string LocalVersionFile => $"{SettingsUtil.LocalIl2CppDir}/libil2cpp/hybridclr/generated/libil2cpp-version.txt";
|
||||
|
||||
private string ReadLocalVersion()
|
||||
@@ -174,6 +173,7 @@ namespace HybridCLR.Editor.Installer
|
||||
public void WriteLocalVersion()
|
||||
{
|
||||
InstalledLibil2cppVersion = PackageVersion;
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(LocalVersionFile));
|
||||
File.WriteAllText(LocalVersionFile, PackageVersion, Encoding.UTF8);
|
||||
Debug.Log($"Write installed version:'{PackageVersion}' to {LocalVersionFile}");
|
||||
}
|
||||
@@ -190,8 +190,8 @@ namespace HybridCLR.Editor.Installer
|
||||
|
||||
void CloneBranch(string workDir, string repoUrl, string branch, string repoDir)
|
||||
{
|
||||
BashUtil.RemoveDir(repoDir);
|
||||
BashUtil.RunCommand(workDir, "git", new string[] {"clone", "-b", branch, "--depth", "1", repoUrl, repoDir});
|
||||
DirectoryUtil.RemoveDir(repoDir);
|
||||
BashUtil.RunCommand(workDir, "git", new string[] { "clone", "-b", branch, "--depth", "1", repoUrl, repoDir });
|
||||
}
|
||||
|
||||
private string PrepareLibil2cppWithHybridclrFromGitRepo()
|
||||
@@ -201,9 +201,9 @@ namespace HybridCLR.Editor.Installer
|
||||
//BashUtil.RecreateDir(workDir);
|
||||
|
||||
// clone hybridclr
|
||||
string hybridclrRepoURL = HybridCLRSettings.Instance.hybridclrRepoURL;
|
||||
string hybridclrRepoURL = HybridCLRSettings.instance.hybridclrRepoURL;
|
||||
string hybridclrRepoDir = $"{workDir}/{hybridclr_repo_path}";
|
||||
CloneBranch(workDir, hybridclrRepoURL, _curDefaultVersion.hybridclr.branch, hybridclrRepoDir);
|
||||
CloneBranch(workDir, hybridclrRepoURL, _curDefaultVersion.hybridclr.tag, hybridclrRepoDir);
|
||||
|
||||
if (!Directory.Exists(hybridclrRepoDir))
|
||||
{
|
||||
@@ -211,9 +211,9 @@ namespace HybridCLR.Editor.Installer
|
||||
}
|
||||
|
||||
// clone il2cpp_plus
|
||||
string il2cppPlusRepoURL = HybridCLRSettings.Instance.il2cppPlusRepoURL;
|
||||
string il2cppPlusRepoURL = HybridCLRSettings.instance.il2cppPlusRepoURL;
|
||||
string il2cppPlusRepoDir = $"{workDir}/{il2cpp_plus_repo_path}";
|
||||
CloneBranch(workDir, il2cppPlusRepoURL, _curDefaultVersion.il2cpp_plus.branch, il2cppPlusRepoDir);
|
||||
CloneBranch(workDir, il2cppPlusRepoURL, _curDefaultVersion.il2cpp_plus.tag, il2cppPlusRepoDir);
|
||||
|
||||
if (!Directory.Exists(il2cppPlusRepoDir))
|
||||
{
|
||||
@@ -226,36 +226,41 @@ namespace HybridCLR.Editor.Installer
|
||||
|
||||
public void InstallFromLocal(string libil2cppWithHybridclrSourceDir)
|
||||
{
|
||||
RunInitLocalIl2CppData(ApplicationIl2cppPath, libil2cppWithHybridclrSourceDir, _curVersion);
|
||||
RunInitLocalIl2CppData(ApplicationIl2cppPath, libil2cppWithHybridclrSourceDir);
|
||||
}
|
||||
|
||||
private void RunInitLocalIl2CppData(string editorIl2cppPath, string libil2cppWithHybridclrSourceDir, UnityVersion version)
|
||||
private void RunInitLocalIl2CppData(string editorIl2cppPath, string libil2cppWithHybridclrSourceDir)
|
||||
{
|
||||
if (GetCompatibleType() == CompatibleType.Incompatible)
|
||||
{
|
||||
Debug.LogError($"Incompatible with current version, minimum compatible version: {GetCurrentUnityVersionMinCompatibleVersionStr()}");
|
||||
return;
|
||||
}
|
||||
string workDir = SettingsUtil.HybridCLRDataDir;
|
||||
Directory.CreateDirectory(workDir);
|
||||
|
||||
// create LocalIl2Cpp
|
||||
string localUnityDataDir = SettingsUtil.LocalUnityDataDir;
|
||||
BashUtil.RecreateDir(localUnityDataDir);
|
||||
|
||||
DirectoryUtil.RecreateDir(localUnityDataDir);
|
||||
#if !NEW_IL2CPP_PATH
|
||||
// copy MonoBleedingEdge
|
||||
BashUtil.CopyDir($"{Directory.GetParent(editorIl2cppPath)}/MonoBleedingEdge", $"{localUnityDataDir}/MonoBleedingEdge", true);
|
||||
|
||||
DirectoryUtil.CopyDir($"{Directory.GetParent(editorIl2cppPath)}/MonoBleedingEdge", $"{localUnityDataDir}/MonoBleedingEdge", true);
|
||||
#endif
|
||||
// copy il2cpp
|
||||
BashUtil.CopyDir(editorIl2cppPath, SettingsUtil.LocalIl2CppDir, true);
|
||||
DirectoryUtil.CopyDir(editorIl2cppPath, SettingsUtil.LocalIl2CppDir, true);
|
||||
#if NEW_IL2CPP_PATH
|
||||
string buildDir = $"{SettingsUtil.LocalIl2CppDir}/build";
|
||||
if (RuntimeInformation.ProcessArchitecture == Architecture.Arm || RuntimeInformation.ProcessArchitecture == Architecture.Arm64)
|
||||
{
|
||||
DirectoryUtil.CopyDir($"{buildDir}/deploy_arm64", $"{buildDir}/deploy", false);
|
||||
}
|
||||
else
|
||||
{
|
||||
DirectoryUtil.CopyDir($"{buildDir}/deploy_x86_64", $"{buildDir}/deploy", false);
|
||||
}
|
||||
#endif
|
||||
|
||||
// replace libil2cpp
|
||||
string dstLibil2cppDir = $"{SettingsUtil.LocalIl2CppDir}/libil2cpp";
|
||||
BashUtil.CopyDir($"{libil2cppWithHybridclrSourceDir}", dstLibil2cppDir, true);
|
||||
DirectoryUtil.CopyDir($"{libil2cppWithHybridclrSourceDir}", dstLibil2cppDir, true);
|
||||
|
||||
// clean Il2cppBuildCache
|
||||
BashUtil.RemoveDir($"{SettingsUtil.ProjectDir}/Library/Il2cppBuildCache", true);
|
||||
|
||||
DirectoryUtil.RemoveDir($"{SettingsUtil.ProjectDir}/Library/Il2cppBuildCache", true);
|
||||
if (HasInstalledHybridCLR())
|
||||
{
|
||||
WriteLocalVersion();
|
||||
|
||||
@@ -1,11 +1,29 @@
|
||||
using System;
|
||||
// Copyright 2026 Code Philosophy
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
|
||||
|
||||
namespace HybridCLR.Editor.Installer
|
||||
namespace HybridCLR.Installer
|
||||
{
|
||||
public class InstallerWindow : EditorWindow
|
||||
{
|
||||
@@ -44,46 +62,35 @@ namespace HybridCLR.Editor.Installer
|
||||
EditorGUILayout.LabelField($"Installed: {hasInstall}", EditorStyles.boldLabel);
|
||||
GUILayout.Space(10f);
|
||||
|
||||
EditorGUILayout.LabelField($"Package Version: v{_controller.PackageVersion}");
|
||||
EditorGUILayout.LabelField($"Package Version: v{_controller.PackageVersion}");
|
||||
GUILayout.Space(5f);
|
||||
EditorGUILayout.LabelField($"Installed Version: {_controller.InstalledLibil2cppVersion ?? "Unknown"}");
|
||||
EditorGUILayout.LabelField($"Installed Version: v{_controller.InstalledLibil2cppVersion ?? " Unknown"}");
|
||||
GUILayout.Space(5f);
|
||||
|
||||
GUILayout.Space(10f);
|
||||
|
||||
InstallerController.CompatibleType compatibleType = _controller.GetCompatibleType();
|
||||
if (compatibleType != InstallerController.CompatibleType.Incompatible)
|
||||
|
||||
|
||||
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)))
|
||||
{
|
||||
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();
|
||||
|
||||
GUILayout.Space(20f);
|
||||
|
||||
EditorGUILayout.BeginHorizontal();
|
||||
if (GUILayout.Button("Install", GUILayout.Width(100)))
|
||||
{
|
||||
InstallLocalHybridCLR();
|
||||
GUIUtility.ExitGUI();
|
||||
}
|
||||
EditorGUILayout.EndHorizontal();
|
||||
_installLibil2cppWithHybridclrSourceDir = EditorUtility.OpenFolderPanel("Select libil2cpp", Application.dataPath, "libil2cpp");
|
||||
}
|
||||
else
|
||||
EditorGUI.EndDisabledGroup();
|
||||
EditorGUILayout.EndHorizontal();
|
||||
|
||||
GUILayout.Space(20f);
|
||||
|
||||
EditorGUILayout.BeginHorizontal();
|
||||
if (GUILayout.Button("Install", GUILayout.Width(100)))
|
||||
{
|
||||
EditorGUILayout.HelpBox($"Incompatible with current version, minimum compatible version:{_controller.GetCurrentUnityVersionMinCompatibleVersionStr()}", MessageType.Error);
|
||||
InstallLocalHybridCLR();
|
||||
GUIUtility.ExitGUI();
|
||||
}
|
||||
EditorGUILayout.EndHorizontal();
|
||||
|
||||
EditorGUILayout.EndVertical();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
// Copyright 2026 Code Philosophy
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
#if UNITY_6000_3_OR_NEWER && UNITY_EDITOR_OSX
|
||||
#define NEW_IL2CPP_PATH
|
||||
#endif
|
||||
namespace HybridCLR.Installer
|
||||
{
|
||||
public class UnityCompatibleUtil
|
||||
{
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 9eaeda6b4aeb5be449ba1ebeb98014df
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,58 @@
|
||||
// Copyright 2026 Code Philosophy
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
#if UNITY_6000_3_OR_NEWER && UNITY_EDITOR_OSX
|
||||
#define NEW_IL2CPP_PATH
|
||||
#endif
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace HybridCLR.Installer
|
||||
{
|
||||
public class UnityVersion
|
||||
{
|
||||
public int major;
|
||||
public int minor1;
|
||||
public int minor2;
|
||||
public bool isTuanjieEngine;
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return $"{major}.{minor1}.{minor2}";
|
||||
}
|
||||
|
||||
|
||||
private static readonly Regex s_unityVersionPat = new Regex(@"(\d+)\.(\d+)\.(\d+)");
|
||||
|
||||
public static UnityVersion ParseUnityVersion(string versionStr)
|
||||
{
|
||||
var matches = s_unityVersionPat.Matches(versionStr);
|
||||
if (matches.Count == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
Match match = matches[matches.Count - 1];
|
||||
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 };
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 7b474b2f44b3d804dace7aa7357ce144
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -1,47 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using dnlib.DotNet;
|
||||
using HybridCLR.Editor.Meta;
|
||||
using UnityEditor;
|
||||
using IAssemblyResolver = HybridCLR.Editor.Meta.IAssemblyResolver;
|
||||
|
||||
namespace HybridCLR.Editor.Link
|
||||
{
|
||||
public class Analyzer
|
||||
{
|
||||
private readonly IAssemblyResolver _resolver;
|
||||
|
||||
public Analyzer(IAssemblyResolver resolver)
|
||||
{
|
||||
_resolver = resolver;
|
||||
}
|
||||
|
||||
public HashSet<TypeRef> CollectRefs(List<string> rootAssemblies)
|
||||
{
|
||||
using (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);
|
||||
foreach (var type in dnAss.GetTypeRefs())
|
||||
{
|
||||
if (!rootAssemblyNames.Contains(type.DefinitionAssembly.Name.ToString()))
|
||||
{
|
||||
typeRefs.Add(type);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
assCollector.Dispose();
|
||||
return typeRefs;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
using dnlib.DotNet;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace HybridCLR.Editor.Link
|
||||
{
|
||||
internal class LinkXmlWriter
|
||||
{
|
||||
public void Write(string outputLinkXmlFile, HashSet<TypeRef> refTypes)
|
||||
{
|
||||
string parentDir = Directory.GetParent(outputLinkXmlFile).FullName;
|
||||
Directory.CreateDirectory(parentDir);
|
||||
var writer = System.Xml.XmlWriter.Create(outputLinkXmlFile,
|
||||
new System.Xml.XmlWriterSettings { Encoding = Encoding.UTF8, Indent = true});
|
||||
|
||||
writer.WriteStartDocument();
|
||||
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));
|
||||
|
||||
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)
|
||||
{
|
||||
writer.WriteStartElement("type");
|
||||
writer.WriteAttributeString("fullname", typeName);
|
||||
writer.WriteAttributeString("preserve", "all");
|
||||
writer.WriteEndElement();
|
||||
}
|
||||
writer.WriteEndElement();
|
||||
}
|
||||
writer.WriteEndElement();
|
||||
writer.WriteEndDocument();
|
||||
writer.Close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
// Copyright 2026 Code Philosophy
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
using HybridCLR.Installer;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
|
||||
namespace HybridCLR
|
||||
{
|
||||
public static class MenuProvider
|
||||
{
|
||||
public const string WebsiteUrl = "https://www.hybridclr.cn";
|
||||
|
||||
[MenuItem("HybridCLR/About", priority = 0)]
|
||||
public static void OpenAbout() => Application.OpenURL($"{WebsiteUrl}/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($"{WebsiteUrl}/docs/beginner/quickstart");
|
||||
|
||||
[MenuItem("HybridCLR/Documents/Performance")]
|
||||
public static void OpenPerformance() => Application.OpenURL($"{WebsiteUrl}/docs/basic/performance");
|
||||
|
||||
[MenuItem("HybridCLR/Documents/FAQ")]
|
||||
public static void OpenFAQ() => Application.OpenURL($"{WebsiteUrl}/docs/help/faq");
|
||||
|
||||
[MenuItem("HybridCLR/Documents/Common Errors")]
|
||||
public static void OpenCommonErrors() => Application.OpenURL($"{WebsiteUrl}/docs/help/commonerrors");
|
||||
|
||||
[MenuItem("HybridCLR/Documents/Bug Report")]
|
||||
public static void OpenBugReport() => Application.OpenURL($"{WebsiteUrl}/docs/help/issue");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
using dnlib.DotNet;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using UnityEngine;
|
||||
|
||||
namespace HybridCLR.Editor.Meta
|
||||
{
|
||||
public class AssemblyCache : AssemblyCacheBase
|
||||
{
|
||||
|
||||
public AssemblyCache(IAssemblyResolver assemblyResolver) : base(assemblyResolver)
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,30 @@
|
||||
// Copyright 2026 Code Philosophy
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
using dnlib.DotNet;
|
||||
using System;
|
||||
using HybridCLR.Mod;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using UnityEngine;
|
||||
using IAssemblyResolver = HybridCLR.Mod.IAssemblyResolver;
|
||||
|
||||
namespace HybridCLR.Editor.Meta
|
||||
namespace HybridCLR.Meta
|
||||
{
|
||||
public class AssemblyReferenceDeepCollector : AssemblyCacheBase
|
||||
{
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace HybridCLR.Editor.Meta
|
||||
{
|
||||
public abstract class AssemblyResolverBase : IAssemblyResolver
|
||||
{
|
||||
public string ResolveAssembly(string assemblyName, bool throwExIfNotFind)
|
||||
{
|
||||
if (TryResolveAssembly(assemblyName, out string assemblyPath))
|
||||
{
|
||||
return assemblyPath;
|
||||
}
|
||||
if (throwExIfNotFind)
|
||||
{
|
||||
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.");
|
||||
}
|
||||
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.");
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
protected abstract bool TryResolveAssembly(string assemblyName, out string assemblyPath);
|
||||
}
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace HybridCLR.Editor.Meta
|
||||
{
|
||||
public class CombinedAssemblyResolver : AssemblyResolverBase
|
||||
{
|
||||
private readonly IAssemblyResolver[] _resolvers;
|
||||
|
||||
public CombinedAssemblyResolver(params IAssemblyResolver[] resolvers)
|
||||
{
|
||||
_resolvers = resolvers;
|
||||
}
|
||||
|
||||
protected override bool TryResolveAssembly(string assemblyName, out string assemblyPath)
|
||||
{
|
||||
foreach(var resolver in _resolvers)
|
||||
{
|
||||
var assembly = resolver.ResolveAssembly(assemblyName, false);
|
||||
if (assembly != null)
|
||||
{
|
||||
assemblyPath = assembly;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
assemblyPath = null;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user