Compare commits

..

1 Commits

Author SHA1 Message Date
walon dad411f4e2 [version] 发布v3.4.3版本 2023-09-26 21:13:52 +08:00
209 changed files with 4898 additions and 7677 deletions
Binary file not shown.
Binary file not shown.
+20
View File
@@ -0,0 +1,20 @@
#include <codegen/il2cpp-codegen-metadata.h>
#include "vm/ClassInlines.h"
#include "vm/Object.h"
#include "vm/Class.h"
#include "../metadata/MetadataModule.h"
#include "../metadata/MetadataUtil.h"
#include "../interpreter/MethodBridge.h"
#include "../interpreter/Interpreter.h"
#include "../interpreter/MemoryUtil.h"
#include "../interpreter/InstrinctDef.h"
using namespace hybridclr::interpreter;
#if {PLATFORM_ABI}
//!!!{{CODE
//!!!}}CODE
#endif
@@ -0,0 +1,32 @@
#include "../metadata/ReversePInvokeMethodStub.h"
#include "../metadata/MetadataModule.h"
namespace hybridclr
{
namespace metadata
{
#if {PLATFORM_ABI}
//!!!{{CODE
void __ReversePInvokeMethod_0(void* xState)
{
CallLuaFunction(xState, 0);
}
void __ReversePInvokeMethod_1(void* xState)
{
CallLuaFunction(xState, 1);
}
Il2CppMethodPointer s_ReversePInvokeMethodStub[]
{
(Il2CppMethodPointer)__ReversePInvokeMethod_0,
(Il2CppMethodPointer)__ReversePInvokeMethod_1,
nullptr,
};
//!!!}}CODE
#endif
}
}
+9 -14
View File
@@ -1,24 +1,19 @@
{
"versions": [
{
"unity_version":"2022.3.x",
"hybridclr" : { "tag":"v9.1.0"},
"il2cpp_plus": { "tag":"v2022.3.x-9.1.0"}
"unity_version":"2020",
"hybridclr" : { "branch":"v3.3.3"},
"il2cpp_plus": { "branch":"v2020-3.3.2"}
},
{
"unity_version":"2022.3.x-tuanjie",
"hybridclr" : { "tag":"v9.1.0"},
"il2cpp_plus": { "tag":"v2022.3.x-tuanjie-9.1.0"}
"unity_version":"2021",
"hybridclr" : { "branch":"v3.3.3"},
"il2cpp_plus": { "branch":"v2021-3.3.2"}
},
{
"unity_version":"6000.0.x",
"hybridclr" : { "tag":"v9.1.0"},
"il2cpp_plus": { "tag":"v6000.0.x-9.1.0"}
},
{
"unity_version":"6000.3.x",
"hybridclr" : { "tag":"v6000.3.x-9.1.0"},
"il2cpp_plus": { "tag":"v6000.3.x-9.1.0"}
"unity_version":"2022",
"hybridclr" : { "branch":"v3.3.3"},
"il2cpp_plus": { "branch":"v2022-3.3.3"}
}
]
}
@@ -1,51 +0,0 @@
---
name: hybridclr-aot-generic
description: >-
Handle HybridCLR AOT generics: supplementary metadata via LoadMetadataForAOTAssembly, saving stripped AOT dlls per platform, HomologousImageMode, AOTGenericReference, and MissingMethodException for an AOT generic method. Use when an AOT generic fails to instantiate, the user asks about metadata patching, List/Dictionary/async generics, or which supplementary dll to ship.
---
# AOT generics
Docs: `guide/build/aotgeneric.md` and `start/generic.md` in the HybridCLR documentation.
Generic types and methods **defined in hot-update assemblies** have no AOT restriction. The restriction is hot-update code using a generic **defined in an AOT assembly** (`List<T>`, `Dictionary<TKey,TValue>`, async state machines, and similar) when that instantiation was not generated in AOT. Typical log:
```text
MissingMethodException: AOT generic method not instantiated in aot module
```
## Default: supplementary metadata
The community edition uses supplementary metadata. Do not send the user to hand-written RefTypes unless they are chasing one instantiation or optimizing a hot path.
Patch the **AOT dll that contains the generic method**, not the dll that contains the generic argument. `List<SomeHotUpdateStruct>` needs `mscorlib.dll`, because the missing IL is `List<T>.Add`, not the struct.
```csharp
// Call once before any hot-update code uses that AOT generic. Order among dlls does not matter.
LoadImageErrorCode err = HybridCLR.RuntimeApi.LoadMetadataForAOTAssembly(dllBytes, HomologousImageMode.SuperSet);
// Do not keep dllBytes. The API copies them.
```
- Call it after player startup, or after hot-update dlls are loaded and before business code runs. The supplementary dlls can ship in the player (for example StreamingAssets) or with a hot update.
- Call it on another thread if it stalls.
- Loaded metadata uses several times the dll size and is not released. Memory-tight projects use the commercial full generic sharing build (no supplementary dlls), or run `AOTAssemblyMetadataStripper.Strip` to drop non-generic method metadata first.
- `HybridCLR/Generate/AOTGenericReference` writes a conservative `PatchedAOTAssemblyList`. Load the whole list when memory is fine. Otherwise start with common dlls such as `mscorlib` and add a dll when a new AOT generic error appears. Supplementary dlls can themselves be hot-updated.
## Which dll
The player build copies stripped AOT dlls to `{project}/HybridCLRData/AssembliesPostIl2CppStrip/{target}`. `Generate/AotDlls` can also produce them by exporting a temp project.
- **Stripped dlls from different BuildTargets are not interchangeable.**
- **Freeze the dlls from the shipped player.** Do not replace them with a newer Generate output on every hot update.
- `HomologousImageMode.SuperSet`: a superset is enough. Stripped or original AOT dlls both work. Use this by default.
- `HomologousImageMode.Consistent`: the bytes must match **that player build's** stripped dll. Original dlls do not work. `Generate/All` output often differs slightly from the real player, so Consistent fails more often.
## Generic sharing (optional)
After metadata is loaded, HybridCLR still prefers an il2cpp shared instantiation when one exists. Class type arguments share as `object`. Non-enum value types share only with themselves. Enums share with enums of the same underlying type. Value types do not share across different types the way classes do, so `List<HotUpdateStruct>` is not covered by an AOT `List<int>`.
Instantiations in `AOTGenericReferences.cs` are comments and are overwritten on regenerate. Copy any you want into another AOT file (for example `new List<object>()`). That is a performance optimization, not a requirement for correctness.
## Full generic sharing
Commercial editions only. It removes the size, memory, and interpreted-call cost of supplementary metadata. Do not switch the workflow to it unless the user has that edition.
@@ -1,48 +0,0 @@
---
name: hybridclr-avoid-code-strip
description: >-
Keep Unity IL2CPP from stripping AOT types and methods that hot-update code calls: Generate/LinkXml, linkPreserveLevel, a hand-written Assets/link.xml, a real reference from the main project, and MissingMetadataChecker. Use for TypeLoadException, MissingMethodException that is not an AOT generic error, code stripping, link.xml, or Generate/LinkXml.
---
# Avoid code stripping
Doc: `guide/build/codestriping.md` in the HybridCLR documentation.
If a stripped AOT type or method is called from hot-update code:
```text
TypeLoadException: Could not load type 'Xxx' from assembly 'yyy'
MissingMethodException: ...
```
If the log says `AOT generic method not instantiated`, use `hybridclr-aot-generic`. link.xml does not fix that.
## Before the player build
Run `HybridCLR/Generate/All` before building the player. It includes `Generate/LinkXml`. LinkXml alone scans AOT references from the current hot-update dlls.
- Output is Settings `outputLinkFile`, default `Assets/HybridCLR/Generate/link.xml`.
- **Do not** point `outputLinkFile` at a hand-maintained `Assets/link.xml`. Generation overwrites it.
- `linkPreserveLevel`: default `PreserveAllOfDeclaringType` keeps the whole referenced type. Use `PreserveExactMember` only to shrink the player (referenced fields, methods, properties, and events). A later hot update that touches another member can then miss it.
## When link.xml has no effect
If the main project never references any type or method in an AOT assembly, Unity strips that assembly entirely and preserve entries are ignored. Reference one type or method from that dll in the main project.
`preserve all` on `UnityEngine.Debug` can hit a Unity bug. Since 6.1.0, generated link.xml skips that class. Do not add it back.
## Reserve types for later hot updates
`Generate/LinkXml` only covers references in the **current** hot-update dlls. Put types you will need later in a separate `Assets/link.xml`, or call them from the main project. Do not put them in the generated file.
## Check before publishing a hot update
Use the stripped AOT dll directory saved from the player build. Do not use `AssembliesPostIl2CppStrip` after a later `Generate/All` has refreshed it.
```csharp
var checker = new HybridCLR.HotUpdate.MissingMetadataChecker(
aotDirFromPlayerBuild, SettingsUtil.HotUpdateAssemblyNamesIncludePreserved);
bool ok = checker.Check(hotUpdateDllPath); // false: the dll touches a stripped type or method
```
The second argument is hot-update assembly names without `.dll`. If an Ultimate build also has DHE assemblies, include those names in the list.
-51
View File
@@ -1,51 +0,0 @@
---
name: hybridclr-configure
description: >-
Configure HybridCLR Settings and PlayerSettings: enable, hot-update assembly lists, external dll search paths, link.xml output, linkPreserveLevel, incremental GC, and IL2CPP. Use when the user opens HybridCLR/Settings, edits ProjectSettings/HybridCLRSettings.asset, checks settings before a player build, or asks what a setting does.
---
# Configure HybridCLR
Docs: `guide/setup/projectsettings.md` and `guide/setup/hybridclr-unity-package.md` in the HybridCLR documentation. Fields follow `Editor/Settings/HybridCLRSettings.cs` in this repo. The asset is `ProjectSettings/HybridCLRSettings.asset`.
How to split assemblies and create asmdefs is `hybridclr-hotupdate-assembly`. Do not expand that here.
## PlayerSettings
- Scripting Backend is **IL2CPP**. WebGL does not use this option. Since v2.4.0 the build check switches this automatically.
- Api Compatibility Level is **.NET Framework**.
- Incremental GC is allowed since v4.0.0. Older packages must turn it off.
## Hot-update lists
`hotUpdateAssemblyDefinitions` and `hotUpdateAssemblies` merge into the final hot-update dll list. **Do not put the same assembly in both.**
| Source | Where |
|---|---|
| asmdef | `hotUpdateAssemblyDefinitions` |
| External dll, or `Assembly-CSharp` | `hotUpdateAssemblies`, name **without** `.dll` |
An empty list fails the player-build check. `IFilterBuildAssemblies` removes these dlls from the player build so they are not compiled into AOT.
## Settings
- `enable`: default true. Turning it off drops HybridCLR from the player. Also remove the main project's reference to `HybridCLR.Runtime`, or symbols such as `LoadMetadataForAOTAssembly` are missing.
- `useGlobalIl2cpp`: default false. Keep the local `UNITY_IL2CPP_PATH`.
- `hybridclrRepoURL` / `il2cppPlusRepoURL`: clone URLs for the installer. Default is gitee.
- `preserveHotUpdateAssemblies`: names of hot-update dlls that do not exist yet (no `.dll`). The build does not check that the files exist, but it writes the names into `ScriptingAssemblies.json` so scripts can be attached to assets later. Do not list dlls that already exist.
- `externalHotUpdateAssembliyDirs`: search paths for external hot-update dlls. The serialized name is spelled `Assembliy`. Do not rename it. Paths are relative to the **project root** (parent of Assets). Each entry is searched as `{dir}/{platform}` first, then `{dir}`. Earlier entries win. The dll name still goes in `hotUpdateAssemblies`.
- `outputLinkFile`: output of `Generate/LinkXml`. Default `HybridCLR/Generate/link.xml`, relative to Assets. **Do not** point it at `Assets/link.xml`. Generation overwrites the file.
- `linkPreserveLevel`: `PreserveAllOfDeclaringType` (default; keep every member of a referenced type) or `PreserveExactMember` (only referenced fields, methods, properties, and events; smaller).
- `outputAOTGenericReferenceFile`: default `HybridCLR/Generate/AOTGenericReferences.cs`.
- `maxGenericReferenceIteration` / `maxMethodBridgeGenericIteration`: generic scan iteration cap, default 10. Raise them only if the log shows the scan has not converged.
## Fixed output directories
These are not settings:
- Hot-update dlls: `{project}/HybridCLRData/HotUpdateDlls/{target}`
- Stripped AOT dlls: `{project}/HybridCLRData/AssembliesPostIl2CppStrip/{target}`
## What the package does during a player build
Do not hand-edit these: set or clear the process `UNITY_IL2CPP_PATH` from `enable`; strip hot-update assemblies from the build; write hot-update dll names into the assembly list; copy stripped AOT dlls to the directory above.
@@ -1,61 +0,0 @@
---
name: hybridclr-hotupdate-assembly
description: >-
Split, create, compile, and load HybridCLR hot-update assemblies: asmdefs and Assembly-CSharp, forbidding AOT references to hot-update code, CompileDll, Assembly.Load order, and calling hot-update entry points from the main project. Use when the user adds a hot-update module, splits AOT and hot-update code, compiles HotUpdate.dll, loads a dll, hits a duplicate load, or a player build references a hot-update assembly.
---
# Hot-update assemblies
Docs: `guide/setup/hotupdateassemblysetting.md`, `guide/build/compileassembly.md`, and `guide/build/runhotupdatecodes.md` in the HybridCLR documentation. Settings fields are in `hybridclr-configure`.
## Split
Keep at least one **AOT** assembly for startup and for downloading hot-update content. Hot-update code must live in its own assembly.
Two common layouts:
- `Assembly-CSharp` stays AOT, and other code is split into AOT and hot-update asmdefs. **Turn off Auto Referenced on hot-update asmdefs.** `Assembly-CSharp` references every other assembly, so Auto Referenced easily creates an AOT reference to a hot-update dll and the player build fails.
- `Assembly-CSharp` itself is hot-update. Put the name in `hotUpdateAssemblies` without `.dll`.
AOT assemblies must not reference hot-update assemblies. Hot-update assemblies may reference each other. Load dependencies first.
## Create
1. Create a folder, for example `Assets/HotUpdate`.
2. Create → Assembly Definition, named like the module.
3. In `HybridCLR/Settings`, put asmdefs in `hotUpdateAssemblyDefinitions`. Put assemblies that have no asmdef in `hotUpdateAssemblies` by name. Do not add the same assembly to both.
4. For a prebuilt dll outside the default output directory, put the name in `hotUpdateAssemblies` and the directory in `externalHotUpdateAssembliyDirs` (relative to the project root).
## Compile
Do not ship dlls from `Library/ScriptAssemblies`. Those are compiled for the Editor target and depend on the debugger setting.
- Use `HybridCLR/Compile/{platform}`, or `HybridCLR.Editor.Commands.CompileDllCommand.CompileDll(BuildTarget)`.
- Output: `{project}/HybridCLRData/HotUpdateDlls/{target}`. Compile once per BuildTarget so defines such as `UNITY_ANDROID` match.
- `HybridCLR/Generate/All` also compiles hot-update dlls. **After the player is shipped**, a normal hot update only recompiles and publishes the dll. Do not run Generate every time.
When copying into assets, add a `.bytes` extension (`HotUpdate.dll.bytes`).
## Load
```csharp
// The runtime copies the bytes. Do not keep assemblyData or pdb after the call returns.
Assembly ass = Assembly.Load(assemblyData);
// Since v6.4.0, symbols can load with the assembly:
Assembly ass2 = Assembly.Load(assemblyData, pdbSymbolData);
```
- `Assembly.Load` multiple dlls in dependency order. Move the call to another thread if it stalls the main thread.
- **Do not Load again in the Editor.** The assemblies are already in the domain. Wrap the load in `#if !UNITY_EDITOR` and, in the Editor, find them with `AppDomain.CurrentDomain.GetAssemblies()`.
- An assembly missing from the hot-update lists is compiled into AOT. Loading it again at runtime is a duplicate load.
## Call hot-update code from AOT
The main project cannot reference hot-update types directly. Typical entry points:
- Reflection: `ass.GetType(...).GetMethod(...).Invoke`
- `Delegate.CreateDelegate`, or `Activator.CreateInstance` cast to an interface defined in AOT
- `go.AddComponent(type)` after the dll is loaded
- Instantiate a prefab or scene packed in an AssetBundle (extra rules for scripts on assets are in `hybridclr-monobehaviour`)
Load the dll **before** loading an AssetBundle that should restore those scripts.
@@ -1,28 +0,0 @@
---
name: hybridclr-monobehaviour
description: >-
Use MonoBehaviour and ScriptableObject from HybridCLR hot-update code: AddComponent, scripts on assets, ScriptingAssemblies.json, AssetBundle load order, Script Missing, and the GetComponent(string) limitation. Use when the user attaches a hot-update script to a prefab or scene, hits Script Missing, or asks about the hot-update MonoBehaviour workflow.
---
# Hot-update MonoBehaviour
Doc: `guide/features/monobehaviour.md` in the HybridCLR documentation. Registering the assembly is `hybridclr-hotupdate-assembly`.
`AddComponent<T>()` and `AddComponent(Type)` work after that dll has been `Assembly.Load`ed.
## Scripts and ScriptableObjects on assets
Deserialization needs all of the following:
1. The dll that contains the script is already loaded.
2. The asset is loaded from an AssetBundle (Addressables and other AB-based systems count). A script on a Resources asset or a scene that ships in the player becomes **Script Missing**. Building that asset into an AssetBundle and then placing the bundle in Resources is fine.
3. The dll name is in the generated `ScriptingAssemblies.json`. Hot-update dlls are removed by `IFilterBuildAssemblies`, so they are not listed on their own. `PatchScriptingAssemblyList` writes names from `hotUpdateAssemblyDefinitions`, `hotUpdateAssemblies`, and `preserveHotUpdateAssemblies`. Unlisted assemblies are not restored.
The hot-update dll itself may live in an AssetBundle, as a raw file, or in an encrypted package. `Assembly.Load` it **before** loading assets that contain the scripts.
Do not rename these assemblies after release. The assembly list is baked into the player and cannot be hot-updated.
## Known limits
- `GetComponent(string)` cannot find a hot-update script that was restored from a hot-update asset. Use `GetComponent<T>()` or `GetComponent(typeof(T))`. Components added with `AddComponent` in code are not affected.
- Do not disable TypeTree when building AssetBundles. Script signature checks then fail and a normal load fails. If TypeTree must be off, call `AssetBundleCreateRequest.SetEnableCompatibilityChecks(false)` through reflection and keep code and asset versions matched. A mismatch can crash.
@@ -1,39 +0,0 @@
---
name: hybridclr-monopinvokecallback
description: >-
Reserve MonoPInvokeCallback and ReversePInvokeWrapper slots for HybridCLR hot-update methods: ReversePInvokeWrapperGenerationAttribute, Generate/ReversePInvokeWrapper, and the lack of automatic marshaling for string and other non-blittable arguments. Use for MonoPInvokeCallback, xlua/tolua/puerts callbacks, too few wrappers, or a crash when native code calls hot-update C#.
---
# MonoPInvokeCallback
Doc: `guide/features/monopinvokecallback.md` in the HybridCLR documentation. Choosing a Lua, JS, or Python stack is `hybridclr-script-language`.
A static method with `[MonoPInvokeCallback]` needs a C++ wrapper before `Marshal.GetFunctionPointerForDelegate` can return a pointer. Platforms that cannot JIT, including iOS, cannot create that wrapper at runtime. Generate it in the player build with `HybridCLR/Generate/ReversePInvokeWrapper` (`Generate/All` includes it).
## Reserve a count
Generating one wrapper per current callback runs out as soon as a later hot update adds another callback.
Add `[ReversePInvokeWrapperGeneration(preserveCount)]` (`HybridCLR` namespace) on the callback. **Counts are per signature:**
wrappers for a signature = sum of `preserveCount` on that signature + number of callbacks of that signature that do not have the attribute.
```csharp
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
delegate int LuaFunction(IntPtr luaState);
[ReversePInvokeWrapperGeneration(10)]
[MonoPInvokeCallback(typeof(LuaFunction))]
public static int LuaCallback(IntPtr luaState) => 0;
```
The reservation is fixed in the player. Hot updates can only consume wrappers that were already generated.
## Argument marshaling
HybridCLR does **not** marshal arguments when calling these callbacks. `int` and `float` work. `string` arrives as `char*` and using it as a string crashes.
Two options:
1. Put the callback in AOT and call into hot-update code from there. The AOT wrapper has il2cpp marshaling.
2. Take `IntPtr` in the hot-update callback and convert with `Marshal.PtrToStringUTF8`. Do the same for other non-primitive types that need marshaling.
@@ -1,36 +0,0 @@
---
name: hybridclr-script-language
description: >-
Run HybridCLR next to Lua, JavaScript/TypeScript, or Python: prefer ZLua and ZenTS; xlua, tolua, slua, and puerts need reserved ReversePInvokeWrappers and generated binding code moved into a hot-update assembly. Use when the user combines HybridCLR with lua, js, ts, python, xlua, tolua, puerts, zlua, or ZenTS, or is moving script hot update to C#.
---
# Script languages
Doc: `guide/features/workwithscriptlanguage.md` in the HybridCLR documentation. Wrapper reservation rules are in `hybridclr-monopinvokecallback`. Do not restate them here.
HybridCLR is native C# hot update. It can sit beside an existing script stack while gameplay moves back to C#.
## Prefer ZLua / ZenTS
For a new scripting layer, use the official stacks instead of xlua or puerts.
- [ZLua](https://github.com/focus-creative-games/zlua) for Lua
- [ZenTS](https://github.com/focus-creative-games/zen-ts) for JavaScript / TypeScript
They talk to il2cpp directly. They do not need `[MonoPInvokeCallback]` or a wrapper quota. Use the path below only when the project is already on xlua, tolua, or puerts.
## Other script stacks
xlua, tolua, slua, puerts, and similar binders call C# from native through `[MonoPInvokeCallback]`. Before the player build:
1. Add `[ReversePInvokeWrapperGeneration(n)]` on signatures that will grow. The count must cover later hot updates, not only the callbacks that exist now.
2. Run `HybridCLR/Generate/All` (includes `ReversePInvokeWrapper`).
3. Put generated binding code in a **hot-update** assembly and register that assembly. Do not leave it where it will be compiled as AOT.
### xlua
xlua emits code into global `Assembly-CSharp` and ties it to runtime types with partial classes. The generated output usually has to be edited before it can live in a hot-update assembly. [HybridCLRXlua](https://gitee.com/ldr123/HybridCLRXlua) is a working reference. Follow that project's assembly split. Do not assume the stock xlua generator supports HybridCLR as-is.
### tolua, slua, puerts
Check three things: enough wrappers are reserved, generated code is in the hot-update module, and registration runs after the hot-update dll is loaded.
-47
View File
@@ -1,47 +0,0 @@
---
name: hybridclr-setup
description: >-
Install and initialize com.code-philosophy.hybridclr: pick a matching Unity and package version, add the package from git or a local Packages folder, run HybridCLR/Installer, and recover from git or network failures. Use when the user installs, upgrades, or initializes HybridCLR, or when install fails, git clone fails, or the player still uses stock IL2CPP.
---
# Install HybridCLR
Docs: `guide/setup/install.md` and `guide/setup/supported-platforms-and-unity-versions.md` in the HybridCLR documentation. Package and il2cpp branches come from this repo's `Data~/hybridclr_version.json`. Do not change those branches from memory.
## Versions
- **v9.x** supports Unity **2022.3.x** and **6000.x** except 6000.5.x. Use **v8.x** for 2019.4, 2020.3, and 2021.3.
- The package name is `com.code-philosophy.hybridclr`. Before v3.0.0 it was `com.focus-creative-games.hybridclr_unity`.
- Standalone players need the **IL2CPP** module (`Windows Build Support (IL2CPP)` or `Mac Build Support (IL2CPP)`). An editor that only has the iOS or Android module cannot build that Standalone player. Exporting an iOS Xcode project does not require a local signing certificate.
## Install the package
Either:
1. Package Manager → Add package from git URL: `https://gitee.com/focus-creative-games/hybridclr_unity.git` or the GitHub repo with the same name. Pin a tag with `#{tag}`, for example `#v9.0.0`.
2. Place the repo at `Packages/com.code-philosophy.hybridclr`.
## Initialize (required)
Installing the package does not replace libil2cpp.
1. **git** must be installed. Restart the Unity Editor and Hub after installing git. Restart the machine if git is on PATH but the installer still cannot find it.
2. Open `HybridCLR/Installer...` and use the default remote install. Success prints `安装成功` and the status becomes installed.
3. The installer clones the `hybridclr` and `il2cpp_plus` branches listed in `Data~/hybridclr_version.json` for the current Unity major version. Do not edit that file unless the user explicitly wants a non-matching version.
4. If git or the network is unavailable, merge a local libil2cpp that already contains HybridCLR, enable "copy libil2cpp from local" in the installer, and install. Merge `il2cpp_plus/libil2cpp` with `hybridclr/hybridclr` into the final libil2cpp (see the install doc).
Local install lands in `{project}/HybridCLRData/LocalIl2CppData-{platform}/`. The package sets `UNITY_IL2CPP_PATH` only for the **current Editor process**. Leave `useGlobalIl2cpp` off.
## Updates
After updating the package, run `HybridCLR/Installer` again. The installer clears `Library/Il2cppBuildCache`. If libil2cpp was replaced by hand, delete that cache or the player build keeps the old IL2CPP.
## Host tools
- Windows: Visual Studio 2022 or newer with the Unity game development and C++ game development workloads, plus git.
- Mac: macOS 12 or newer, Xcode 13 or newer, plus git and cmake.
## Do not
- Do not replace libil2cpp inside the Editor install unless the user explicitly wants a global install and accepts that other projects are affected and that every `Generate` must be copied back over the Editor libil2cpp.
- WebGL uses the same local install as other platforms.
+26 -145
View File
@@ -1,5 +1,9 @@
using DotNetDetour;
using DotNetDetour;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
namespace MonoHook
{
@@ -7,16 +11,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()
@@ -43,7 +47,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)
@@ -72,8 +76,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);
@@ -117,7 +121,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;
@@ -255,19 +259,10 @@ namespace MonoHook
0x00, 0x00, 0x00, 0x14, // B $val ; $val = (($dst - $src)/4) & 7FFFFFF
};
/// <summary>
/// B 指令的 imm26 是有符号数,以 4 字节为单位,可达范围是 -128MB ~ +128MB-4
/// </summary>
public const long MaxJmpOffset = (1L << 27) - 4;
public CodePatcher_arm64_near(IntPtr target, IntPtr replace, IntPtr proxy) : base(target, replace, proxy, s_jmpCode.Length)
{
if (Math.Abs((long)target - (long)replace) > MaxJmpOffset)
throw new ArgumentException("address offset of target and replace must not exceed ±128MB, please use CodePatcher_arm64_far instead");
// proxy 末尾要跳回 target,距离同样受 B 指令范围限制
if (proxy != IntPtr.Zero && Math.Abs((long)target - (long)proxy) > MaxJmpOffset)
throw new ArgumentException("address offset of target and proxy must not exceed ±128MB, please use CodePatcher_arm64_far instead");
if (Math.Abs((long)target - (long)replace) >= ((1 << 26) - 1) * 4)
throw new ArgumentException("address offset of target and replace must less than (1 << 26) - 1) * 4");
#if ENABLE_HOOK_DEBUG
Debug.Log($"CodePatcher_arm64: {PrintAddrs()}");
@@ -297,143 +292,29 @@ namespace MonoHook
}
/// <summary>
/// arm64 下距离超过 ±128MB 的跳转
/// 会覆盖 target 开头 4 条指令,并把它们原样搬到 proxy 执行,所以这 4 条指令里不能有 PC 相对寻址或跳转,否则拒绝 hook
/// arm64 远距离跳转
/// </summary>
public unsafe class CodePatcher_arm64_far : CodePatcher
{
private static readonly byte[] s_jmpCode = new byte[] // 16 bytes
private static readonly byte[] s_jmpCode = new byte[] // 20 bytes(字节数过多,太危险了,不建议使用)
{
/*
* LDR(literal): https://developer.arm.com/documentation/ddi0596/2021-09/Base-Instructions/LDR--literal---Load-Register--literal--
* ADR: https://developer.arm.com/documentation/ddi0596/2021-09/Base-Instructions/ADR--Form-PC-relative-address-
* BR: https://developer.arm.com/documentation/ddi0596/2021-09/Base-Instructions/BR--Branch-to-Register-
* X16/X17(IP0/IP1) 是 AAPCS64 规定的过程间临时寄存器,函数入口处本就允许被 veneer 改写,用来中转是安全的
*/
0x50, 0x00, 0x00, 0x58, // LDR X16, #8
0x00, 0x02, 0x1F, 0xD6, // BR X16
0x6A, 0x00, 0x00, 0x10, // ADR X10, #C
0x4A, 0x01, 0x40, 0xF9, // LDR X10, [X10,#0]
0x40, 0x01, 0x1F, 0xD6, // BR X10
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // $dst
};
private readonly int _scratchReg;
public CodePatcher_arm64_far(IntPtr target, IntPtr replace, IntPtr proxy) : base(target, replace, proxy, s_jmpCode.Length)
public CodePatcher_arm64_far(IntPtr target, IntPtr replace, IntPtr proxy, int jmpCodeSize) : base(target, replace, proxy, jmpCodeSize)
{
int insCount = s_jmpCode.Length / 4;
uint* ins = (uint*)_pTarget;
// 没有 proxy:被覆盖的指令不会再执行,只要求函数不短于 16 字节;函数入口处 X16 可以随意改写
if (proxy == IntPtr.Zero)
{
for (int i = 0; i < insCount - 1; i++)
{
if (IsFunctionEnd(ins[i]))
throw new ArgumentException($"can not hook target 0x{(long)target:x}: instruction {i} (0x{ins[i]:X8}) ends the function, it is shorter than {s_jmpCode.Length} bytes");
}
_scratchReg = 16;
#if ENABLE_HOOK_DEBUG
Debug.Log($"CodePatcher_arm64_far: {PrintAddrs()}, scratch: X{_scratchReg}");
#endif
return;
}
for (int i = 0; i < insCount; i++)
{
if (IsPcRelativeOrBranch(ins[i]))
throw new ArgumentException($"can not hook target 0x{(long)target:x}: instruction {i} (0x{ins[i]:X8}) is pc-relative or a branch, can not be relocated");
}
// proxy 执行完搬过去的指令后跳回 target 时会改写中转寄存器,X16/X17 里挑一个此时已经没用的
if (IsDeadAfter(ins, insCount, 16))
_scratchReg = 16;
else if (IsDeadAfter(ins, insCount, 17))
_scratchReg = 17;
else
throw new ArgumentException($"can not hook target 0x{(long)target:x}: X16 and X17 may both be live after the first {insCount} instructions " +
$"({ins[0]:X8} {ins[1]:X8} {ins[2]:X8} {ins[3]:X8})");
// proxy 要写入 32 字节(搬过去的 4 条指令 + 跳回 target),前 7 条里就出现 RET 说明 proxy 太短,会写坏后面的函数
uint* proxyIns = (uint*)_pProxy;
for (int i = 0; i < s_jmpCode.Length * 2 / 4 - 1; i++)
{
if ((proxyIns[i] & 0xFFFFFC1F) == 0xD65F0000) // RET Xn
throw new ArgumentException($"proxy method at 0x{(long)proxy:x} is too short for arm64 far jump (need {s_jmpCode.Length * 2} bytes), please fill some dummy code inside");
}
#if ENABLE_HOOK_DEBUG
Debug.Log($"CodePatcher_arm64_far: {PrintAddrs()}, scratch: X{_scratchReg}");
#endif
}
protected override unsafe byte[] GenJmpCode(void* jmpFrom, void* jmpTo)
{
byte[] ret = new byte[s_jmpCode.Length];
fixed (void* p = &ret[0])
{
uint* ptr = (uint*)p;
*ptr++ = 0x58000040u | (uint)_scratchReg; // LDR Xn, #8
*ptr++ = 0xD61F0000u | ((uint)_scratchReg << 5); // BR Xn
*(long*)ptr = (long)jmpTo;
}
return ret;
}
private static bool IsPcRelativeOrBranch(uint ins)
{
return (ins & 0x1F000000) == 0x10000000 // ADR / ADRP
|| (ins & 0x7C000000) == 0x14000000 // B / BL
|| (ins & 0xFF000000) == 0x54000000 // B.cond
|| (ins & 0x7E000000) == 0x34000000 // CBZ / CBNZ
|| (ins & 0x7E000000) == 0x36000000 // TBZ / TBNZ
|| (ins & 0x3B000000) == 0x18000000 // LDR / LDRSW / PRFM (literal)
|| (ins & 0xFE000000) == 0xD6000000; // BR / BLR / RET 等寄存器跳转
}
private static bool IsFunctionEnd(uint ins)
{
return (ins & 0xFFFFFC1F) == 0xD65F0000 // RET
|| (ins & 0xFFFFFC1F) == 0xD61F0000 // BR
|| (ins & 0xFC000000) == 0x14000000; // B
}
/// <summary>
/// 粗略判断:凡是可能放寄存器号的字段等于 reg 就算用到,宁可多判
/// </summary>
private static bool MayUseReg(uint ins, int reg)
{
uint r = (uint)reg;
return (ins & 0x1F) == r || ((ins >> 5) & 0x1F) == r || ((ins >> 10) & 0x1F) == r || ((ins >> 16) & 0x1F) == r;
}
/// <summary>
/// 判断执行完前 count 条指令后 reg 是否已经没用:
/// 1. 这几条指令根本没碰它:函数入口处 X16/X17 本就没有有效值(AAPCS64 允许 veneer 随意改写);
/// 2. 最后一次访问是 add/sub/mov 把它当源操作数读掉:mono 只把 IP0/IP1 当作单条 IR 内的临时寄存器,
/// 如大栈帧序言 movz x16, #size; sub x17, sp, x16; mov sp, x17。
/// 其它指令不区分读写,一律当作可能仍在用。
/// </summary>
private static bool IsDeadAfter(uint* ins, int count, int reg)
{
uint r = (uint)reg;
for (int i = count - 1; i >= 0; i--)
{
uint x = ins[i];
if (!MayUseReg(x, reg))
continue;
bool addSubImm = (x & 0x1F000000) == 0x11000000; // ADD/SUB (immediate),含 mov sp, xN
bool addSubLogicReg = (x & 0x1F000000) == 0x0B000000 // ADD/SUB (shifted / extended register)
|| (x & 0x1F000000) == 0x0A000000; // AND/ORR/EOR (shifted register),含 mov xd, xm
if (!addSubImm && !addSubLogicReg)
return false;
if ((x & 0x1F) == r) // Rd:被改写,值可能留到后面用
return false;
if (((x >> 5) & 0x1F) == r || (addSubLogicReg && ((x >> 16) & 0x1F) == r))
return true; // Rn / Rm:作为源操作数读掉
// 只是立即数字段恰好等于 reg,不算访问,继续往前看
}
return true;
throw new NotImplementedException();
}
}
}
+6 -2
View File
@@ -1,7 +1,11 @@
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEngine;
using System.Linq;
using System.IO;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace MonoHook
@@ -56,7 +60,7 @@ namespace MonoHook
var list = _hooks.Values.ToList();
foreach (var hook in list)
{
if (hook.tag == tag)
if(hook.tag == tag)
hook.Uninstall();
}
}
+10 -10
View File
@@ -1,4 +1,4 @@
#if !(UNITY_STANDALONE_OSX || UNITY_EDITOR_OSX)
#if !(UNITY_STANDALONE_OSX || UNITY_EDITOR_OSX)
using System;
using System.Collections.Generic;
using System.Reflection;
@@ -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_EDITOR_WIN || (!UNITY_EDITOR && UNITY_STANDALONE_WIN)
#if UNITY_STANDALONE_WIN || UNITY_EDITOR_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.ToLowerInvariant();
if (processorType.Contains("intel") || processorType.Contains("amd"))
string processorType = SystemInfo.processorType;
if (processorType.Contains("Intel") || processorType.Contains("AMD"))
return;
if (IntPtr.Size == 4)
@@ -223,7 +223,7 @@ namespace MonoHook
};
#if UNITY_EDITOR_WIN || (!UNITY_EDITOR && UNITY_STANDALONE_WIN)
#if UNITY_STANDALONE_WIN || UNITY_EDITOR_WIN
[Flags]
public enum Protection
{
+2 -16
View File
@@ -1,4 +1,4 @@
#if (UNITY_STANDALONE_OSX || UNITY_EDITOR_OSX)
#if (UNITY_STANDALONE_OSX || UNITY_EDITOR_OSX)
using System;
using System.Collections.Generic;
using System.Reflection;
@@ -16,11 +16,7 @@ namespace MonoHook
static HookUtils()
{
try
{
jit_write_protect_supported = pthread_jit_write_protect_supported_np() != 0;
}
catch { }
jit_write_protect_supported = pthread_jit_write_protect_supported_np() != 0;
PropertyInfo p_SystemPageSize = typeof(Environment).GetProperty("SystemPageSize");
if (p_SystemPageSize == null)
@@ -39,16 +35,6 @@ 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,36 +1,18 @@
// 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 MonoHook;

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using UnityEditor;
using UnityEngine;
using UnityEditor;
using System.Runtime.CompilerServices;
using MonoHook;
using HybridCLR.Editor.BuildProcessors;
using System.IO;
namespace HybridCLR.BuildProcessors.Hooks
namespace HybridCLR.MonoHook
{
#if UNITY_2021_1_OR_NEWER && !UNITY_2023_1_OR_NEWER
#if UNITY_2021 && UNITY_IOS
[InitializeOnLoad]
public class CopyStrippedAOTAssembliesHook
{
@@ -61,7 +43,7 @@ namespace HybridCLR.BuildProcessors.Hooks
return false;
}
UnityEngine.Debug.Log($"== StripAssembliesTo outputDir:{outputFolder}");
string outputStrippedDir = HybridCLR.SettingsUtil.GetAssembliesPostIl2CppStripDir(EditorUserBuildSettings.activeBuildTarget);
string outputStrippedDir = HybridCLR.Editor.SettingsUtil.GetAssembliesPostIl2CppStripDir(EditorUserBuildSettings.activeBuildTarget);
Directory.CreateDirectory(outputStrippedDir);
foreach (var aotDll in Directory.GetFiles(outputFolder, "*.dll"))
{
@@ -1,33 +1,18 @@
// 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 MonoHook;

using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.CompilerServices;
using UnityEditor;
using UnityEngine;
using UnityEditor;
using System.Runtime.CompilerServices;
using MonoHook;
using HybridCLR.Editor.BuildProcessors;
using System.IO;
namespace HybridCLR.BuildProcessors.Hooks
namespace HybridCLR.MonoHook
{
#if UNITY_2022
[InitializeOnLoad]
public class GetIl2CppFolderHook
{
@@ -67,4 +52,5 @@ namespace HybridCLR.BuildProcessors.Hooks
return null;
}
}
#endif
}
@@ -0,0 +1,57 @@
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
}
+47 -49
View File
@@ -1,4 +1,4 @@
using System;
using System;
using System.Runtime.InteropServices;
namespace DotNetDetour
@@ -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,20 +783,19 @@ 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)
@@ -804,7 +803,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);
@@ -820,7 +819,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;
@@ -834,41 +833,40 @@ namespace DotNetDetour
switch (mod)
{
case 0:
if (is64)
{
if (rm == 5)
{
ld.disp_size = 4;
case 0:
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;
{
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;
}
if (ld.disp_size > 0)
if (ld.disp_size>0)
{
ld.disp_offset = (byte)(p - (byte*)code);
p += ld.disp_size;
@@ -878,20 +876,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;
}
-21
View File
@@ -1,21 +0,0 @@
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.
-7
View File
@@ -1,7 +0,0 @@
fileFormatVersion: 2
guid: 9298d9b76a5b2074da06bd90eb3bb6fd
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
+13 -17
View File
@@ -6,11 +6,15 @@
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;
/*
@@ -106,9 +110,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();
@@ -214,23 +218,15 @@ namespace MonoHook
private void CreateCodePatcher()
{
long addrOffset = Math.Abs(_targetPtr.ToInt64() - _replacementPtr.ToInt64());
if (_proxyPtr != IntPtr.Zero)
long addrOffset = Math.Abs(_targetPtr.ToInt64() - _proxyPtr.ToInt64());
if(_proxyPtr != IntPtr.Zero)
addrOffset = Math.Max(addrOffset, Math.Abs(_targetPtr.ToInt64() - _proxyPtr.ToInt64()));
if (LDasm.IsARM())
{
if (IntPtr.Size == 8)
{
if (addrOffset <= CodePatcher_arm64_near.MaxJmpOffset)
_codePatcher = new CodePatcher_arm64_near(_targetPtr, _replacementPtr, _proxyPtr);
else
{
UnityEngine.Debug.Log($"[MonoHook] {targetMethod.DeclaringType.Name}.{targetMethod.Name}: address offset {addrOffset / (1024 * 1024)}MB exceeds ±128MB, use arm64 far jump");
_codePatcher = new CodePatcher_arm64_far(_targetPtr, _replacementPtr, _proxyPtr);
}
}
_codePatcher = new CodePatcher_arm64_near(_targetPtr, _replacementPtr, _proxyPtr);
else if (addrOffset < ((1 << 25) - 1))
_codePatcher = new CodePatcher_arm32_near(_targetPtr, _replacementPtr, _proxyPtr);
else if (addrOffset < ((1 << 27) - 1))
@@ -242,7 +238,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);
@@ -267,7 +263,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 -1
View File
@@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: c27fe11625b7eee46847a83a9897fdc0
guid: d26c8b77c84f09442a05f2c67e5e09b8
folderAsset: yes
DefaultImporter:
externalObjects: {}
+23
View File
@@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HybridCLR.Editor.ABI
{
public static class 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,5 +1,5 @@
fileFormatVersion: 2
guid: d2e4ca0a49975a84a8a72dbc70ec7795
guid: edeb86f4b5b13ca4cb0fe9d87ce509bb
MonoImporter:
externalObjects: {}
serializedVersion: 2
@@ -1,29 +1,13 @@
// 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;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace HybridCLR.Meta
namespace HybridCLR.Editor.ABI
{
public class MethodDesc : IEquatable<MethodDesc>
{
@@ -37,7 +21,7 @@ namespace HybridCLR.Meta
public void Init()
{
for (int i = 0; i < ParamInfos.Count; i++)
for(int i = 0; i < ParamInfos.Count; i++)
{
ParamInfos[i].Index = i;
}
@@ -47,7 +31,7 @@ namespace HybridCLR.Meta
public void TransfromSigTypes(Func<TypeInfo, bool, TypeInfo> transformer)
{
ReturnInfo.Type = transformer(ReturnInfo.Type, true);
foreach (var paramType in ParamInfos)
foreach(var paramType in ParamInfos)
{
paramType.Type = transformer(paramType.Type, false);
}
@@ -57,7 +41,7 @@ namespace HybridCLR.Meta
{
var n = new StringBuilder();
n.Append(ReturnInfo.Type.CreateSigName());
foreach (var param in ParamInfos)
foreach(var param in ParamInfos)
{
n.Append(param.Type.CreateSigName());
}
+49
View File
@@ -0,0 +1,49 @@
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 bool IsNative2ManagedByAddress => Type.PorType >= ParamOrReturnType.STRUCT_NOT_PASS_AS_VALUE;
public bool IsPassToManagedByAddress => Type.GetParamSlotNum() > 1;
public bool IsPassToNativeByAddress => Type.PorType == ParamOrReturnType.STRUCTURE_AS_REF_PARAM;
public string Native2ManagedParamValue(PlatformABI canv)
{
return IsPassToManagedByAddress ? $"(uint64_t)&__arg{Index}" : $"*(uint64_t*)&__arg{Index}";
}
public string Managed2NativeParamValue(PlatformABI canv)
{
return IsPassToNativeByAddress ? $"(uint64_t)(localVarBase+argVarIndexs[{Index}])" : $"*({Type.GetTypeName()}*)(localVarBase+argVarIndexs[{Index}])";
}
}
public class ReturnInfo
{
public TypeInfo Type { get; set; }
public bool IsVoid => Type.PorType == ParamOrReturnType.VOID;
public int GetParamSlotNum(PlatformABI canv)
{
return Type.GetParamSlotNum();
}
public override string ToString()
{
return Type.GetTypeName();
}
}
}
+43
View File
@@ -0,0 +1,43 @@
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,
ARM64_HFA_FLOAT_2,
VALUE_TYPE_SIZE_LESS_EQUAL_8,
I16, // 8 < size <= 16
STRUCT_NOT_PASS_AS_VALUE, // struct pass not as value
STRUCTURE_AS_REF_PARAM, // size > 16
ARM64_HFA_FLOAT_3,
ARM64_HFA_FLOAT_4,
ARM64_HFA_DOUBLE_2,
ARM64_HFA_DOUBLE_3,
ARM64_HFA_DOUBLE_4,
ARM64_HVA_8,
ARM64_HVA_16,
STRUCTURE_ALIGN1, // size > 16
STRUCTURE_ALIGN2,
STRUCTURE_ALIGN4,
STRUCTURE_ALIGN8,
SPECIAL_STRUCTURE_ALIGN1,
SPECIAL_STRUCTURE_ALIGN2,
SPECIAL_STRUCTURE_ALIGN4,
SPECIAL_STRUCTURE_ALIGN8,
}
}
+10
View File
@@ -0,0 +1,10 @@
namespace HybridCLR.Editor.ABI
{
public enum PlatformABI
{
Universal32,
Universal64,
Arm64,
WebGL32,
}
}
@@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: 6ce33c8e48da5a649b261ba3a60fd3b9
guid: b9f06ff0612105b4ea20e0309e759e24
MonoImporter:
externalObjects: {}
serializedVersion: 2
+138
View File
@@ -0,0 +1,138 @@
using dnlib.DotNet;
using HybridCLR.Editor.Meta;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HybridCLR.Editor.ABI
{
public class HFATypeInfo
{
public TypeSig Type { get; set; }
public int Count { get; set; }
}
public class TypeCreatorArm64 : TypeCreatorBase
{
public override bool IsArch32 => false;
protected override TypeInfo OptimizeSigType(TypeInfo type, bool returnType)
{
if (!type.IsGeneralValueType)
{
return type;
}
int typeSize = type.Size;
if (typeSize <= 8)
{
return TypeInfo.s_i8;
}
if (typeSize <= 16)
{
return TypeInfo.s_i16;
}
if (returnType)
{
return type.PorType != ParamOrReturnType.STRUCTURE_ALIGN1 ? new TypeInfo(ParamOrReturnType.STRUCTURE_ALIGN1, typeSize) : type;
}
return TypeInfo.s_ref;
}
private static bool IsNotHFAFastCheck(int typeSize)
{
return typeSize % 4 != 0 || typeSize > 32;
}
private static bool ComputHFATypeInfo0(TypeSig type, HFATypeInfo typeInfo)
{
TypeDef typeDef = type.ToTypeDefOrRef().ResolveTypeDefThrow();
List<TypeSig> klassInst = type.ToGenericInstSig()?.GenericArguments?.ToList();
GenericArgumentContext ctx = klassInst != null ? new GenericArgumentContext(klassInst, null) : null;
var fields = typeDef.Fields;// typeDef.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
foreach (FieldDef field in fields)
{
if (field.IsStatic)
{
continue;
}
TypeSig ftype = ctx != null ? MetaUtil.Inflate(field.FieldType, ctx) : field.FieldType;
switch (ftype.ElementType)
{
case ElementType.R4:
case ElementType.R8:
{
if (ftype == typeInfo.Type || typeInfo.Type == null)
{
typeInfo.Type = ftype;
++typeInfo.Count;
}
else
{
return false;
}
break;
}
case ElementType.ValueType:
{
if (!ComputHFATypeInfo0(ftype, typeInfo))
{
return false;
}
break;
}
case ElementType.GenericInst:
{
if (!ftype.IsValueType || !ComputHFATypeInfo0(ftype, typeInfo))
{
return false;
}
break;
}
default: return false;
}
}
return typeInfo.Count <= 4;
}
private static bool ComputHFATypeInfo(TypeSig type, int typeSize, out HFATypeInfo typeInfo)
{
typeInfo = new HFATypeInfo();
if (IsNotHFAFastCheck(typeSize))
{
return false;
}
bool ok = ComputHFATypeInfo0(type, typeInfo);
if (ok && typeInfo.Count >= 1 && typeInfo.Count <= 4)
{
int fieldSize = typeInfo.Type.ElementType == ElementType.R4 ? 4 : 8;
return typeSize == fieldSize * typeInfo.Count;
}
return false;
}
protected override bool TryCreateCustomValueTypeInfo(TypeSig type, int typeSize, int typeAligment, out TypeInfo typeInfo)
{
if (ComputHFATypeInfo(type, typeSize, out HFATypeInfo hfaTypeInfo))
{
bool isFloat = hfaTypeInfo.Type.ElementType == ElementType.R4;
switch (hfaTypeInfo.Count)
{
case 1: typeInfo = isFloat ? TypeInfo.s_r4 : TypeInfo.s_r8; break;
case 2: typeInfo = isFloat ? TypeInfo.s_vf2 : TypeInfo.s_vd2; break;
case 3: typeInfo = isFloat ? TypeInfo.s_vf3 : TypeInfo.s_vd3; break;
case 4: typeInfo = isFloat ? TypeInfo.s_vf4 : TypeInfo.s_vd4; break;
default: throw new NotSupportedException();
}
return true;
}
typeInfo = null;
return false;
}
}
}
@@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: 7e9e6a048682dcb4fab806251411f29f
guid: a22846b73022cb2458d1c40549ab6877
MonoImporter:
externalObjects: {}
serializedVersion: 2
+157
View File
@@ -0,0 +1,157 @@
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 abstract class TypeCreatorBase
{
public abstract bool IsArch32 { get; }
public TypeInfo GetNativeIntTypeInfo() => IsArch32 ? TypeInfo.s_i4 : TypeInfo.s_i8;
public ValueTypeSizeAligmentCalculator Calculator => IsArch32 ? ValueTypeSizeAligmentCalculator.Caculator32 : ValueTypeSizeAligmentCalculator.Caculator64;
private readonly Dictionary<TypeSig, (int, int)> _typeSizeCache = new Dictionary<TypeSig, (int, int)>(TypeEqualityComparer.Instance);
private readonly Dictionary<TypeSig, TypeInfo> _typeInfoCache = new Dictionary<TypeSig, TypeInfo>(TypeEqualityComparer.Instance);
public (int Size, int Aligment) ComputeSizeAndAligment(TypeSig t)
{
if (_typeSizeCache.TryGetValue(t, out var sizeAndAligment))
{
return sizeAndAligment;
}
sizeAndAligment = Calculator.SizeAndAligmentOf(t);
_typeSizeCache.Add(t, sizeAndAligment);
return sizeAndAligment;
}
public TypeInfo CreateTypeInfo(TypeSig type)
{
if (!_typeInfoCache.TryGetValue(type, out var typeInfo))
{
typeInfo = CreateTypeInfo0(type);
_typeInfoCache.Add(type, typeInfo);
}
return new TypeInfo(typeInfo.PorType, typeInfo.Size);
}
TypeInfo CreateTypeInfo0(TypeSig type)
{
type = type.RemovePinnedAndModifiers();
if (type.IsByRef)
{
return GetNativeIntTypeInfo();
}
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.U: return IsArch32 ? TypeInfo.s_u4 : TypeInfo.s_u8;
case ElementType.I:
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 GetNativeIntTypeInfo();
case ElementType.TypedByRef: return CreateValueType(type);
case ElementType.ValueType:
{
TypeDef typeDef = type.ToTypeDefOrRef().ResolveTypeDef();
if (typeDef == null)
{
throw new Exception($"type:{type} 未能找到定义。请尝试 `HybridCLR/Genergate/LinkXml`,然后Build一次生成AOT dll,再重新生成桥接函数");
}
if (typeDef.IsEnum)
{
return CreateTypeInfo(typeDef.GetEnumUnderlyingType());
}
return CreateValueType(type);
}
case ElementType.GenericInst:
{
GenericInstSig gis = (GenericInstSig)type;
if (!gis.GenericType.IsValueType)
{
return GetNativeIntTypeInfo();
}
TypeDef typeDef = gis.GenericType.ToTypeDefOrRef().ResolveTypeDef();
if (typeDef.IsEnum)
{
return CreateTypeInfo(typeDef.GetEnumUnderlyingType());
}
return CreateValueType(type);
}
default: throw new NotSupportedException($"{type.ElementType}");
}
}
protected static TypeInfo CreateGeneralValueType(TypeSig type, int size, int aligment)
{
System.Diagnostics.Debug.Assert(size % aligment == 0);
switch (aligment)
{
case 1: return new TypeInfo(ParamOrReturnType.STRUCTURE_ALIGN1, size);
case 2: return new TypeInfo(ParamOrReturnType.STRUCTURE_ALIGN2, size);
case 4: return new TypeInfo(ParamOrReturnType.STRUCTURE_ALIGN4, size);
case 8: return new TypeInfo(ParamOrReturnType.STRUCTURE_ALIGN8, size);
default: throw new NotSupportedException($"type:{type} not support aligment:{aligment}");
}
}
protected virtual bool TryCreateCustomValueTypeInfo(TypeSig type, int typeSize, int typeAligment, out TypeInfo typeInfo)
{
typeInfo = null;
return false;
}
protected TypeInfo CreateValueType(TypeSig type)
{
(int typeSize, int typeAligment) = ComputeSizeAndAligment(type);
if (TryCreateCustomValueTypeInfo(type, typeSize, typeAligment, out var typeInfo))
{
//Debug.Log($"[{GetType().Name}] CustomeValueType:{type} => {typeInfo.CreateSigName()}");
return typeInfo;
}
else
{
// 64位下结构体内存对齐规则是一样的
return CreateGeneralValueType(type, typeSize, typeAligment);
}
}
protected abstract TypeInfo OptimizeSigType(TypeInfo type, bool returnType);
public virtual void OptimizeMethod(MethodDesc method)
{
method.TransfromSigTypes(OptimizeSigType);
}
}
}
@@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: e721876312c6e1b4997df2e900f1d754
guid: b63c5bf995a6d624dbd10d9df6cb6a7a
MonoImporter:
externalObjects: {}
serializedVersion: 2
+23
View File
@@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HybridCLR.Editor.ABI
{
public static class TypeCreatorFactory
{
public static TypeCreatorBase CreateTypeCreator(PlatformABI abi)
{
switch(abi)
{
case PlatformABI.Arm64: return new TypeCreatorArm64();
case PlatformABI.Universal32: return new TypeCreatorUniversal32();
case PlatformABI.Universal64: return new TypeCreatorUniversal64();
case PlatformABI.WebGL32: return new TypeCreatorWebGL32();
default: throw new NotSupportedException(abi.ToString());
}
}
}
}
+11
View File
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: fe1634f74b7ca2e42bd07233b451cd94
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
+22
View File
@@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HybridCLR.Editor.ABI
{
public class TypeCreatorUniversal32 : TypeCreatorBase
{
public override bool IsArch32 => true;
protected override TypeInfo OptimizeSigType(TypeInfo type, bool returnType)
{
if (type.PorType > ParamOrReturnType.STRUCTURE_ALIGN1 && type.PorType <= ParamOrReturnType.STRUCTURE_ALIGN4)
{
return new TypeInfo(ParamOrReturnType.STRUCTURE_ALIGN1, type.Size);
}
return type;
}
}
}
+11
View File
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 1eb9e19189731a344aad024a43e795bc
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
+23
View File
@@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HybridCLR.Editor.ABI
{
public class TypeCreatorUniversal64 : TypeCreatorBase
{
public override bool IsArch32 => false;
protected override TypeInfo OptimizeSigType(TypeInfo type, bool returnType)
{
if (type.PorType > ParamOrReturnType.STRUCTURE_ALIGN1 && type.PorType <= ParamOrReturnType.STRUCTURE_ALIGN8)
{
return new TypeInfo(ParamOrReturnType.STRUCTURE_ALIGN1, type.Size);
}
return type;
}
}
}
+11
View File
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 7867dfe20d27e324e90bc13b9d4f05bb
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
+220
View File
@@ -0,0 +1,220 @@
using dnlib.DotNet;
using HybridCLR.Editor.Meta;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HybridCLR.Editor.ABI
{
public class SingletonStruct
{
public TypeSig Type { get; set; }
}
public class TypeCreatorWebGL32 : TypeCreatorBase
{
public override bool IsArch32 => true;
protected override TypeInfo OptimizeSigType(TypeInfo type, bool returnType)
{
//if (type.PorType > ParamOrReturnType.STRUCTURE_ALIGN1 && type.PorType <= ParamOrReturnType.STRUCTURE_ALIGN4)
//{
// return new TypeInfo(ParamOrReturnType.STRUCTURE_ALIGN1, type.Size);
//}
return type;
}
private static bool IsEmptyOrSpeicalValueType(TypeSig type)
{
TypeDef typeDef = type.ToTypeDefOrRef().ResolveTypeDefThrow();
if (typeDef.IsEnum)
{
return false;
}
var fields = typeDef.Fields;// typeDef.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (fields.Count == 0)
{
return true;
}
if (fields.All(f => f.IsStatic))
{
return true;
}
if (typeDef.IsExplicitLayout && fields.Count(f => !f.IsStatic) > 1)
{
return true;
}
return false;
}
public static bool TryComputSingletonStructTypeInfo(TypeSig type, int typeAligment, int typeSize, out TypeInfo typeInfo)
{
typeInfo = null;
if (typeAligment > 8 || typeSize > 8)
{
return false;
}
var ss = new SingletonStruct();
if (!TryComputSingletonStruct0(type, ss) || ss.Type == null)
{
return false;
}
if (ss.Type.IsByRef)
{
typeInfo = TypeInfo.s_i4;
return true;
}
switch (ss.Type.ElementType)
{
case ElementType.Boolean:
case ElementType.Char:
case ElementType.I1:
case ElementType.U1:
case ElementType.I2:
case ElementType.U2:
case ElementType.I4:
case ElementType.U4:
case ElementType.I:
case ElementType.U:
case ElementType.String:
case ElementType.Ptr:
case ElementType.Class:
case ElementType.Array:
case ElementType.GenericInst:
case ElementType.FnPtr:
case ElementType.Object:
case ElementType.SZArray:
{
if (typeAligment <= 4 && typeSize <= 4)
{
typeInfo = TypeInfo.s_i4;
}
break;
}
case ElementType.I8:
case ElementType.U8:
{
if (typeAligment <= 8 && typeSize <= 8)
{
typeInfo = TypeInfo.s_i8;
}
break;
}
case ElementType.R4:
{
if (typeAligment <= 4 && typeSize <= 4)
{
typeInfo = TypeInfo.s_r4;
}
break;
}
case ElementType.R8:
{
if (typeAligment <= 8 && typeSize <= 8)
{
typeInfo = TypeInfo.s_r8;
}
break;
}
default: return false;
}
return typeInfo != null;
}
public static bool TryComputSingletonStruct(TypeSig type, out SingletonStruct result)
{
result = new SingletonStruct();
return TryComputSingletonStruct0(type, result) && result.Type != null;
}
public static bool TryComputSingletonStruct0(TypeSig type, SingletonStruct result)
{
TypeDef typeDef = type.ToTypeDefOrRef().ResolveTypeDefThrow();
if (typeDef.IsEnum)
{
if (result.Type == null)
{
result.Type = typeDef.GetEnumUnderlyingType();
return true;
}
else
{
return false;
}
}
List<TypeSig> klassInst = type.ToGenericInstSig()?.GenericArguments?.ToList();
GenericArgumentContext ctx = klassInst != null ? new GenericArgumentContext(klassInst, null) : null;
var fields = typeDef.Fields;// typeDef.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
foreach (FieldDef field in fields)
{
if (field.IsStatic)
{
continue;
}
TypeSig ftype = ctx != null ? MetaUtil.Inflate(field.FieldType, ctx) : field.FieldType;
switch (ftype.ElementType)
{
case ElementType.TypedByRef: return false;
case ElementType.ValueType:
{
if (!TryComputSingletonStruct0(ftype, result))
{
return false;
}
break;
}
case ElementType.GenericInst:
{
if (!ftype.IsValueType)
{
goto default;
}
if (!TryComputSingletonStruct0(ftype, result))
{
return false;
}
break;
}
default:
{
if (result.Type != null)
{
return false;
}
result.Type = ftype;
break;
}
}
}
return true;
}
protected override bool TryCreateCustomValueTypeInfo(TypeSig type, int typeSize, int typeAligment, out TypeInfo typeInfo)
{
typeInfo = null;
if (IsEmptyOrSpeicalValueType(type))
{
switch (typeAligment)
{
case 1: typeInfo = new TypeInfo(ParamOrReturnType.SPECIAL_STRUCTURE_ALIGN1, typeSize); break;
case 2: typeInfo = new TypeInfo(ParamOrReturnType.SPECIAL_STRUCTURE_ALIGN2, typeSize); break;
case 4: typeInfo = new TypeInfo(ParamOrReturnType.SPECIAL_STRUCTURE_ALIGN4, typeSize); break;
case 8: typeInfo = new TypeInfo(ParamOrReturnType.SPECIAL_STRUCTURE_ALIGN8, typeSize); break;
default: throw new NotSupportedException();
}
return true;
}
if (TryComputSingletonStructTypeInfo(type, typeAligment, typeSize, out typeInfo))
{
return true;
}
return false;
}
}
}
+11
View File
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 4790a87aacda1a14d813570e9e0f35ca
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
+167
View File
@@ -0,0 +1,167 @@
using dnlib.DotNet;
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_i16 = new TypeInfo(ParamOrReturnType.I16);
public static readonly TypeInfo s_ref = new TypeInfo(ParamOrReturnType.STRUCTURE_AS_REF_PARAM);
public static readonly TypeInfo s_vf2 = new TypeInfo(ParamOrReturnType.ARM64_HFA_FLOAT_2);
public static readonly TypeInfo s_vf3 = new TypeInfo(ParamOrReturnType.ARM64_HFA_FLOAT_3);
public static readonly TypeInfo s_vf4 = new TypeInfo(ParamOrReturnType.ARM64_HFA_FLOAT_4);
public static readonly TypeInfo s_vd2 = new TypeInfo(ParamOrReturnType.ARM64_HFA_DOUBLE_2);
public static readonly TypeInfo s_vd3 = new TypeInfo(ParamOrReturnType.ARM64_HFA_DOUBLE_3);
public static readonly TypeInfo s_vd4 = new TypeInfo(ParamOrReturnType.ARM64_HFA_DOUBLE_4);
public TypeInfo(ParamOrReturnType portype)
{
PorType = portype;
Size = 0;
}
public TypeInfo(ParamOrReturnType portype, int size)
{
PorType = portype;
Size = size;
}
public ParamOrReturnType PorType { get; }
public bool IsGeneralValueType => PorType >= ParamOrReturnType.STRUCTURE_ALIGN1 && PorType <= ParamOrReturnType.STRUCTURE_ALIGN8;
public int Size { get; }
public bool Equals(TypeInfo other)
{
return PorType == other.PorType && Size == other.Size;
}
public override bool Equals(object obj)
{
return Equals((TypeInfo)obj);
}
public override int GetHashCode()
{
return (int)PorType * 23 + Size;
}
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.I16: return "i16";
case ParamOrReturnType.STRUCTURE_AS_REF_PARAM: return "sr";
case ParamOrReturnType.ARM64_HFA_FLOAT_2: return "vf2";
case ParamOrReturnType.ARM64_HFA_FLOAT_3: return "vf3";
case ParamOrReturnType.ARM64_HFA_FLOAT_4: return "vf4";
case ParamOrReturnType.ARM64_HFA_DOUBLE_2: return "vd2";
case ParamOrReturnType.ARM64_HFA_DOUBLE_3: return "vd3";
case ParamOrReturnType.ARM64_HFA_DOUBLE_4: return "vd4";
case ParamOrReturnType.STRUCTURE_ALIGN1: return "S" + Size;
case ParamOrReturnType.STRUCTURE_ALIGN2: return "A" + Size;
case ParamOrReturnType.STRUCTURE_ALIGN4: return "B" + Size;
case ParamOrReturnType.STRUCTURE_ALIGN8: return "C" + Size;
case ParamOrReturnType.SPECIAL_STRUCTURE_ALIGN1: return "X" + Size;
case ParamOrReturnType.SPECIAL_STRUCTURE_ALIGN2: return "Y" + Size;
case ParamOrReturnType.SPECIAL_STRUCTURE_ALIGN4: return "Z" + Size;
case ParamOrReturnType.SPECIAL_STRUCTURE_ALIGN8: return "W" + Size;
default: throw new NotSupportedException(PorType.ToString());
};
}
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.I16: return "ValueTypeSize16";
case ParamOrReturnType.STRUCTURE_AS_REF_PARAM: return "uint64_t";
case ParamOrReturnType.ARM64_HFA_FLOAT_2: return "HtVector2f";
case ParamOrReturnType.ARM64_HFA_FLOAT_3: return "HtVector3f";
case ParamOrReturnType.ARM64_HFA_FLOAT_4: return "HtVector4f";
case ParamOrReturnType.ARM64_HFA_DOUBLE_2: return "HtVector2d";
case ParamOrReturnType.ARM64_HFA_DOUBLE_3: return "HtVector3d";
case ParamOrReturnType.ARM64_HFA_DOUBLE_4: return "HtVector4d";
case ParamOrReturnType.STRUCTURE_ALIGN1: return $"ValueTypeSize<{Size}>";
case ParamOrReturnType.STRUCTURE_ALIGN2: return $"ValueTypeSizeAlign2<{Size}>";
case ParamOrReturnType.STRUCTURE_ALIGN4: return $"ValueTypeSizeAlign4<{Size}>";
case ParamOrReturnType.STRUCTURE_ALIGN8: return $"ValueTypeSizeAlign8<{Size}>";
case ParamOrReturnType.SPECIAL_STRUCTURE_ALIGN1: return $"WebGLSpeicalValueType<{Size}>";
case ParamOrReturnType.SPECIAL_STRUCTURE_ALIGN2: return $"WebGLSpeicalValueTypeAlign2<{Size}>";
case ParamOrReturnType.SPECIAL_STRUCTURE_ALIGN4: return $"WebGLSpeicalValueTypeAlign4<{Size}>";
case ParamOrReturnType.SPECIAL_STRUCTURE_ALIGN8: return $"WebGLSpeicalValueTypeAlign8<{Size}>";
default: throw new NotImplementedException(PorType.ToString());
};
}
public int GetParamSlotNum()
{
switch (PorType)
{
case ParamOrReturnType.VOID: return 0;
case ParamOrReturnType.I16: return 2;
case ParamOrReturnType.STRUCTURE_AS_REF_PARAM: return 1;
case ParamOrReturnType.ARM64_HFA_FLOAT_3: return 2;
case ParamOrReturnType.ARM64_HFA_FLOAT_4: return 2;
case ParamOrReturnType.ARM64_HFA_DOUBLE_2: return 2;
case ParamOrReturnType.ARM64_HFA_DOUBLE_3: return 3;
case ParamOrReturnType.ARM64_HFA_DOUBLE_4: return 4;
case ParamOrReturnType.ARM64_HVA_8:
case ParamOrReturnType.ARM64_HVA_16: throw new NotSupportedException();
case ParamOrReturnType.STRUCTURE_ALIGN1:
case ParamOrReturnType.STRUCTURE_ALIGN2:
case ParamOrReturnType.STRUCTURE_ALIGN4:
case ParamOrReturnType.STRUCTURE_ALIGN8:
case ParamOrReturnType.SPECIAL_STRUCTURE_ALIGN1:
case ParamOrReturnType.SPECIAL_STRUCTURE_ALIGN2:
case ParamOrReturnType.SPECIAL_STRUCTURE_ALIGN4:
case ParamOrReturnType.SPECIAL_STRUCTURE_ALIGN8:
return (Size + 7) / 8;
default:
{
Debug.Assert(PorType < ParamOrReturnType.STRUCT_NOT_PASS_AS_VALUE);
Debug.Assert(Size <= 8);
return 1;
}
}
}
}
}
@@ -0,0 +1,181 @@
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());
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: b7af32bdf1cf55c42bfc449820d401cb
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,49 +1,28 @@
// 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.Meta;
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.CodeGen.AOT
namespace HybridCLR.Editor.AOT
{
public class AOTReferenceAnalyzer
public class Analyzer
{
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>();
@@ -64,11 +43,10 @@ namespace HybridCLR.CodeGen.AOT
public List<GenericMethod> AotGenericMethods { get; } = new List<GenericMethod>();
public AOTReferenceAnalyzer(Options options)
public Analyzer(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"));
}
@@ -93,7 +71,7 @@ namespace HybridCLR.CodeGen.AOT
private bool IsAotType(TypeDef type)
{
return _computeAotAssembly || !_hotUpdateAssemblyFiles.Contains(type.Module.Name);
return !_hotUpdateAssemblyFiles.Contains(type.Module.Name);
}
private bool IsAotGenericMethod(MethodDef method)
@@ -103,7 +81,7 @@ namespace HybridCLR.CodeGen.AOT
private void OnNewMethod(MethodDef methodDef, List<TypeSig> klassGenericInst, List<TypeSig> methodGenericInst, GenericMethod method)
{
if (method == null)
if(method == null)
{
return;
}
@@ -167,8 +145,8 @@ namespace HybridCLR.CodeGen.AOT
private void Prepare()
{
// Add all non-generic methods to the list and walk them immediately.
// Later iterations only walk MethodSpec entries
// 将所有非泛型函数全部加入函数列表,同时立马walk这些method。
// 后续迭代中将只遍历MethodSpec
foreach (var ass in _assemblyCollector.GetLoadedModulesOfRootAssemblies())
{
foreach (TypeDef typeDef in ass.GetTypes())
@@ -213,29 +191,11 @@ namespace HybridCLR.CodeGen.AOT
}
}
private bool IsNotShareableAOTGenericType(TypeDef typeDef)
{
if (!IsAotType(typeDef))
{
return false;
}
return typeDef.GenericParameters.Any(c => !c.HasReferenceTypeConstraint);
}
private bool IsNotShareableAOTGenericMethod(MethodDef method)
{
if (!IsAotGenericMethod(method))
{
return false;
}
return method.GenericParameters.Concat(method.DeclaringType.GenericParameters).Any(c => !c.HasReferenceTypeConstraint);
}
private void FilterAOTGenericTypeAndMethods()
{
ConstraintContext cc = this.ConstraintContext;
AotGenericTypes.AddRange(_genericTypes.Where(type => IsNotShareableAOTGenericType(type.Type)).Select(gc => cc.ApplyConstraints(gc)));
AotGenericMethods.AddRange(_genericMethods.Where(method => IsNotShareableAOTGenericMethod(method.Method)).Select(gm => cc.ApplyConstraints(gm)));
AotGenericTypes.AddRange(_genericTypes.Where(type => IsAotType(type.Type)).Select(gc => cc.ApplyConstraints(gc)));
AotGenericMethods.AddRange(_genericMethods.Where(method => IsAotGenericMethod(method.Method)).Select(gm => cc.ApplyConstraints(gm)));
}
public void Run()
@@ -1,29 +1,12 @@
// 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.Meta;
using HybridCLR.Utils;
using dnlib.DotNet;
using HybridCLR.Editor.Meta;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HybridCLR.CodeGen.AOT
namespace HybridCLR.Editor.AOT
{
public class ConstraintContext
@@ -60,7 +43,7 @@ namespace HybridCLR.CodeGen.AOT
}
private int ComputHash()
{
{
int hash = 0;
if (BaseType != null)
{
@@ -1,35 +1,16 @@
// 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 HybridCLR.Editor.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.CodeGen.AOT
namespace HybridCLR.Editor.AOT
{
public class AOTGenericReferenceWriter
public class GenericReferenceWriter
{
private static readonly Dictionary<Type, string> _typeNameMapping = new Dictionary<Type, string>
{
@@ -52,13 +33,13 @@ namespace HybridCLR.CodeGen.AOT
private readonly Regex _systemTypePattern;
private readonly Regex _genericPattern = new Regex(@"`\d+");
public AOTGenericReferenceWriter()
public GenericReferenceWriter()
{
foreach (var e in _typeNameMapping)
{
_typeSimpleNameMapping.Add(e.Key.FullName, e.Value);
}
_systemTypePattern = new Regex(string.Join("|", _typeSimpleNameMapping.Keys.Select(k => $@"\b{Regex.Escape(k)}\b")));
_systemTypePattern = new Regex(string.Join("|", _typeSimpleNameMapping.Keys.Select (k => $@"\b{k}\b")));
}
public string PrettifyTypeSig(string typeSig)
@@ -82,49 +63,47 @@ namespace HybridCLR.CodeGen.AOT
string parentDir = Directory.GetParent(outputFile).FullName;
Directory.CreateDirectory(parentDir);
var cw = new CodeWriter();
cw.WriteLine("using System.Collections.Generic;");
cw.WriteLine("public class AOTGenericReferences : UnityEngine.MonoBehaviour");
cw.WriteLine("{");
cw.IncreaseIndent();
List<string> codes = new List<string>();
codes.Add("using System.Collections.Generic;");
codes.Add("public class AOTGenericReferences : UnityEngine.MonoBehaviour");
codes.Add("{");
cw.WriteLine();
cw.WriteLine("// {{ AOT assemblies");
cw.WriteLine("public static readonly IReadOnlyList<string> PatchedAOTAssemblyList = new List<string>");
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{");
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)
{
cw.WriteLine($"\"{module.Name}\",");
codes.Add($"\t\t\"{module.Name}\",");
}
cw.DecreaseIndent();
cw.WriteLine("};");
cw.WriteLine("// }}");
codes.Add("\t};");
codes.Add("\t// }}");
cw.WriteLine();
cw.WriteLine("// {{ constraint implement type");
cw.WriteLine("// }} ");
cw.WriteLine();
cw.WriteLine("// {{ AOT generic types");
codes.Add("");
codes.Add("\t// {{ constraint implement type");
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)
{
cw.WriteLine($"// {typeName}");
codes.Add($"\t// {typeName}");
}
cw.WriteLine("// }}");
cw.WriteLine();
cw.WriteLine("public void RefMethods()");
cw.WriteLine("{");
cw.IncreaseIndent();
codes.Add("\t// }}");
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();
@@ -143,17 +122,18 @@ namespace HybridCLR.CodeGen.AOT
}
return String.Compare(a.Item3, b.Item3, StringComparison.Ordinal);
});
foreach (var method in methodTypeAndNames)
foreach(var method in methodTypeAndNames)
{
cw.WriteLine($"// {PrettifyMethodSig(method.Item3)}");
codes.Add($"\t\t// {PrettifyMethodSig(method.Item3)}");
}
cw.DecreaseIndent();
cw.WriteLine("}");
codes.Add("\t}");
cw.DecreaseIndent();
cw.WriteLine("}");
codes.Add("}");
cw.Save(outputFile);
var utf8WithoutBom = new System.Text.UTF8Encoding(false);
File.WriteAllText(outputFile, string.Join("\n", codes), utf8WithoutBom);
Debug.Log($"[GenericReferenceWriter] write {outputFile}");
}
}
}
@@ -0,0 +1,256 @@
using System;
using HybridCLR.Editor.Installer;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using UnityEditor;
#if (UNITY_2020 || UNITY_2021) && UNITY_IOS
using UnityEditor.Build;
using UnityEditor.Callbacks;
using UnityEditor.iOS.Xcode;
using UnityEngine;
namespace HybridCLR.Editor
{
public static class AddLil2cppSourceCodeToXcodeproj2021OrOlder
{
//[MenuItem("Test/GenProj")]
//public static void Modify()
//{
// OnPostProcessBuild(BuildTarget.iOS, $"{SettingsUtil.ProjectDir}/Build-iOS");
//}
//[MenuItem("Test/CreateLumps")]
//public static void CreateLumpsCmd()
//{
// CreateLumps($"{SettingsUtil.LocalIl2CppDir}/libil2cpp", $"{SettingsUtil.HybridCLRDataDir}/lumps");
//}
[PostProcessBuild]
public static void OnPostProcessBuild(BuildTarget target, string pathToBuiltProject)
{
if (target != BuildTarget.iOS || !HybridCLRSettings.Instance.enable)
return;
/*
* 1. 生成lump,并且添加到工程
3. 将libil2cpp目录复制到 Library/. 删除旧的. search paths里修改 libil2cpp/include为libil2cpp
3. Libraries/bdwgc/include -> Libraries/external/bdwgc/include
4. 将external目录复制到 Library/external。删除旧目录
5. 将Library/external/baselib/Platforms/OSX改名为 IOS 全大写
6. 将 external/zlib下c 文件添加到工程
7. 移除libil2cpp.a
8. Include path add libil2cpp/os/ClassLibraryPAL/brotli/include
9. add external/xxHash
*/
string pbxprojFile = $"{pathToBuiltProject}/Unity-iPhone.xcodeproj/project.pbxproj";
string srcLibil2cppDir = $"{SettingsUtil.LocalIl2CppDir}/libil2cpp";
string dstLibil2cppDir = $"{pathToBuiltProject}/Libraries/libil2cpp";
string lumpDir = $"{pathToBuiltProject}/Libraries/lumps";
string srcExternalDir = $"{SettingsUtil.LocalIl2CppDir}/external";
string dstExternalDir = $"{pathToBuiltProject}/Libraries/external";
//RemoveExternalLibil2cppOption(srcExternalDir, dstExternalDir);
CopyLibil2cppToXcodeProj(srcLibil2cppDir, dstLibil2cppDir);
CopyExternalToXcodeProj(srcExternalDir, dstExternalDir);
var lumpFiles = CreateLumps(dstLibil2cppDir, lumpDir);
var extraSources = GetExtraSourceFiles(dstExternalDir, dstLibil2cppDir);
var cflags = new List<string>()
{
"-DIL2CPP_MONO_DEBUGGER_DISABLED",
};
ModifyPBXProject(pathToBuiltProject, pbxprojFile, lumpFiles, extraSources, cflags);
}
private static string GetRelativePathFromProj(string path)
{
return path.Substring(path.IndexOf("Libraries", StringComparison.Ordinal)).Replace('\\', '/');
}
private static void ModifyPBXProject(string pathToBuiltProject, string pbxprojFile, List<LumpFile> lumpFiles, List<string> extraFiles, List<string> cflags)
{
var proj = new PBXProject();
proj.ReadFromFile(pbxprojFile);
string targetGUID = proj.GetUnityFrameworkTargetGuid();
// 移除旧的libil2cpp.a
var libil2cppGUID = proj.FindFileGuidByProjectPath("Libraries/libil2cpp.a");
if (!string.IsNullOrEmpty(libil2cppGUID))
{
proj.RemoveFileFromBuild(targetGUID, libil2cppGUID);
proj.RemoveFile(libil2cppGUID);
File.Delete(Path.Combine(pathToBuiltProject, "Libraries", "libil2cpp.a"));
}
//var lumpGroupGuid = proj.AddFile("Lumps", $"Classes/Lumps", PBXSourceTree.Group);
foreach (var lumpFile in lumpFiles)
{
string lumpFileName = Path.GetFileName(lumpFile.lumpFile);
string projPathOfFile = $"Classes/Lumps/{lumpFileName}";
string relativePathOfFile = GetRelativePathFromProj(lumpFile.lumpFile);
string lumpGuid = proj.FindFileGuidByProjectPath(projPathOfFile);
if (!string.IsNullOrEmpty(lumpGuid))
{
proj.RemoveFileFromBuild(targetGUID, lumpGuid);
proj.RemoveFile(lumpGuid);
}
lumpGuid = proj.AddFile(relativePathOfFile, projPathOfFile, PBXSourceTree.Source);
proj.AddFileToBuild(targetGUID, lumpGuid);
}
foreach (var extraFile in extraFiles)
{
string projPathOfFile = $"Classes/Extrals/{Path.GetFileName(extraFile)}";
string extraFileGuid = proj.FindFileGuidByProjectPath(projPathOfFile);
if (!string.IsNullOrEmpty(extraFileGuid))
{
proj.RemoveFileFromBuild(targetGUID, extraFileGuid);
proj.RemoveFile(extraFileGuid);
//Debug.LogWarning($"remove exist extra file:{projPathOfFile} guid:{extraFileGuid}");
}
var lumpGuid = proj.AddFile(GetRelativePathFromProj(extraFile), projPathOfFile, PBXSourceTree.Source);
proj.AddFileToBuild(targetGUID, lumpGuid);
}
foreach(var configName in proj.BuildConfigNames())
{
//Debug.Log($"build config:{bcn}");
string configGuid = proj.BuildConfigByName(targetGUID, configName);
string headerSearchPaths = "HEADER_SEARCH_PATHS";
string hspProp = proj.GetBuildPropertyForConfig(configGuid, headerSearchPaths);
//Debug.Log($"config guid:{configGuid} prop:{hspProp}");
string newPro = hspProp.Replace("libil2cpp/include", "libil2cpp")
.Replace("Libraries/bdwgc", "Libraries/external/bdwgc");
if (!newPro.Contains("Libraries/libil2cpp/os/ClassLibraryPAL/brotli/include"))
{
newPro += " $(SRCROOT)/Libraries/libil2cpp/os/ClassLibraryPAL/brotli/include";
}
if (!newPro.Contains("Libraries/external/xxHash"))
{
newPro += " $(SRCROOT)/Libraries/external/xxHash";
}
//Debug.Log($"config:{bcn} new prop:{newPro}");
proj.SetBuildPropertyForConfig(configGuid, headerSearchPaths, newPro);
string cflagKey = "OTHER_CFLAGS";
string cfProp = proj.GetBuildPropertyForConfig(configGuid, cflagKey);
foreach (var flag in cflags)
{
if (!cfProp.Contains(flag))
{
cfProp += " " + flag;
}
}
if (configName.Contains("Debug") && !cfProp.Contains("-DIL2CPP_DEBUG="))
{
cfProp += " -DIL2CPP_DEBUG=1 -DDEBUG=1";
}
proj.SetBuildPropertyForConfig(configGuid, cflagKey, cfProp);
}
proj.WriteToFile(pbxprojFile);
}
private static void CopyLibil2cppToXcodeProj(string srcLibil2cppDir, string dstLibil2cppDir)
{
BashUtil.RemoveDir(dstLibil2cppDir);
BashUtil.CopyDir(srcLibil2cppDir, dstLibil2cppDir, true);
}
private static void CopyExternalToXcodeProj(string srcExternalDir, string dstExternalDir)
{
BashUtil.RemoveDir(dstExternalDir);
BashUtil.CopyDir(srcExternalDir, dstExternalDir, true);
string baselibPlatfromsDir = $"{dstExternalDir}/baselib/Platforms";
BashUtil.RemoveDir($"{baselibPlatfromsDir}/IOS");
BashUtil.CopyDir($"{baselibPlatfromsDir}/OSX", $"{baselibPlatfromsDir}/IOS", true);
}
class LumpFile
{
public List<string> cppFiles = new List<string>();
public readonly string lumpFile;
public readonly string il2cppConfigFile;
public LumpFile(string lumpFile, string il2cppConfigFile)
{
this.lumpFile = lumpFile;
this.il2cppConfigFile = il2cppConfigFile;
this.cppFiles.Add(il2cppConfigFile);
}
public void SaveFile()
{
var lumpFileContent = new List<string>();
foreach (var file in cppFiles)
{
lumpFileContent.Add($"#include \"{GetRelativePathFromProj(file)}\"");
}
File.WriteAllLines(lumpFile, lumpFileContent, Encoding.UTF8);
Debug.Log($"create lump file:{lumpFile}");
}
}
private static List<LumpFile> CreateLumps(string libil2cppDir, string outputDir)
{
BashUtil.RecreateDir(outputDir);
var cppFiles = Directory.GetFiles(libil2cppDir, "*.cpp", SearchOption.AllDirectories);
int maxCppFilePerLump = 50;
string il2cppConfigFile = $"{libil2cppDir}/il2cpp-config.h";
var lumpFiles = new List<LumpFile>();
for (int i = 0; i < (cppFiles.Length + maxCppFilePerLump - 1) / maxCppFilePerLump; i++)
{
var lumpFile = new LumpFile($"{outputDir}/lump_{i}.cpp", il2cppConfigFile);
for (int j = 0; j < maxCppFilePerLump; j++)
{
int index = i * maxCppFilePerLump + j;
if (index >= cppFiles.Length)
{
break;
}
lumpFile.cppFiles.Add(cppFiles[index]);
}
lumpFile.SaveFile();
lumpFiles.Add(lumpFile);
}
var mmFiles = Directory.GetFiles(libil2cppDir, "*.mm", SearchOption.AllDirectories);
if (mmFiles.Length > 0)
{
var lumpFile = new LumpFile($"{outputDir}/lump_mm.mm", il2cppConfigFile);
foreach (var file in mmFiles)
{
lumpFile.cppFiles.Add(file);
}
lumpFile.SaveFile();
lumpFiles.Add(lumpFile);
}
return lumpFiles;
}
private static List<string> GetExtraSourceFiles(string externalDir, string libil2cppDir)
{
var files = new List<string>();
foreach (string extraDir in new string[]
{
$"{externalDir}/zlib",
$"{externalDir}/xxHash",
$"{libil2cppDir}/os/ClassLibraryPAL/brotli",
})
{
if (!Directory.Exists(extraDir))
{
continue;
}
files.AddRange(Directory.GetFiles(extraDir, "*.c", SearchOption.AllDirectories));
}
return files;
}
}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 61948fcb1bc40ba47b8c10b0ae801ebb
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,102 +1,56 @@
// 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 HybridCLR.Utils;
using HybridCLR.Editor.Installer;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEditor.Build;
using UnityEditor.Callbacks;
using UnityEngine;
#if UNITY_2022_2_OR_NEWER && UNITY_IOS
namespace HybridCLR.BuildProcessors
namespace HybridCLR.Editor
{
public static class AddLil2cppSourceCodeToXcodeproj2022OrNewer
{
//[MenuItem("HybridCLR/Modfiyxcode")]
//public static void Modify()
//{
// OnPostProcessBuild(BuildTarget.iOS, $"{SettingsUtil.ProjectDir}/Build-iOS");
//}
#if UNITY_2022 && (UNITY_IOS || UNITY_TVOS || UNITY_VISIONOS)
[PostProcessBuild]
#endif
public static void OnPostProcessBuild(BuildTarget target, string pathToBuiltProject)
{
if (!HybridCLRSettings.instance.enable)
if (target != BuildTarget.iOS || !HybridCLRSettings.Instance.enable)
return;
string pbxprojFile = XcodeProjectFileUtil.GetXcodeProjectFile(pathToBuiltProject);
string pbxprojFile = $"{pathToBuiltProject}/Unity-iPhone.xcodeproj/project.pbxproj";
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))
{
pbxprojContent = pbxprojContent.Replace(removeBuildOption, "");
Debug.Log($"[AddLil2cppSourceCodeToXcodeproj] remove il2cpp build option '{removeBuildOption}' from file '{pbxprojFile}'");
//throw new BuildFailedException("modified project.pbxproj fail");
Debug.LogError("[AddLil2cppSourceCodeToXcodeproj] modified project.pbxproj fail");
return;
}
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);
pbxprojContent = pbxprojContent.Replace(removeBuildOption, "");
File.WriteAllText(pbxprojFile, pbxprojContent, Encoding.UTF8);
Debug.Log($"[AddLil2cppSourceCodeToXcodeproj] remove il2cpp build option '{removeBuildOption}' from file '{pbxprojFile}'");
}
private static void CopyLibil2cppToXcodeProj(string pathToBuiltProject)
{
string srcLibil2cppDir = $"{SettingsUtil.LocalIl2CppDir}/libil2cpp";
string destLibil2cppDir = $"{pathToBuiltProject}/Il2CppOutputProject/IL2CPP/libil2cpp";
DirectoryUtil.RemoveDir(destLibil2cppDir);
DirectoryUtil.CopyDir(srcLibil2cppDir, destLibil2cppDir, true);
BashUtil.RemoveDir(destLibil2cppDir);
BashUtil.CopyDir(srcLibil2cppDir, destLibil2cppDir, true);
}
}
}
}
#endif
@@ -1,54 +0,0 @@
// 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 HybridCLR.Utils;
using System.IO;
using System.Text;
using UnityEditor;
using UnityEditor.Build;
using UnityEditor.Callbacks;
using UnityEngine;
namespace HybridCLR.BuildProcessors
{
public static class AddLil2cppSourceCodeToXcodeproj2023OrNewer
{
#if UNITY_2023_1_OR_NEWER && (UNITY_IOS || UNITY_TVOS || UNITY_VISIONOS)
[PostProcessBuild]
#endif
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";
DirectoryUtil.RemoveDir(destLibil2cppDir);
DirectoryUtil.CopyDir(srcLibil2cppDir, destLibil2cppDir, true);
}
}
}
@@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: 2fa46135129b046a28014d58fdfd18ca
+17 -65
View File
@@ -1,40 +1,19 @@
// 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.IO;
using System.Text.RegularExpressions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEditor;
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
using UnityEngine;
namespace HybridCLR.BuildProcessors
namespace HybridCLR.Editor.BuildProcessors
{
internal class CheckSettings : IPreprocessBuildWithReport
{
public int callbackOrder => 0;
public static bool DisableMethodBridgeDevelopmentFlagChecking { get; set; }
public void OnPreprocessBuild(BuildReport report)
{
HybridCLRSettings globalSettings = SettingsUtil.HybridCLRSettings;
@@ -44,7 +23,7 @@ namespace HybridCLR.BuildProcessors
if (!string.IsNullOrEmpty(oldIl2cppPath))
{
Environment.SetEnvironmentVariable("UNITY_IL2CPP_PATH", "");
Debug.Log($"[CheckSettings] clean process environment variable: UNITY_IL2CPP_PATH, old vlaue:'{oldIl2cppPath}'");
Debug.Log($"[CheckSettings] 清除 UNITY_IL2CPP_PATH, 旧值为:'{oldIl2cppPath}'");
}
}
else
@@ -53,66 +32,39 @@ namespace HybridCLR.BuildProcessors
if (curIl2cppPath != SettingsUtil.LocalIl2CppDir)
{
Environment.SetEnvironmentVariable("UNITY_IL2CPP_PATH", SettingsUtil.LocalIl2CppDir);
Debug.Log($"[CheckSettings] UNITY_IL2CPP_PATH old value:'{curIl2cppPath}', new value:'{SettingsUtil.LocalIl2CppDir}'");
Debug.Log($"[CheckSettings] UNITY_IL2CPP_PATH 当前值为:'{curIl2cppPath}',更新为:'{SettingsUtil.LocalIl2CppDir}'");
}
}
if (!globalSettings.enable)
{
return;
}
BuildTargetGroup buildTargetGroup = BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget);
#if UNITY_6000_0_OR_NEWER
NamedBuildTarget namedBuildTarget = NamedBuildTarget.FromBuildTargetGroup(buildTargetGroup);
ScriptingImplementation curScriptingImplementation = PlayerSettings.GetScriptingBackend(namedBuildTarget);
#else
if (PlayerSettings.gcIncremental)
{
Debug.LogError($"[CheckSettings] HybridCLR不支持增量式GC,已经自动将该选项关闭");
PlayerSettings.gcIncremental = false;
}
BuildTargetGroup buildTargetGroup = EditorUserBuildSettings.selectedBuildTargetGroup;
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
Debug.LogError($"[CheckSettings] 当前ScriptingBackend是:{curScriptingImplementation},已经自动切换为:{targetScriptingImplementation}");
PlayerSettings.SetScriptingBackend(buildTargetGroup, targetScriptingImplementation);
#endif
}
var installer = new Installer.InstallerController();
if (!installer.HasInstalledHybridCLR())
{
throw new BuildFailedException($"You have not initialized HybridCLR, please install it via menu 'HybridCLR/Installer'");
}
if (installer.PackageVersion != installer.InstalledLibil2cppVersion)
{
throw new BuildFailedException($"You must run `HybridCLR/Installer` after upgrading package");
throw new BuildFailedException($"你没有初始化HybridCLR,请通过菜单'HybridCLR/Installer'安装");
}
HybridCLRSettings gs = SettingsUtil.HybridCLRSettings;
if (((gs.hotUpdateAssemblies?.Length + gs.hotUpdateAssemblyDefinitions?.Length) ?? 0) == 0)
{
Debug.LogWarning("[CheckSettings] No hot update modules configured in HybridCLRSettings");
Debug.LogWarning("[CheckSettings] HybridCLRSettings中未配置任何热更新模块");
}
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,93 +1,59 @@
// 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 UnityEditor.Build.Reporting;
using UnityEngine;
#if !UNITY_2021_1_OR_NEWER
using UnityEditor.Il2Cpp;
#endif
using UnityEditor.UnityLinker;
using UnityEngine;
namespace HybridCLR.BuildProcessors
namespace HybridCLR.Editor.BuildProcessors
{
internal class CopyStrippedAOTAssemblies : IPostprocessBuildWithReport, IPreprocessBuildWithReport
internal class CopyStrippedAOTAssemblies : IPostprocessBuildWithReport
#if !UNITY_2021_1_OR_NEWER
, IIl2CppProcessor
#endif
{
public int callbackOrder => 0;
#if UNITY_2021_1_OR_NEWER
public static string GetStripAssembliesDir2021(BuildTarget target)
{
string projectDir = SettingsUtil.ProjectDir;
switch (target)
{
case BuildTarget.StandaloneWindows:
case BuildTarget.StandaloneWindows64:
#if UNITY_STANDALONE_WIN
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:
#elif UNITY_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
#elif UNITY_IOS
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:
#elif UNITY_WEBGL
return $"{projectDir}/Library/Bee/artifacts/WebGL/ManagedStripped";
case BuildTarget.StandaloneOSX:
#elif UNITY_EDITOR_OSX
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";
#else
throw new NotSupportedException("GetOriginBuildStripAssembliesDir");
#endif
#if UNITY_OPENHARMONY
case BuildTarget.OpenHarmony:
return $"{projectDir}/Library/Bee/artifacts/OpenHarmonyPlayerBuildProgram/ManagedStripped";
#endif
default: return "";
}
}
#else
private string GetStripAssembliesDir2020(BuildTarget target)
{
string subPath = target == BuildTarget.Android ?
"assets/bin/Data/Managed" :
"Data/Managed/";
return $"{SettingsUtil.ProjectDir}/Temp/StagingArea/{subPath}";
}
public void OnBeforeConvertRun(BuildReport report, Il2CppBuildPipelineData data)
{
// 此回调只在 2020中调用
CopyStripDlls(GetStripAssembliesDir2020(data.target), data.target);
}
#endif
public static void CopyStripDlls(string srcStripDllPath, BuildTarget target)
{
@@ -112,19 +78,10 @@ namespace HybridCLR.BuildProcessors
public void OnPostprocessBuild(BuildReport report)
{
BuildTarget target = report.summary.platform;
string srcStripDllPath = GetStripAssembliesDir2021(target);
if (!string.IsNullOrEmpty(srcStripDllPath) && Directory.Exists(srcStripDllPath))
{
CopyStripDlls(srcStripDllPath, target);
}
}
public void OnPreprocessBuild(BuildReport report)
{
BuildTarget target = report.summary.platform;
var dstPath = SettingsUtil.GetAssembliesPostIl2CppStripDir(target);
DirectoryUtil.RecreateDir(dstPath);
#if (UNITY_2021 && !UNITY_IOS) || UNITY_2022_1_OR_NEWER
BuildTarget target = EditorUserBuildSettings.activeBuildTarget;
CopyStripDlls(GetStripAssembliesDir2021(target), target);
#endif
}
}
}
@@ -1,37 +1,18 @@
// 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 HybridCLR.Editor.Meta;
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.BuildProcessors
namespace HybridCLR.Editor.BuildProcessors
{
/// <summary>
/// Filter hot update assemblies from build process to prevent them from being packaged into the main project
/// 将热更新dll从Build过程中过滤,防止打包到主工程中
/// </summary>
internal class FilterHotFixAssemblies : IFilterBuildAssemblies
{
@@ -46,36 +27,39 @@ namespace HybridCLR.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))
{
throw new BuildFailedException($"hot update assembly name cann't be empty");
throw new BuildFailedException($"热更新 assembly 名不能为空");
}
if (!hotUpdateDllSet.Add(hotUpdateDll))
{
throw new BuildFailedException($"hot update assembly:{hotUpdateDll} is duplicated");
throw new BuildFailedException($"热更新 assembly:{hotUpdateDll} 在列表中重复,请除去重复条目");
}
}
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");
throw new BuildFailedException($"热更新 assembly:{hotUpdateDllName} 不存在,请检查拼写错误");
}
}
// 将热更dll从打包列表中移除
return assemblies.Where(ass =>
{
string assName = Path.GetFileNameWithoutExtension(ass);
bool reserved = allHotUpdateDllNames.All(dll => !assName.Equals(dll, StringComparison.Ordinal));
if (!reserved)
{
Debug.Log($"[FilterHotFixAssemblies] filter assembly:{assName}");
Debug.Log($"[FilterHotFixAssemblies] 过滤热更新assembly:{assName}");
}
return reserved;
}).ToArray();
@@ -1,90 +0,0 @@
// 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 MonoHook;
using System;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using UnityEditor;
using UnityEngine;
namespace HybridCLR.BuildProcessors.Hooks
{
[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;
#if UNITY_2021_1_OR_NEWER && (UNITY_WEBGL || UNITY_WEIXINMINIGAME)
_hook = new MethodHook(miTarget, miReplacement, miProxy);
_hook.Install();
#endif
}
}
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;
}
}
}
@@ -0,0 +1,28 @@
#if UNITY_EDITOR
using System;
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
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
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 8bff6cadf0b8db54b87ba51b24d080f6
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,51 +1,35 @@
// 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 UnityEditor;
using UnityEditor.Android;
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
using UnityEditor.Il2Cpp;
using UnityEditor.UnityLinker;
using UnityEngine;
namespace HybridCLR.BuildProcessors
namespace HybridCLR.Editor.BuildProcessors
{
public class PatchScriptingAssemblyList :
#if UNITY_ANDROID
IPostGenerateGradleAndroidProject,
#elif UNITY_OPENHARMONY
UnityEditor.OpenHarmony.IPostGenerateOpenHarmonyProject,
#endif
IPostprocessBuildWithReport
#if UNITY_PS5
, IUnityLinkerProcessor
#if !UNITY_2021_1_OR_NEWER && UNITY_WEBGL
, IIl2CppProcessor
#endif
{
public int callbackOrder => 0;
public void OnPostGenerateGradleAndroidProject(string path)
{
// 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
// 如果直接打包apk,没有机会在PostprocessBuild中修改ScriptingAssemblies.json。
// 因此需要在这个时机处理
// Unity有bug,偶然情况下会传入apk的路径,导致替换失败
if (Directory.Exists(path))
{
PathScriptingAssembilesFile(path);
@@ -56,36 +40,16 @@ namespace HybridCLR.BuildProcessors
}
}
#if UNITY_OPENHARMONY
public void OnPostGenerateOpenHarmonyProject(string path)
{
OnPostGenerateGradleAndroidProject(path);
}
#endif
public void OnPostprocessBuild(BuildReport report)
{
// For Android targets this was already handled in OnPostGenerateGradleAndroidProject,
// so skip duplicate processing here
#if !UNITY_ANDROID && !UNITY_WEBGL && !UNITY_OPENHARMONY
// 如果target为Android,由于已经在OnPostGenerateGradelAndroidProject中处理过,
// 这里不再重复处理
#if !UNITY_ANDROID && !UNITY_WEBGL
PathScriptingAssembilesFile(report.summary.outputPath);
#endif
}
#if UNITY_PS5
/// <summary>
/// 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)
{
string path = $"{SettingsUtil.ProjectDir}/Library/PlayerDataCache/PS5/Data";
PathScriptingAssembilesFile(path);
return null;
}
#endif
public void PathScriptingAssembilesFile(string path)
{
if (!SettingsUtil.Enable)
@@ -102,21 +66,19 @@ namespace HybridCLR.BuildProcessors
AddHotFixAssembliesToScriptingAssembliesJson(path);
}
private const string scriptingAssembliesJsonFile = "ScriptingAssemblies.json";
private void AddHotFixAssembliesToScriptingAssembliesJson(string path)
{
Debug.Log($"[PatchScriptingAssemblyList]. path:{path}");
/*
* 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
* ScriptingAssemblies.json 文件中记录了所有的dll名称,此列表在游戏启动时自动加载,
* 不在此列表中的dll在资源反序列化时无法被找到其类型
* 因此 OnFilterAssemblies 中移除的条目需要再加回来
*/
string[] jsonFiles = Directory.GetFiles(path, scriptingAssembliesJsonFile, SearchOption.AllDirectories);
string[] jsonFiles = Directory.GetFiles(path, SettingsUtil.ScriptingAssembliesJsonFile, SearchOption.AllDirectories);
if (jsonFiles.Length == 0)
{
Debug.LogWarning($"can not find file {scriptingAssembliesJsonFile}");
//Debug.LogError($"can not find file {SettingsUtil.ScriptingAssembliesJsonFile}");
return;
}
@@ -128,5 +90,12 @@ namespace HybridCLR.BuildProcessors
patcher.Save(file);
}
}
#if UNITY_WEBGL
public void OnBeforeConvertRun(BuildReport report, Il2CppBuildPipelineData data)
{
PathScriptingAssembilesFile($"{SettingsUtil.ProjectDir}/Temp/StagingArea/Data");
}
#endif
}
}
@@ -1,29 +1,12 @@
// 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;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
namespace HybridCLR.BuildProcessors
namespace HybridCLR.Editor.BuildProcessors
{
public class ScriptingAssembliesJsonPatcher
{
@@ -1,71 +0,0 @@
// 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);
}
}
}
-94
View File
@@ -1,94 +0,0 @@
// 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,99 +0,0 @@
// 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}");
}
}
}
-222
View File
@@ -1,222 +0,0 @@
// 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;
}
}
}
-40
View File
@@ -1,40 +0,0 @@
// 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,
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 6c7a2b75b4c05e13ab1128274336e1d5
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,43 +0,0 @@
// 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;
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 03cdedb09fc930d2f1d79689f124f68c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
-109
View File
@@ -1,109 +0,0 @@
// 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>");
}
}
}
@@ -1,31 +0,0 @@
// 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,81 +0,0 @@
// 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();
}
}
}
File diff suppressed because it is too large Load Diff
@@ -1,94 +0,0 @@
// 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();
}
}
}
+16 -113
View File
@@ -1,36 +1,16 @@
// 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 HybridCLR.Editor.AOT;
using HybridCLR.Editor.Meta;
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.Commands
namespace HybridCLR.Editor.Commands
{
using Analyzer = HybridCLR.Editor.AOT.Analyzer;
public static class AOTReferenceGeneratorCommand
{
@@ -42,102 +22,25 @@ namespace HybridCLR.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;
AssemblyReferenceDeepCollector collector = new AssemblyReferenceDeepCollector(MetaUtil.CreateHotUpdateAndAOTAssemblyResolver(target, hotUpdateDllNames), hotUpdateDllNames);
var analyzer = new AOTReferenceAnalyzer(new AOTReferenceAnalyzer.Options
using (AssemblyReferenceDeepCollector collector = new AssemblyReferenceDeepCollector(MetaUtil.CreateHotUpdateAndAOTAssemblyResolver(target, hotUpdateDllNames), hotUpdateDllNames))
{
MaxIterationCount = Math.Min(20, gs.maxGenericReferenceIteration),
Collector = collector,
});
analyzer.Run();
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))
var analyzer = new Analyzer(new Analyzer.Options
{
typeSig2Type.Remove(key);
Debug.Log($"remove AOT type:{removedType.ToTypeSig()} ");
}
}
MaxIterationCount = Math.Min(20, gs.maxGenericReferenceIteration),
Collector = collector,
});
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()} ");
}
}
analyzer.Run();
return (typeSig2Type.Values.ToList(), methodSig2Method.Values.ToList());
var writer = new GenericReferenceWriter();
writer.Write(analyzer.AotGenericTypes.ToList(), analyzer.AotGenericMethods.ToList(), $"{Application.dataPath}/{gs.outputAOTGenericReferenceFile}");
AssetDatabase.Refresh();
}
}
}
}
+10 -36
View File
@@ -1,29 +1,14 @@
// 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 UnityEditor;
using UnityEditor.Build.Player;
using UnityEngine;
namespace HybridCLR.Commands
namespace HybridCLR.Editor.Commands
{
public class CompileDllCommand
{
@@ -40,15 +25,10 @@ namespace HybridCLR.Commands
#if UNITY_2022
UnityEditor.EditorUtility.ClearProgressBar();
#endif
Debug.Log($"compile finish!!! buildDir:{buildDir} target:{target} development:{developmentBuild}");
Debug.Log("compile finish!!!");
}
public static void CompileDll(BuildTarget target)
{
CompileDll(target, EditorUserBuildSettings.development);
}
public static void CompileDll(BuildTarget target, bool developmentBuild)
public static void CompileDll(BuildTarget target, bool developmentBuild = false)
{
CompileDll(SettingsUtil.GetHotUpdateDllsOutputDirByTarget(target), target, developmentBuild);
}
@@ -56,16 +36,10 @@ namespace HybridCLR.Commands
[MenuItem("HybridCLR/CompileDll/ActiveBuildTarget", priority = 100)]
public static void CompileDllActiveBuildTarget()
{
CompileDll(EditorUserBuildSettings.activeBuildTarget, EditorUserBuildSettings.development);
CompileDll(EditorUserBuildSettings.activeBuildTarget);
}
[MenuItem("HybridCLR/CompileDll/ActiveBuildTarget_Release", priority = 102)]
public static void CompileDllActiveBuildTargetRelease()
{
CompileDll(EditorUserBuildSettings.activeBuildTarget, false);
}
[MenuItem("HybridCLR/CompileDll/ActiveBuildTarget_Development", priority = 104)]
[MenuItem("HybridCLR/CompileDll/ActiveBuildTarget_Development", priority = 101)]
public static void CompileDllActiveBuildTargetDevelopment()
{
CompileDll(EditorUserBuildSettings.activeBuildTarget, true);
+10 -26
View File
@@ -1,28 +1,12 @@
// 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 HybridCLR.Editor.Link;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEditor;
using UnityEngine;
namespace HybridCLR.Commands
namespace HybridCLR.Editor.Commands
{
public static class Il2CppDefGeneratorCommand
@@ -31,15 +15,15 @@ namespace HybridCLR.Commands
[MenuItem("HybridCLR/Generate/Il2CppDef", priority = 104)]
public static void GenerateIl2CppDef()
{
var options = new Il2CppDefGenerator.Options()
var options = new Il2CppDef.Il2CppDefGenerator.Options()
{
UnityVersion = Application.unityVersion,
HotUpdateAssemblies = SettingsUtil.HotUpdateAssemblyNamesIncludePreserved,
UnityVersionOutputFile = $"{SettingsUtil.GeneratedCppDir}/UnityVersion.inc",
AssemblyManifestOutputFile = $"{SettingsUtil.GeneratedCppDir}/AssemblyManifest.inc",
OutputFile = $"{SettingsUtil.LocalIl2CppDir}/libil2cpp/hybridclr/generated/UnityVersion.h",
OutputFile2 = $"{SettingsUtil.LocalIl2CppDir}/libil2cpp/hybridclr/generated/AssemblyManifest.cpp",
};
var g = new Il2CppDefGenerator(options);
var g = new Il2CppDef.Il2CppDefGenerator(options);
g.Generate();
}
}
+11 -28
View File
@@ -1,32 +1,15 @@
// 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 HybridCLR.Editor.Link;
using HybridCLR.Editor.Meta;
using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEditor;
using UnityEngine;
namespace HybridCLR.Commands
namespace HybridCLR.Editor.Commands
{
using Analyzer = HybridCLR.Editor.Link.Analyzer;
public static class LinkGeneratorCommand
{
@@ -44,12 +27,12 @@ namespace HybridCLR.Commands
List<string> hotfixAssemblies = SettingsUtil.HotUpdateAssemblyNamesExcludePreserved;
var analyzer = new LinkAnalyzer(MetaUtil.CreateHotUpdateAndAOTAssemblyResolver(target, hotfixAssemblies));
var preserveTypes = analyzer.CollectRefs(hotfixAssemblies, ls.linkPreserveLevel);
var analyzer = new Analyzer(MetaUtil.CreateHotUpdateAndAOTAssemblyResolver(target, hotfixAssemblies));
var refTypes = analyzer.CollectRefs(hotfixAssemblies);
Debug.Log($"[LinkGeneratorCommand] hotfix assembly count:{hotfixAssemblies.Count}, preserve level:{ls.linkPreserveLevel}, type count:{preserveTypes.Count} output:{Application.dataPath}/{ls.outputLinkFile}");
Debug.Log($"[LinkGeneratorCommand] hotfix assembly count:{hotfixAssemblies.Count}, ref type count:{refTypes.Count} output:{Application.dataPath}/{ls.outputLinkFile}");
var linkXmlWriter = new LinkXmlWriter();
linkXmlWriter.Write($"{Application.dataPath}/{ls.outputLinkFile}", preserveTypes);
linkXmlWriter.Write($"{Application.dataPath}/{ls.outputLinkFile}", refTypes);
AssetDatabase.Refresh();
}
}
+56 -69
View File
@@ -1,99 +1,86 @@
// 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 HybridCLR.Editor;
using HybridCLR.Editor.ABI;
using HybridCLR.Editor.Meta;
using HybridCLR.Editor.MethodBridge;
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.Commands
namespace HybridCLR.Editor.Commands
{
using Analyzer = HybridCLR.Editor.MethodBridge.Analyzer;
public class MethodBridgeGeneratorCommand
{
public static void GenerateMethodBridgeCppFile(IReadOnlyCollection<GenericMethod> genericMethods, List<RawMonoPInvokeCallbackMethodInfo> reversePInvokeMethods, IReadOnlyCollection<CallNativeMethodSignatureInfo> calliMethodSignatures, string outputFile)
public static void CleanIl2CppBuildCache()
{
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, PlatformABI platform, string templateCode, string outputFile)
{
var g = new Generator(new Generator.Options()
{
PlatformABI = platform,
TemplateCode = templateCode,
OutputFile = outputFile,
GenericMethods = genericMethods,
ReversePInvokeMethods = reversePInvokeMethods,
CalliMethodSignatures = calliMethodSignatures,
Development = EditorUserBuildSettings.development,
GenericMethods = analyzer.GenericMethods,
NotGenericMethods = analyzer.NotGenericMethods,
SpeicalPreserveMethods = analyzer.SpeicalPreserveMethods,
});
g.PrepareMethods();
g.Generate();
Debug.LogFormat("[MethodBridgeGeneratorCommand] output:{0}", outputFile);
Debug.LogFormat("== output:{0} ==", outputFile);
}
[MenuItem("HybridCLR/Generate/MethodBridgeAndReversePInvokeWrapper", priority = 101)]
public static void GenerateMethodBridgeAndReversePInvokeWrapper()
[MenuItem("HybridCLR/Generate/MethodBridge", priority = 101)]
public static void CompileAndGenerateMethodBridge()
{
BuildTarget target = EditorUserBuildSettings.activeBuildTarget;
GenerateMethodBridgeAndReversePInvokeWrapper(target);
CompileDllCommand.CompileDll(target);
GenerateMethodBridge(target);
}
public static void GenerateEmptyMethodBridgeAndReversePInvokeWrapper(BuildTarget target)
public static void GenerateMethodBridge(BuildTarget target)
{
string outputFile = $"{SettingsUtil.GeneratedCppDir}/MethodBridge.inc";
GenerateMethodBridgeCppFile(new List<GenericMethod>(), new List<RawMonoPInvokeCallbackMethodInfo>(), new List<CallNativeMethodSignatureInfo>(), outputFile);
}
public static void GenerateMethodBridgeAndReversePInvokeWrapper(BuildTarget target)
{
string aotDllDir = SettingsUtil.GetAssembliesPostIl2CppStripDir(target);
List<string> aotAssemblyNames = Directory.Exists(aotDllDir) ?
Directory.GetFiles(aotDllDir, "*.dll", SearchOption.TopDirectoryOnly).Select(Path.GetFileNameWithoutExtension).ToList()
: new List<string>();
if (aotAssemblyNames.Count == 0)
List<string> hotUpdateDllNames = SettingsUtil.HotUpdateAssemblyNamesExcludePreserved;
using (AssemblyReferenceDeepCollector collector = new AssemblyReferenceDeepCollector(MetaUtil.CreateHotUpdateAndAOTAssemblyResolver(target, hotUpdateDllNames), hotUpdateDllNames))
{
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`");
var analyzer = new Analyzer(new Analyzer.Options
{
MaxIterationCount = Math.Min(20, SettingsUtil.HybridCLRSettings.maxMethodBridgeGenericIteration),
Collector = collector,
});
analyzer.Run();
var tasks = new List<Task>();
string templateCode = File.ReadAllText($"{SettingsUtil.TemplatePathInPackage}/MethodBridgeStub.cpp");
foreach (PlatformABI platform in Enum.GetValues(typeof(PlatformABI)))
{
string outputFile = $"{SettingsUtil.GeneratedCppDir}/MethodBridge_{platform}.cpp";
tasks.Add(Task.Run(() =>
{
GenerateMethodBridgeCppFile(analyzer, platform, templateCode, outputFile);
}));
}
Task.WaitAll(tasks.ToArray());
}
AssemblyReferenceDeepCollector collector = new AssemblyReferenceDeepCollector(MetaUtil.CreateAOTAssemblyResolver(target), aotAssemblyNames);
var methodBridgeAnalyzer = new MethodBridgeAnalyzer(new MethodBridgeAnalyzer.Options
{
MaxIterationCount = Math.Min(20, SettingsUtil.HybridCLRSettings.maxMethodBridgeGenericIteration),
Collector = collector,
});
methodBridgeAnalyzer.Run();
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);
CleanIl2CppBuildCache();
}
}
}
+14 -39
View File
@@ -1,58 +1,33 @@
// 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.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEditor;
using UnityEditor.Build;
namespace HybridCLR.Commands
namespace HybridCLR.Editor.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, EditorUserBuildSettings.development);
CompileDllCommand.CompileDll(target);
Il2CppDefGeneratorCommand.GenerateIl2CppDef();
// These generation depend on HotUpdateDlls
// 这几个生成依赖HotUpdateDlls
LinkGeneratorCommand.GenerateLinkXml(target);
// Because some build targets will link the generated AOT dll before generating method bridge,
// so we need to generate an empty method bridge and reverse PInvoke wrapper first
// so that the generated AOT dll can be linked successfully
MethodBridgeGeneratorCommand.GenerateEmptyMethodBridgeAndReversePInvokeWrapper(target);
// 生成裁剪后的aot dll
StripAOTDllCommand.GenerateStripedAOTDlls(target, EditorUserBuildSettings.selectedBuildTargetGroup);
// Generate stripped aot dll
StripAOTDllCommand.GenerateStripedAOTDlls(target);
// Method bridge generation depends on AOT dll, must be built before generating AOT dll
MethodBridgeGeneratorCommand.GenerateMethodBridgeAndReversePInvokeWrapper(target);
// 桥接函数生成依赖于AOT dll,必须保证已经build过,生成AOT dll
MethodBridgeGeneratorCommand.GenerateMethodBridge(target);
ReversePInvokeWrapperGeneratorCommand.GenerateReversePInvokeWrapper(target);
AOTReferenceGeneratorCommand.GenerateAOTGenericReference(target);
}
}
@@ -0,0 +1,53 @@
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 templateCode = File.ReadAllText($"{SettingsUtil.TemplatePathInPackage}/ReversePInvokeMethodStub.cpp");
foreach (PlatformABI abi in Enum.GetValues(typeof(PlatformABI)))
{
string outputFile = $"{SettingsUtil.GeneratedCppDir}/ReversePInvokeMethodStub_{abi}.cpp";
List<ABIReversePInvokeMethodInfo> methods = analyzer.BuildABIMethods(abi);
Debug.Log($"GenerateReversePInvokeWrapper. abi:{abi} wraperCount:{methods.Sum(m => m.Count)} output:{outputFile}");
var generator = new Generator();
generator.Generate(templateCode, abi, methods, outputFile);
}
}
MethodBridgeGeneratorCommand.CleanIl2CppBuildCache();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 7db18e1736f593c4089c85d764cf8620
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
+54 -143
View File
@@ -1,210 +1,121 @@
// 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 HybridCLR.Editor.Installer;
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.Commands
namespace HybridCLR.Editor.Commands
{
public static class StripAOTDllCommand
{
[MenuItem("HybridCLR/Generate/StrippedAotDlls", priority = 105)]
[MenuItem("HybridCLR/Generate/AOTDlls", priority = 105)]
public static void GenerateStripedAOTDlls()
{
GenerateStripedAOTDlls(EditorUserBuildSettings.activeBuildTarget);
}
static BuildOptions GetBuildPlayerOptions(BuildTarget buildTarget)
{
BuildOptions options = BuildOptions.None;
bool development = EditorUserBuildSettings.development;
if (development)
{
options |= BuildOptions.Development;
}
if (EditorUserBuildSettings.allowDebugging && development)
{
options |= BuildOptions.AllowDebugging;
}
if (EditorUserBuildSettings.connectProfiler && (development || buildTarget == BuildTarget.WSAPlayer))
{
options |= BuildOptions.ConnectWithProfiler;
}
if (EditorUserBuildSettings.buildWithDeepProfilingSupport && development)
{
options |= BuildOptions.EnableDeepProfilingSupport;
}
#if UNITY_2021_2_OR_NEWER
options |= BuildOptions.CleanBuildCache;
#endif
return options;
GenerateStripedAOTDlls(EditorUserBuildSettings.activeBuildTarget, EditorUserBuildSettings.selectedBuildTargetGroup);
}
private static string GetLocationPathName(string buildDir, BuildTarget target)
{
switch (target)
switch(target)
{
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;
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;
}
}
public static void GenerateStripedAOTDlls(BuildTarget target)
public static void GenerateStripedAOTDlls(BuildTarget target, BuildTargetGroup group)
{
string outputPath = $"Temp/HybridCLR/StrippedAOTDllsTempProj/{target}";
DirectoryUtil.RemoveDir(outputPath);
string outputPath = $"{SettingsUtil.HybridCLRDataDir}/StrippedAOTDllsTempProj/{target}";
BashUtil.RemoveDir(outputPath);
var buildOptions = GetBuildPlayerOptions(target);
var buildOptions = BuildOptions.BuildScriptsOnly;
#if UNITY_2021_2_OR_NEWER
buildOptions |= BuildOptions.CleanBuildCache;
#endif
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 oldBuildLocation = EditorUserBuildSettings.GetBuildLocation(target);
try
switch (target)
{
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");
}
}
finally
{
CheckSettings.DisableMethodBridgeDevelopmentFlagChecking = false;
EditorUserBuildSettings.buildScriptsOnly = oldBuildScriptsOnly;
EditorUserBuildSettings.SetBuildLocation(target, oldBuildLocation);
switch (target)
{
BuildPlayerOptions buildPlayerOptions = new BuildPlayerOptions()
{
scenes = EditorBuildSettings.scenes.Where(s => s.enabled).Select(s => s.path).ToArray(),
locationPathName = GetLocationPathName(outputPath, target),
options = buildOptions,
target = target,
targetGroup = group,
};
var report = BuildPipeline.BuildPlayer(buildPlayerOptions);
EditorUserBuildSettings.buildScriptsOnly = oldBuildScriptsOnly;
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;
#endif
break;
}
#if TUANJIE_2022_3_OR_NEWER
case BuildTarget.HMIAndroid:
UnityEditor.OSXStandalone.UserBuildSettings.createXcodeProject = oldCreateSolution;
#endif
break;
}
case BuildTarget.Android:
{
EditorUserBuildSettings.exportAsGoogleAndroidProject = oldExportAndroidProj;
break;
}
#if TUANJIE_2022_3_OR_NEWER
case BuildTarget.OpenHarmony:
{
EditorUserBuildSettings.exportAsOpenHarmonyProject = oldOpenHarmonyProj;
break;
}
#endif
}
}
Debug.Log($"GenerateStripedAOTDlls target:{target} path:{outputPath}");
if (report.summary.result != UnityEditor.Build.Reporting.BuildResult.Succeeded)
{
throw new Exception("GenerateStripedAOTDlls 失败");
}
Debug.Log($"GenerateStripedAOTDlls target:{target} group:{group} path:{outputPath}");
}
}
}
+28
View File
@@ -0,0 +1,28 @@
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: 4db1429642a79b24ba0c91b80ff9290c
guid: 5d4ae4a5c0bba49469c525887d812717
MonoImporter:
externalObjects: {}
serializedVersion: 2
-125
View File
@@ -1,125 +0,0 @@
// 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;
}
}
}

Some files were not shown because too many files have changed in this diff Show More