diff --git a/Data~/ModifiedUnityAssemblies/2019.4.40/Unity.IL2CPP-Mac.dll b/Data~/ModifiedUnityAssemblies/2019.4.40/Unity.IL2CPP-Mac.dll deleted file mode 100644 index 2cce7a7..0000000 Binary files a/Data~/ModifiedUnityAssemblies/2019.4.40/Unity.IL2CPP-Mac.dll and /dev/null differ diff --git a/Data~/ModifiedUnityAssemblies/2019.4.40/Unity.IL2CPP-Win.dll b/Data~/ModifiedUnityAssemblies/2019.4.40/Unity.IL2CPP-Win.dll deleted file mode 100644 index 17135a1..0000000 Binary files a/Data~/ModifiedUnityAssemblies/2019.4.40/Unity.IL2CPP-Win.dll and /dev/null differ diff --git a/Data~/Templates/AssemblyManifest.cpp.tpl b/Data~/Templates/AssemblyManifest.cpp.tpl deleted file mode 100644 index d43977d..0000000 --- a/Data~/Templates/AssemblyManifest.cpp.tpl +++ /dev/null @@ -1,12 +0,0 @@ -#include "../Il2CppCompatibleDef.h" - -namespace hybridclr -{ - const char* g_placeHolderAssemblies[] = - { - //!!!{{PLACE_HOLDER - - //!!!}}PLACE_HOLDER - nullptr, - }; -} diff --git a/Data~/Templates/MethodBridge.cpp.tpl b/Data~/Templates/MethodBridge.cpp.tpl deleted file mode 100644 index b723a16..0000000 --- a/Data~/Templates/MethodBridge.cpp.tpl +++ /dev/null @@ -1,32 +0,0 @@ -#include -#if HYBRIDCLR_UNITY_2023_OR_NEW -#include -#elif HYBRIDCLR_UNITY_2022 -#include -#elif HYBRIDCLR_UNITY_2020 || HYBRIDCLR_UNITY_2021 -#include -#else -#include -#endif - -#include "vm/ClassInlines.h" -#include "vm/Object.h" -#include "vm/Class.h" -#include "vm/ScopedThreadAttacher.h" - -#include "../metadata/MetadataUtil.h" - - -#include "../interpreter/InterpreterModule.h" -#include "../interpreter/MethodBridge.h" -#include "../interpreter/Interpreter.h" -#include "../interpreter/MemoryUtil.h" -#include "../interpreter/InstrinctDef.h" - -using namespace hybridclr::interpreter; -using namespace hybridclr::metadata; - -//!!!{{CODE - - -//!!!}}CODE diff --git a/Data~/Templates/UnityVersion.h.tpl b/Data~/Templates/UnityVersion.h.tpl deleted file mode 100644 index f0fddb8..0000000 --- a/Data~/Templates/UnityVersion.h.tpl +++ /dev/null @@ -1,6 +0,0 @@ -#pragma once - -//!!!{{UNITY_VERSION - - -//!!!}}UNITY_VERSION \ No newline at end of file diff --git a/Data~/hybridclr_version.json b/Data~/hybridclr_version.json index 73e8eb6..53b1d65 100644 --- a/Data~/hybridclr_version.json +++ b/Data~/hybridclr_version.json @@ -1,49 +1,24 @@ { "versions": [ { - "unity_version":"2019", - "hybridclr" : { "branch":"v8.15.0"}, - "il2cpp_plus": { "branch":"v2019-8.15.0"} + "unity_version":"2022.3.x", + "hybridclr" : { "tag":"v9.0.0"}, + "il2cpp_plus": { "tag":"v2022.3.x-9.0.0"} }, { - "unity_version":"2020", - "hybridclr" : { "branch":"v8.15.0"}, - "il2cpp_plus": { "branch":"v2020-8.15.0"} + "unity_version":"2022.3.x-tuanjie", + "hybridclr" : { "tag":"v9.0.0"}, + "il2cpp_plus": { "tag":"v2022.3.x-tuanjie-9.0.0"} }, { - "unity_version":"2021", - "hybridclr" : { "branch":"v8.15.0"}, - "il2cpp_plus": { "branch":"v2021-8.15.0"} - }, - { - "unity_version":"2022", - "hybridclr" : { "branch":"v8.15.0"}, - "il2cpp_plus": { "branch":"v2022-8.15.0"} - }, - { - "unity_version":"2022-tuanjie", - "hybridclr" : { "branch":"v8.15.0"}, - "il2cpp_plus": { "branch":"v2022-tuanjie-8.15.0"} - }, - { - "unity_version":"2023", - "hybridclr" : { "branch":"v8.15.0"}, - "il2cpp_plus": { "branch":"v2023-8.1.0"} - }, - { - "unity_version":"6000", - "hybridclr" : { "branch":"v8.15.0"}, - "il2cpp_plus": { "branch":"v6000-8.15.0"} + "unity_version":"6000.0.x", + "hybridclr" : { "tag":"v9.0.0"}, + "il2cpp_plus": { "tag":"v6000.0.x-9.0.0"} }, { "unity_version":"6000.3.x", - "hybridclr" : { "branch":"v6000.3.x-8.15.0"}, - "il2cpp_plus": { "branch":"v6000.3.x-8.15.0"} - }, - { - "unity_version":"6000.5.x", - "hybridclr" : { "branch":"v6000.5.x-8.15.0"}, - "il2cpp_plus": { "branch":"v6000.5.x-8.15.0"} + "hybridclr" : { "tag":"v6000.3.x-9.0.0"}, + "il2cpp_plus": { "tag":"v6000.3.x-9.0.0"} } ] } \ No newline at end of file diff --git a/Editor/3rds/7zip/Common/CRC.cs b/Editor/3rds/7zip/Common/CRC.cs deleted file mode 100644 index d03fcec..0000000 --- a/Editor/3rds/7zip/Common/CRC.cs +++ /dev/null @@ -1,55 +0,0 @@ -// Common/CRC.cs - -namespace SevenZip -{ - public class CRC - { - public static readonly uint[] Table; - - static CRC() - { - Table = new uint[256]; - const uint kPoly = 0xEDB88320; - for (uint i = 0; i < 256; i++) - { - uint r = i; - for (int j = 0; j < 8; j++) - if ((r & 1) != 0) - r = (r >> 1) ^ kPoly; - else - r >>= 1; - Table[i] = r; - } - } - - uint _value = 0xFFFFFFFF; - - public void Init() { _value = 0xFFFFFFFF; } - - public void UpdateByte(byte b) - { - _value = Table[(((byte)(_value)) ^ b)] ^ (_value >> 8); - } - - public void Update(byte[] data, uint offset, uint size) - { - for (uint i = 0; i < size; i++) - _value = Table[(((byte)(_value)) ^ data[offset + i])] ^ (_value >> 8); - } - - public uint GetDigest() { return _value ^ 0xFFFFFFFF; } - - static uint CalculateDigest(byte[] data, uint offset, uint size) - { - CRC crc = new CRC(); - // crc.Init(); - crc.Update(data, offset, size); - return crc.GetDigest(); - } - - static bool VerifyDigest(uint digest, byte[] data, uint offset, uint size) - { - return (CalculateDigest(data, offset, size) == digest); - } - } -} diff --git a/Editor/3rds/7zip/Common/CommandLineParser.cs b/Editor/3rds/7zip/Common/CommandLineParser.cs deleted file mode 100644 index 8eabf59..0000000 --- a/Editor/3rds/7zip/Common/CommandLineParser.cs +++ /dev/null @@ -1,274 +0,0 @@ -// CommandLineParser.cs - -using System; -using System.Collections; - -namespace SevenZip.CommandLineParser -{ - public enum SwitchType - { - Simple, - PostMinus, - LimitedPostString, - UnLimitedPostString, - PostChar - } - - public class SwitchForm - { - public string IDString; - public SwitchType Type; - public bool Multi; - public int MinLen; - public int MaxLen; - public string PostCharSet; - - public SwitchForm(string idString, SwitchType type, bool multi, - int minLen, int maxLen, string postCharSet) - { - IDString = idString; - Type = type; - Multi = multi; - MinLen = minLen; - MaxLen = maxLen; - PostCharSet = postCharSet; - } - public SwitchForm(string idString, SwitchType type, bool multi, int minLen): - this(idString, type, multi, minLen, 0, "") - { - } - public SwitchForm(string idString, SwitchType type, bool multi): - this(idString, type, multi, 0) - { - } - } - - public class SwitchResult - { - public bool ThereIs; - public bool WithMinus; - public ArrayList PostStrings = new ArrayList(); - public int PostCharIndex; - public SwitchResult() - { - ThereIs = false; - } - } - - public class Parser - { - public ArrayList NonSwitchStrings = new ArrayList(); - SwitchResult[] _switches; - - public Parser(int numSwitches) - { - _switches = new SwitchResult[numSwitches]; - for (int i = 0; i < numSwitches; i++) - _switches[i] = new SwitchResult(); - } - - bool ParseString(string srcString, SwitchForm[] switchForms) - { - int len = srcString.Length; - if (len == 0) - return false; - int pos = 0; - if (!IsItSwitchChar(srcString[pos])) - return false; - while (pos < len) - { - if (IsItSwitchChar(srcString[pos])) - pos++; - const int kNoLen = -1; - int matchedSwitchIndex = 0; - int maxLen = kNoLen; - for (int switchIndex = 0; switchIndex < _switches.Length; switchIndex++) - { - int switchLen = switchForms[switchIndex].IDString.Length; - if (switchLen <= maxLen || pos + switchLen > len) - continue; - if (String.Compare(switchForms[switchIndex].IDString, 0, - srcString, pos, switchLen, true) == 0) - { - matchedSwitchIndex = switchIndex; - maxLen = switchLen; - } - } - if (maxLen == kNoLen) - throw new Exception("maxLen == kNoLen"); - SwitchResult matchedSwitch = _switches[matchedSwitchIndex]; - SwitchForm switchForm = switchForms[matchedSwitchIndex]; - if ((!switchForm.Multi) && matchedSwitch.ThereIs) - throw new Exception("switch must be single"); - matchedSwitch.ThereIs = true; - pos += maxLen; - int tailSize = len - pos; - SwitchType type = switchForm.Type; - switch (type) - { - case SwitchType.PostMinus: - { - if (tailSize == 0) - matchedSwitch.WithMinus = false; - else - { - matchedSwitch.WithMinus = (srcString[pos] == kSwitchMinus); - if (matchedSwitch.WithMinus) - pos++; - } - break; - } - case SwitchType.PostChar: - { - if (tailSize < switchForm.MinLen) - throw new Exception("switch is not full"); - string charSet = switchForm.PostCharSet; - const int kEmptyCharValue = -1; - if (tailSize == 0) - matchedSwitch.PostCharIndex = kEmptyCharValue; - else - { - int index = charSet.IndexOf(srcString[pos]); - if (index < 0) - matchedSwitch.PostCharIndex = kEmptyCharValue; - else - { - matchedSwitch.PostCharIndex = index; - pos++; - } - } - break; - } - case SwitchType.LimitedPostString: - case SwitchType.UnLimitedPostString: - { - int minLen = switchForm.MinLen; - if (tailSize < minLen) - throw new Exception("switch is not full"); - if (type == SwitchType.UnLimitedPostString) - { - matchedSwitch.PostStrings.Add(srcString.Substring(pos)); - return true; - } - String stringSwitch = srcString.Substring(pos, minLen); - pos += minLen; - for (int i = minLen; i < switchForm.MaxLen && pos < len; i++, pos++) - { - char c = srcString[pos]; - if (IsItSwitchChar(c)) - break; - stringSwitch += c; - } - matchedSwitch.PostStrings.Add(stringSwitch); - break; - } - } - } - return true; - - } - - public void ParseStrings(SwitchForm[] switchForms, string[] commandStrings) - { - int numCommandStrings = commandStrings.Length; - bool stopSwitch = false; - for (int i = 0; i < numCommandStrings; i++) - { - string s = commandStrings[i]; - if (stopSwitch) - NonSwitchStrings.Add(s); - else - if (s == kStopSwitchParsing) - stopSwitch = true; - else - if (!ParseString(s, switchForms)) - NonSwitchStrings.Add(s); - } - } - - public SwitchResult this[int index] { get { return _switches[index]; } } - - public static int ParseCommand(CommandForm[] commandForms, string commandString, - out string postString) - { - for (int i = 0; i < commandForms.Length; i++) - { - string id = commandForms[i].IDString; - if (commandForms[i].PostStringMode) - { - if (commandString.IndexOf(id) == 0) - { - postString = commandString.Substring(id.Length); - return i; - } - } - else - if (commandString == id) - { - postString = ""; - return i; - } - } - postString = ""; - return -1; - } - - static bool ParseSubCharsCommand(int numForms, CommandSubCharsSet[] forms, - string commandString, ArrayList indices) - { - indices.Clear(); - int numUsedChars = 0; - for (int i = 0; i < numForms; i++) - { - CommandSubCharsSet charsSet = forms[i]; - int currentIndex = -1; - int len = charsSet.Chars.Length; - for (int j = 0; j < len; j++) - { - char c = charsSet.Chars[j]; - int newIndex = commandString.IndexOf(c); - if (newIndex >= 0) - { - if (currentIndex >= 0) - return false; - if (commandString.IndexOf(c, newIndex + 1) >= 0) - return false; - currentIndex = j; - numUsedChars++; - } - } - if (currentIndex == -1 && !charsSet.EmptyAllowed) - return false; - indices.Add(currentIndex); - } - return (numUsedChars == commandString.Length); - } - const char kSwitchID1 = '-'; - const char kSwitchID2 = '/'; - - const char kSwitchMinus = '-'; - const string kStopSwitchParsing = "--"; - - static bool IsItSwitchChar(char c) - { - return (c == kSwitchID1 || c == kSwitchID2); - } - } - - public class CommandForm - { - public string IDString = ""; - public bool PostStringMode = false; - public CommandForm(string idString, bool postStringMode) - { - IDString = idString; - PostStringMode = postStringMode; - } - } - - class CommandSubCharsSet - { - public string Chars = ""; - public bool EmptyAllowed = false; - } -} diff --git a/Editor/3rds/7zip/Common/InBuffer.cs b/Editor/3rds/7zip/Common/InBuffer.cs deleted file mode 100644 index 7c51f0b..0000000 --- a/Editor/3rds/7zip/Common/InBuffer.cs +++ /dev/null @@ -1,72 +0,0 @@ -// InBuffer.cs - -namespace SevenZip.Buffer -{ - public class InBuffer - { - byte[] m_Buffer; - uint m_Pos; - uint m_Limit; - uint m_BufferSize; - System.IO.Stream m_Stream; - bool m_StreamWasExhausted; - ulong m_ProcessedSize; - - public InBuffer(uint bufferSize) - { - m_Buffer = new byte[bufferSize]; - m_BufferSize = bufferSize; - } - - public void Init(System.IO.Stream stream) - { - m_Stream = stream; - m_ProcessedSize = 0; - m_Limit = 0; - m_Pos = 0; - m_StreamWasExhausted = false; - } - - public bool ReadBlock() - { - if (m_StreamWasExhausted) - return false; - m_ProcessedSize += m_Pos; - int aNumProcessedBytes = m_Stream.Read(m_Buffer, 0, (int)m_BufferSize); - m_Pos = 0; - m_Limit = (uint)aNumProcessedBytes; - m_StreamWasExhausted = (aNumProcessedBytes == 0); - return (!m_StreamWasExhausted); - } - - - public void ReleaseStream() - { - // m_Stream.Close(); - m_Stream = null; - } - - public bool ReadByte(byte b) // check it - { - if (m_Pos >= m_Limit) - if (!ReadBlock()) - return false; - b = m_Buffer[m_Pos++]; - return true; - } - - public byte ReadByte() - { - // return (byte)m_Stream.ReadByte(); - if (m_Pos >= m_Limit) - if (!ReadBlock()) - return 0xFF; - return m_Buffer[m_Pos++]; - } - - public ulong GetProcessedSize() - { - return m_ProcessedSize + m_Pos; - } - } -} diff --git a/Editor/3rds/7zip/Common/OutBuffer.cs b/Editor/3rds/7zip/Common/OutBuffer.cs deleted file mode 100644 index 2da16e1..0000000 --- a/Editor/3rds/7zip/Common/OutBuffer.cs +++ /dev/null @@ -1,47 +0,0 @@ -// OutBuffer.cs - -namespace SevenZip.Buffer -{ - public class OutBuffer - { - byte[] m_Buffer; - uint m_Pos; - uint m_BufferSize; - System.IO.Stream m_Stream; - ulong m_ProcessedSize; - - public OutBuffer(uint bufferSize) - { - m_Buffer = new byte[bufferSize]; - m_BufferSize = bufferSize; - } - - public void SetStream(System.IO.Stream stream) { m_Stream = stream; } - public void FlushStream() { m_Stream.Flush(); } - public void CloseStream() { m_Stream.Close(); } - public void ReleaseStream() { m_Stream = null; } - - public void Init() - { - m_ProcessedSize = 0; - m_Pos = 0; - } - - public void WriteByte(byte b) - { - m_Buffer[m_Pos++] = b; - if (m_Pos >= m_BufferSize) - FlushData(); - } - - public void FlushData() - { - if (m_Pos == 0) - return; - m_Stream.Write(m_Buffer, 0, (int)m_Pos); - m_Pos = 0; - } - - public ulong GetProcessedSize() { return m_ProcessedSize + m_Pos; } - } -} diff --git a/Editor/3rds/7zip/Compress/LZ.meta b/Editor/3rds/7zip/Compress/LZ.meta deleted file mode 100644 index c303414..0000000 --- a/Editor/3rds/7zip/Compress/LZ.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: a83572c42056f474db56e761a4f35e38 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/3rds/7zip/Compress/LZ/IMatchFinder.cs b/Editor/3rds/7zip/Compress/LZ/IMatchFinder.cs deleted file mode 100644 index 10ca2b3..0000000 --- a/Editor/3rds/7zip/Compress/LZ/IMatchFinder.cs +++ /dev/null @@ -1,24 +0,0 @@ -// IMatchFinder.cs - -using System; - -namespace SevenZip.Compression.LZ -{ - interface IInWindowStream - { - void SetStream(System.IO.Stream inStream); - void Init(); - void ReleaseStream(); - Byte GetIndexByte(Int32 index); - UInt32 GetMatchLen(Int32 index, UInt32 distance, UInt32 limit); - UInt32 GetNumAvailableBytes(); - } - - interface IMatchFinder : IInWindowStream - { - void Create(UInt32 historySize, UInt32 keepAddBufferBefore, - UInt32 matchMaxLen, UInt32 keepAddBufferAfter); - UInt32 GetMatches(UInt32[] distances); - void Skip(UInt32 num); - } -} diff --git a/Editor/3rds/7zip/Compress/LZ/IMatchFinder.cs.meta b/Editor/3rds/7zip/Compress/LZ/IMatchFinder.cs.meta deleted file mode 100644 index 88c6d3d..0000000 --- a/Editor/3rds/7zip/Compress/LZ/IMatchFinder.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: bfd1ee430d8108042a2607d92d7f58ad -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/3rds/7zip/Compress/LZ/LzBinTree.cs b/Editor/3rds/7zip/Compress/LZ/LzBinTree.cs deleted file mode 100644 index c1c006b..0000000 --- a/Editor/3rds/7zip/Compress/LZ/LzBinTree.cs +++ /dev/null @@ -1,367 +0,0 @@ -// LzBinTree.cs - -using System; - -namespace SevenZip.Compression.LZ -{ - public class BinTree : InWindow, IMatchFinder - { - UInt32 _cyclicBufferPos; - UInt32 _cyclicBufferSize = 0; - UInt32 _matchMaxLen; - - UInt32[] _son; - UInt32[] _hash; - - UInt32 _cutValue = 0xFF; - UInt32 _hashMask; - UInt32 _hashSizeSum = 0; - - bool HASH_ARRAY = true; - - const UInt32 kHash2Size = 1 << 10; - const UInt32 kHash3Size = 1 << 16; - const UInt32 kBT2HashSize = 1 << 16; - const UInt32 kStartMaxLen = 1; - const UInt32 kHash3Offset = kHash2Size; - const UInt32 kEmptyHashValue = 0; - const UInt32 kMaxValForNormalize = ((UInt32)1 << 31) - 1; - - UInt32 kNumHashDirectBytes = 0; - UInt32 kMinMatchCheck = 4; - UInt32 kFixHashSize = kHash2Size + kHash3Size; - - public void SetType(int numHashBytes) - { - HASH_ARRAY = (numHashBytes > 2); - if (HASH_ARRAY) - { - kNumHashDirectBytes = 0; - kMinMatchCheck = 4; - kFixHashSize = kHash2Size + kHash3Size; - } - else - { - kNumHashDirectBytes = 2; - kMinMatchCheck = 2 + 1; - kFixHashSize = 0; - } - } - - public new void SetStream(System.IO.Stream stream) { base.SetStream(stream); } - public new void ReleaseStream() { base.ReleaseStream(); } - - public new void Init() - { - base.Init(); - for (UInt32 i = 0; i < _hashSizeSum; i++) - _hash[i] = kEmptyHashValue; - _cyclicBufferPos = 0; - ReduceOffsets(-1); - } - - public new void MovePos() - { - if (++_cyclicBufferPos >= _cyclicBufferSize) - _cyclicBufferPos = 0; - base.MovePos(); - if (_pos == kMaxValForNormalize) - Normalize(); - } - - public new Byte GetIndexByte(Int32 index) { return base.GetIndexByte(index); } - - public new UInt32 GetMatchLen(Int32 index, UInt32 distance, UInt32 limit) - { return base.GetMatchLen(index, distance, limit); } - - public new UInt32 GetNumAvailableBytes() { return base.GetNumAvailableBytes(); } - - public void Create(UInt32 historySize, UInt32 keepAddBufferBefore, - UInt32 matchMaxLen, UInt32 keepAddBufferAfter) - { - if (historySize > kMaxValForNormalize - 256) - throw new Exception(); - _cutValue = 16 + (matchMaxLen >> 1); - - UInt32 windowReservSize = (historySize + keepAddBufferBefore + - matchMaxLen + keepAddBufferAfter) / 2 + 256; - - base.Create(historySize + keepAddBufferBefore, matchMaxLen + keepAddBufferAfter, windowReservSize); - - _matchMaxLen = matchMaxLen; - - UInt32 cyclicBufferSize = historySize + 1; - if (_cyclicBufferSize != cyclicBufferSize) - _son = new UInt32[(_cyclicBufferSize = cyclicBufferSize) * 2]; - - UInt32 hs = kBT2HashSize; - - if (HASH_ARRAY) - { - hs = historySize - 1; - hs |= (hs >> 1); - hs |= (hs >> 2); - hs |= (hs >> 4); - hs |= (hs >> 8); - hs >>= 1; - hs |= 0xFFFF; - if (hs > (1 << 24)) - hs >>= 1; - _hashMask = hs; - hs++; - hs += kFixHashSize; - } - if (hs != _hashSizeSum) - _hash = new UInt32[_hashSizeSum = hs]; - } - - public UInt32 GetMatches(UInt32[] distances) - { - UInt32 lenLimit; - if (_pos + _matchMaxLen <= _streamPos) - lenLimit = _matchMaxLen; - else - { - lenLimit = _streamPos - _pos; - if (lenLimit < kMinMatchCheck) - { - MovePos(); - return 0; - } - } - - UInt32 offset = 0; - UInt32 matchMinPos = (_pos > _cyclicBufferSize) ? (_pos - _cyclicBufferSize) : 0; - UInt32 cur = _bufferOffset + _pos; - UInt32 maxLen = kStartMaxLen; // to avoid items for len < hashSize; - UInt32 hashValue, hash2Value = 0, hash3Value = 0; - - if (HASH_ARRAY) - { - UInt32 temp = CRC.Table[_bufferBase[cur]] ^ _bufferBase[cur + 1]; - hash2Value = temp & (kHash2Size - 1); - temp ^= ((UInt32)(_bufferBase[cur + 2]) << 8); - hash3Value = temp & (kHash3Size - 1); - hashValue = (temp ^ (CRC.Table[_bufferBase[cur + 3]] << 5)) & _hashMask; - } - else - hashValue = _bufferBase[cur] ^ ((UInt32)(_bufferBase[cur + 1]) << 8); - - UInt32 curMatch = _hash[kFixHashSize + hashValue]; - if (HASH_ARRAY) - { - UInt32 curMatch2 = _hash[hash2Value]; - UInt32 curMatch3 = _hash[kHash3Offset + hash3Value]; - _hash[hash2Value] = _pos; - _hash[kHash3Offset + hash3Value] = _pos; - if (curMatch2 > matchMinPos) - if (_bufferBase[_bufferOffset + curMatch2] == _bufferBase[cur]) - { - distances[offset++] = maxLen = 2; - distances[offset++] = _pos - curMatch2 - 1; - } - if (curMatch3 > matchMinPos) - if (_bufferBase[_bufferOffset + curMatch3] == _bufferBase[cur]) - { - if (curMatch3 == curMatch2) - offset -= 2; - distances[offset++] = maxLen = 3; - distances[offset++] = _pos - curMatch3 - 1; - curMatch2 = curMatch3; - } - if (offset != 0 && curMatch2 == curMatch) - { - offset -= 2; - maxLen = kStartMaxLen; - } - } - - _hash[kFixHashSize + hashValue] = _pos; - - UInt32 ptr0 = (_cyclicBufferPos << 1) + 1; - UInt32 ptr1 = (_cyclicBufferPos << 1); - - UInt32 len0, len1; - len0 = len1 = kNumHashDirectBytes; - - if (kNumHashDirectBytes != 0) - { - if (curMatch > matchMinPos) - { - if (_bufferBase[_bufferOffset + curMatch + kNumHashDirectBytes] != - _bufferBase[cur + kNumHashDirectBytes]) - { - distances[offset++] = maxLen = kNumHashDirectBytes; - distances[offset++] = _pos - curMatch - 1; - } - } - } - - UInt32 count = _cutValue; - - while(true) - { - if(curMatch <= matchMinPos || count-- == 0) - { - _son[ptr0] = _son[ptr1] = kEmptyHashValue; - break; - } - UInt32 delta = _pos - curMatch; - UInt32 cyclicPos = ((delta <= _cyclicBufferPos) ? - (_cyclicBufferPos - delta) : - (_cyclicBufferPos - delta + _cyclicBufferSize)) << 1; - - UInt32 pby1 = _bufferOffset + curMatch; - UInt32 len = Math.Min(len0, len1); - if (_bufferBase[pby1 + len] == _bufferBase[cur + len]) - { - while(++len != lenLimit) - if (_bufferBase[pby1 + len] != _bufferBase[cur + len]) - break; - if (maxLen < len) - { - distances[offset++] = maxLen = len; - distances[offset++] = delta - 1; - if (len == lenLimit) - { - _son[ptr1] = _son[cyclicPos]; - _son[ptr0] = _son[cyclicPos + 1]; - break; - } - } - } - if (_bufferBase[pby1 + len] < _bufferBase[cur + len]) - { - _son[ptr1] = curMatch; - ptr1 = cyclicPos + 1; - curMatch = _son[ptr1]; - len1 = len; - } - else - { - _son[ptr0] = curMatch; - ptr0 = cyclicPos; - curMatch = _son[ptr0]; - len0 = len; - } - } - MovePos(); - return offset; - } - - public void Skip(UInt32 num) - { - do - { - UInt32 lenLimit; - if (_pos + _matchMaxLen <= _streamPos) - lenLimit = _matchMaxLen; - else - { - lenLimit = _streamPos - _pos; - if (lenLimit < kMinMatchCheck) - { - MovePos(); - continue; - } - } - - UInt32 matchMinPos = (_pos > _cyclicBufferSize) ? (_pos - _cyclicBufferSize) : 0; - UInt32 cur = _bufferOffset + _pos; - - UInt32 hashValue; - - if (HASH_ARRAY) - { - UInt32 temp = CRC.Table[_bufferBase[cur]] ^ _bufferBase[cur + 1]; - UInt32 hash2Value = temp & (kHash2Size - 1); - _hash[hash2Value] = _pos; - temp ^= ((UInt32)(_bufferBase[cur + 2]) << 8); - UInt32 hash3Value = temp & (kHash3Size - 1); - _hash[kHash3Offset + hash3Value] = _pos; - hashValue = (temp ^ (CRC.Table[_bufferBase[cur + 3]] << 5)) & _hashMask; - } - else - hashValue = _bufferBase[cur] ^ ((UInt32)(_bufferBase[cur + 1]) << 8); - - UInt32 curMatch = _hash[kFixHashSize + hashValue]; - _hash[kFixHashSize + hashValue] = _pos; - - UInt32 ptr0 = (_cyclicBufferPos << 1) + 1; - UInt32 ptr1 = (_cyclicBufferPos << 1); - - UInt32 len0, len1; - len0 = len1 = kNumHashDirectBytes; - - UInt32 count = _cutValue; - while (true) - { - if (curMatch <= matchMinPos || count-- == 0) - { - _son[ptr0] = _son[ptr1] = kEmptyHashValue; - break; - } - - UInt32 delta = _pos - curMatch; - UInt32 cyclicPos = ((delta <= _cyclicBufferPos) ? - (_cyclicBufferPos - delta) : - (_cyclicBufferPos - delta + _cyclicBufferSize)) << 1; - - UInt32 pby1 = _bufferOffset + curMatch; - UInt32 len = Math.Min(len0, len1); - if (_bufferBase[pby1 + len] == _bufferBase[cur + len]) - { - while (++len != lenLimit) - if (_bufferBase[pby1 + len] != _bufferBase[cur + len]) - break; - if (len == lenLimit) - { - _son[ptr1] = _son[cyclicPos]; - _son[ptr0] = _son[cyclicPos + 1]; - break; - } - } - if (_bufferBase[pby1 + len] < _bufferBase[cur + len]) - { - _son[ptr1] = curMatch; - ptr1 = cyclicPos + 1; - curMatch = _son[ptr1]; - len1 = len; - } - else - { - _son[ptr0] = curMatch; - ptr0 = cyclicPos; - curMatch = _son[ptr0]; - len0 = len; - } - } - MovePos(); - } - while (--num != 0); - } - - void NormalizeLinks(UInt32[] items, UInt32 numItems, UInt32 subValue) - { - for (UInt32 i = 0; i < numItems; i++) - { - UInt32 value = items[i]; - if (value <= subValue) - value = kEmptyHashValue; - else - value -= subValue; - items[i] = value; - } - } - - void Normalize() - { - UInt32 subValue = _pos - _cyclicBufferSize; - NormalizeLinks(_son, _cyclicBufferSize * 2, subValue); - NormalizeLinks(_hash, _hashSizeSum, subValue); - ReduceOffsets((Int32)subValue); - } - - public void SetCutValue(UInt32 cutValue) { _cutValue = cutValue; } - } -} diff --git a/Editor/3rds/7zip/Compress/LZ/LzBinTree.cs.meta b/Editor/3rds/7zip/Compress/LZ/LzBinTree.cs.meta deleted file mode 100644 index 49637e8..0000000 --- a/Editor/3rds/7zip/Compress/LZ/LzBinTree.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 3ba8015d2d5df3a459615ffc06635e6d -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/3rds/7zip/Compress/LZ/LzInWindow.cs b/Editor/3rds/7zip/Compress/LZ/LzInWindow.cs deleted file mode 100644 index 52d23ce..0000000 --- a/Editor/3rds/7zip/Compress/LZ/LzInWindow.cs +++ /dev/null @@ -1,132 +0,0 @@ -// LzInWindow.cs - -using System; - -namespace SevenZip.Compression.LZ -{ - public class InWindow - { - public Byte[] _bufferBase = null; // pointer to buffer with data - System.IO.Stream _stream; - UInt32 _posLimit; // offset (from _buffer) of first byte when new block reading must be done - bool _streamEndWasReached; // if (true) then _streamPos shows real end of stream - - UInt32 _pointerToLastSafePosition; - - public UInt32 _bufferOffset; - - public UInt32 _blockSize; // Size of Allocated memory block - public UInt32 _pos; // offset (from _buffer) of curent byte - UInt32 _keepSizeBefore; // how many BYTEs must be kept in buffer before _pos - UInt32 _keepSizeAfter; // how many BYTEs must be kept buffer after _pos - public UInt32 _streamPos; // offset (from _buffer) of first not read byte from Stream - - public void MoveBlock() - { - UInt32 offset = (UInt32)(_bufferOffset) + _pos - _keepSizeBefore; - // we need one additional byte, since MovePos moves on 1 byte. - if (offset > 0) - offset--; - - UInt32 numBytes = (UInt32)(_bufferOffset) + _streamPos - offset; - - // check negative offset ???? - for (UInt32 i = 0; i < numBytes; i++) - _bufferBase[i] = _bufferBase[offset + i]; - _bufferOffset -= offset; - } - - public virtual void ReadBlock() - { - if (_streamEndWasReached) - return; - while (true) - { - int size = (int)((0 - _bufferOffset) + _blockSize - _streamPos); - if (size == 0) - return; - int numReadBytes = _stream.Read(_bufferBase, (int)(_bufferOffset + _streamPos), size); - if (numReadBytes == 0) - { - _posLimit = _streamPos; - UInt32 pointerToPostion = _bufferOffset + _posLimit; - if (pointerToPostion > _pointerToLastSafePosition) - _posLimit = (UInt32)(_pointerToLastSafePosition - _bufferOffset); - - _streamEndWasReached = true; - return; - } - _streamPos += (UInt32)numReadBytes; - if (_streamPos >= _pos + _keepSizeAfter) - _posLimit = _streamPos - _keepSizeAfter; - } - } - - void Free() { _bufferBase = null; } - - public void Create(UInt32 keepSizeBefore, UInt32 keepSizeAfter, UInt32 keepSizeReserv) - { - _keepSizeBefore = keepSizeBefore; - _keepSizeAfter = keepSizeAfter; - UInt32 blockSize = keepSizeBefore + keepSizeAfter + keepSizeReserv; - if (_bufferBase == null || _blockSize != blockSize) - { - Free(); - _blockSize = blockSize; - _bufferBase = new Byte[_blockSize]; - } - _pointerToLastSafePosition = _blockSize - keepSizeAfter; - } - - public void SetStream(System.IO.Stream stream) { _stream = stream; } - public void ReleaseStream() { _stream = null; } - - public void Init() - { - _bufferOffset = 0; - _pos = 0; - _streamPos = 0; - _streamEndWasReached = false; - ReadBlock(); - } - - public void MovePos() - { - _pos++; - if (_pos > _posLimit) - { - UInt32 pointerToPostion = _bufferOffset + _pos; - if (pointerToPostion > _pointerToLastSafePosition) - MoveBlock(); - ReadBlock(); - } - } - - public Byte GetIndexByte(Int32 index) { return _bufferBase[_bufferOffset + _pos + index]; } - - // index + limit have not to exceed _keepSizeAfter; - public UInt32 GetMatchLen(Int32 index, UInt32 distance, UInt32 limit) - { - if (_streamEndWasReached) - if ((_pos + index) + limit > _streamPos) - limit = _streamPos - (UInt32)(_pos + index); - distance++; - // Byte *pby = _buffer + (size_t)_pos + index; - UInt32 pby = _bufferOffset + _pos + (UInt32)index; - - UInt32 i; - for (i = 0; i < limit && _bufferBase[pby + i] == _bufferBase[pby + i - distance]; i++); - return i; - } - - public UInt32 GetNumAvailableBytes() { return _streamPos - _pos; } - - public void ReduceOffsets(Int32 subValue) - { - _bufferOffset += (UInt32)subValue; - _posLimit -= (UInt32)subValue; - _pos -= (UInt32)subValue; - _streamPos -= (UInt32)subValue; - } - } -} diff --git a/Editor/3rds/7zip/Compress/LZ/LzInWindow.cs.meta b/Editor/3rds/7zip/Compress/LZ/LzInWindow.cs.meta deleted file mode 100644 index f1e45d6..0000000 --- a/Editor/3rds/7zip/Compress/LZ/LzInWindow.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 333112c3785a6ec4cbbfec8515081cac -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/3rds/7zip/Compress/LZ/LzOutWindow.cs b/Editor/3rds/7zip/Compress/LZ/LzOutWindow.cs deleted file mode 100644 index c998584..0000000 --- a/Editor/3rds/7zip/Compress/LZ/LzOutWindow.cs +++ /dev/null @@ -1,110 +0,0 @@ -// LzOutWindow.cs - -namespace SevenZip.Compression.LZ -{ - public class OutWindow - { - byte[] _buffer = null; - uint _pos; - uint _windowSize = 0; - uint _streamPos; - System.IO.Stream _stream; - - public uint TrainSize = 0; - - public void Create(uint windowSize) - { - if (_windowSize != windowSize) - { - // System.GC.Collect(); - _buffer = new byte[windowSize]; - } - _windowSize = windowSize; - _pos = 0; - _streamPos = 0; - } - - public void Init(System.IO.Stream stream, bool solid) - { - ReleaseStream(); - _stream = stream; - if (!solid) - { - _streamPos = 0; - _pos = 0; - TrainSize = 0; - } - } - - public bool Train(System.IO.Stream stream) - { - long len = stream.Length; - uint size = (len < _windowSize) ? (uint)len : _windowSize; - TrainSize = size; - stream.Position = len - size; - _streamPos = _pos = 0; - while (size > 0) - { - uint curSize = _windowSize - _pos; - if (size < curSize) - curSize = size; - int numReadBytes = stream.Read(_buffer, (int)_pos, (int)curSize); - if (numReadBytes == 0) - return false; - size -= (uint)numReadBytes; - _pos += (uint)numReadBytes; - _streamPos += (uint)numReadBytes; - if (_pos == _windowSize) - _streamPos = _pos = 0; - } - return true; - } - - public void ReleaseStream() - { - Flush(); - _stream = null; - } - - public void Flush() - { - uint size = _pos - _streamPos; - if (size == 0) - return; - _stream.Write(_buffer, (int)_streamPos, (int)size); - if (_pos >= _windowSize) - _pos = 0; - _streamPos = _pos; - } - - public void CopyBlock(uint distance, uint len) - { - uint pos = _pos - distance - 1; - if (pos >= _windowSize) - pos += _windowSize; - for (; len > 0; len--) - { - if (pos >= _windowSize) - pos = 0; - _buffer[_pos++] = _buffer[pos++]; - if (_pos >= _windowSize) - Flush(); - } - } - - public void PutByte(byte b) - { - _buffer[_pos++] = b; - if (_pos >= _windowSize) - Flush(); - } - - public byte GetByte(uint distance) - { - uint pos = _pos - distance - 1; - if (pos >= _windowSize) - pos += _windowSize; - return _buffer[pos]; - } - } -} diff --git a/Editor/3rds/7zip/Compress/LZ/LzOutWindow.cs.meta b/Editor/3rds/7zip/Compress/LZ/LzOutWindow.cs.meta deleted file mode 100644 index 7b3f534..0000000 --- a/Editor/3rds/7zip/Compress/LZ/LzOutWindow.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: bb296a6e14ab7c44cb6388693d581a62 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/3rds/7zip/Compress/LZMA.meta b/Editor/3rds/7zip/Compress/LZMA.meta deleted file mode 100644 index 5c45968..0000000 --- a/Editor/3rds/7zip/Compress/LZMA.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 5fcd2f5c8b724164a8a01cee73896d1a -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/3rds/7zip/Compress/LZMA/LzmaBase.cs b/Editor/3rds/7zip/Compress/LZMA/LzmaBase.cs deleted file mode 100644 index c7bca86..0000000 --- a/Editor/3rds/7zip/Compress/LZMA/LzmaBase.cs +++ /dev/null @@ -1,76 +0,0 @@ -// LzmaBase.cs - -namespace SevenZip.Compression.LZMA -{ - internal abstract class Base - { - public const uint kNumRepDistances = 4; - public const uint kNumStates = 12; - - // static byte []kLiteralNextStates = {0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 4, 5}; - // static byte []kMatchNextStates = {7, 7, 7, 7, 7, 7, 7, 10, 10, 10, 10, 10}; - // static byte []kRepNextStates = {8, 8, 8, 8, 8, 8, 8, 11, 11, 11, 11, 11}; - // static byte []kShortRepNextStates = {9, 9, 9, 9, 9, 9, 9, 11, 11, 11, 11, 11}; - - public struct State - { - public uint Index; - public void Init() { Index = 0; } - public void UpdateChar() - { - if (Index < 4) Index = 0; - else if (Index < 10) Index -= 3; - else Index -= 6; - } - public void UpdateMatch() { Index = (uint)(Index < 7 ? 7 : 10); } - public void UpdateRep() { Index = (uint)(Index < 7 ? 8 : 11); } - public void UpdateShortRep() { Index = (uint)(Index < 7 ? 9 : 11); } - public bool IsCharState() { return Index < 7; } - } - - public const int kNumPosSlotBits = 6; - public const int kDicLogSizeMin = 0; - // public const int kDicLogSizeMax = 30; - // public const uint kDistTableSizeMax = kDicLogSizeMax * 2; - - public const int kNumLenToPosStatesBits = 2; // it's for speed optimization - public const uint kNumLenToPosStates = 1 << kNumLenToPosStatesBits; - - public const uint kMatchMinLen = 2; - - public static uint GetLenToPosState(uint len) - { - len -= kMatchMinLen; - if (len < kNumLenToPosStates) - return len; - return (uint)(kNumLenToPosStates - 1); - } - - public const int kNumAlignBits = 4; - public const uint kAlignTableSize = 1 << kNumAlignBits; - public const uint kAlignMask = (kAlignTableSize - 1); - - public const uint kStartPosModelIndex = 4; - public const uint kEndPosModelIndex = 14; - public const uint kNumPosModels = kEndPosModelIndex - kStartPosModelIndex; - - public const uint kNumFullDistances = 1 << ((int)kEndPosModelIndex / 2); - - public const uint kNumLitPosStatesBitsEncodingMax = 4; - public const uint kNumLitContextBitsMax = 8; - - public const int kNumPosStatesBitsMax = 4; - public const uint kNumPosStatesMax = (1 << kNumPosStatesBitsMax); - public const int kNumPosStatesBitsEncodingMax = 4; - public const uint kNumPosStatesEncodingMax = (1 << kNumPosStatesBitsEncodingMax); - - public const int kNumLowLenBits = 3; - public const int kNumMidLenBits = 3; - public const int kNumHighLenBits = 8; - public const uint kNumLowLenSymbols = 1 << kNumLowLenBits; - public const uint kNumMidLenSymbols = 1 << kNumMidLenBits; - public const uint kNumLenSymbols = kNumLowLenSymbols + kNumMidLenSymbols + - (1 << kNumHighLenBits); - public const uint kMatchMaxLen = kMatchMinLen + kNumLenSymbols - 1; - } -} diff --git a/Editor/3rds/7zip/Compress/LZMA/LzmaBase.cs.meta b/Editor/3rds/7zip/Compress/LZMA/LzmaBase.cs.meta deleted file mode 100644 index 10b16ed..0000000 --- a/Editor/3rds/7zip/Compress/LZMA/LzmaBase.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 62f365191077342479f8227edadf57e3 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/3rds/7zip/Compress/LZMA/LzmaDecoder.cs b/Editor/3rds/7zip/Compress/LZMA/LzmaDecoder.cs deleted file mode 100644 index a9be39f..0000000 --- a/Editor/3rds/7zip/Compress/LZMA/LzmaDecoder.cs +++ /dev/null @@ -1,398 +0,0 @@ -// LzmaDecoder.cs - -using System; - -namespace SevenZip.Compression.LZMA -{ - using RangeCoder; - - public class Decoder : ICoder, ISetDecoderProperties // ,System.IO.Stream - { - class LenDecoder - { - BitDecoder m_Choice = new BitDecoder(); - BitDecoder m_Choice2 = new BitDecoder(); - BitTreeDecoder[] m_LowCoder = new BitTreeDecoder[Base.kNumPosStatesMax]; - BitTreeDecoder[] m_MidCoder = new BitTreeDecoder[Base.kNumPosStatesMax]; - BitTreeDecoder m_HighCoder = new BitTreeDecoder(Base.kNumHighLenBits); - uint m_NumPosStates = 0; - - public void Create(uint numPosStates) - { - for (uint posState = m_NumPosStates; posState < numPosStates; posState++) - { - m_LowCoder[posState] = new BitTreeDecoder(Base.kNumLowLenBits); - m_MidCoder[posState] = new BitTreeDecoder(Base.kNumMidLenBits); - } - m_NumPosStates = numPosStates; - } - - public void Init() - { - m_Choice.Init(); - for (uint posState = 0; posState < m_NumPosStates; posState++) - { - m_LowCoder[posState].Init(); - m_MidCoder[posState].Init(); - } - m_Choice2.Init(); - m_HighCoder.Init(); - } - - public uint Decode(RangeCoder.Decoder rangeDecoder, uint posState) - { - if (m_Choice.Decode(rangeDecoder) == 0) - return m_LowCoder[posState].Decode(rangeDecoder); - else - { - uint symbol = Base.kNumLowLenSymbols; - if (m_Choice2.Decode(rangeDecoder) == 0) - symbol += m_MidCoder[posState].Decode(rangeDecoder); - else - { - symbol += Base.kNumMidLenSymbols; - symbol += m_HighCoder.Decode(rangeDecoder); - } - return symbol; - } - } - } - - class LiteralDecoder - { - struct Decoder2 - { - BitDecoder[] m_Decoders; - public void Create() { m_Decoders = new BitDecoder[0x300]; } - public void Init() { for (int i = 0; i < 0x300; i++) m_Decoders[i].Init(); } - - public byte DecodeNormal(RangeCoder.Decoder rangeDecoder) - { - uint symbol = 1; - do - symbol = (symbol << 1) | m_Decoders[symbol].Decode(rangeDecoder); - while (symbol < 0x100); - return (byte)symbol; - } - - public byte DecodeWithMatchByte(RangeCoder.Decoder rangeDecoder, byte matchByte) - { - uint symbol = 1; - do - { - uint matchBit = (uint)(matchByte >> 7) & 1; - matchByte <<= 1; - uint bit = m_Decoders[((1 + matchBit) << 8) + symbol].Decode(rangeDecoder); - symbol = (symbol << 1) | bit; - if (matchBit != bit) - { - while (symbol < 0x100) - symbol = (symbol << 1) | m_Decoders[symbol].Decode(rangeDecoder); - break; - } - } - while (symbol < 0x100); - return (byte)symbol; - } - } - - Decoder2[] m_Coders; - int m_NumPrevBits; - int m_NumPosBits; - uint m_PosMask; - - public void Create(int numPosBits, int numPrevBits) - { - if (m_Coders != null && m_NumPrevBits == numPrevBits && - m_NumPosBits == numPosBits) - return; - m_NumPosBits = numPosBits; - m_PosMask = ((uint)1 << numPosBits) - 1; - m_NumPrevBits = numPrevBits; - uint numStates = (uint)1 << (m_NumPrevBits + m_NumPosBits); - m_Coders = new Decoder2[numStates]; - for (uint i = 0; i < numStates; i++) - m_Coders[i].Create(); - } - - public void Init() - { - uint numStates = (uint)1 << (m_NumPrevBits + m_NumPosBits); - for (uint i = 0; i < numStates; i++) - m_Coders[i].Init(); - } - - uint GetState(uint pos, byte prevByte) - { return ((pos & m_PosMask) << m_NumPrevBits) + (uint)(prevByte >> (8 - m_NumPrevBits)); } - - public byte DecodeNormal(RangeCoder.Decoder rangeDecoder, uint pos, byte prevByte) - { return m_Coders[GetState(pos, prevByte)].DecodeNormal(rangeDecoder); } - - public byte DecodeWithMatchByte(RangeCoder.Decoder rangeDecoder, uint pos, byte prevByte, byte matchByte) - { return m_Coders[GetState(pos, prevByte)].DecodeWithMatchByte(rangeDecoder, matchByte); } - }; - - LZ.OutWindow m_OutWindow = new LZ.OutWindow(); - RangeCoder.Decoder m_RangeDecoder = new RangeCoder.Decoder(); - - BitDecoder[] m_IsMatchDecoders = new BitDecoder[Base.kNumStates << Base.kNumPosStatesBitsMax]; - BitDecoder[] m_IsRepDecoders = new BitDecoder[Base.kNumStates]; - BitDecoder[] m_IsRepG0Decoders = new BitDecoder[Base.kNumStates]; - BitDecoder[] m_IsRepG1Decoders = new BitDecoder[Base.kNumStates]; - BitDecoder[] m_IsRepG2Decoders = new BitDecoder[Base.kNumStates]; - BitDecoder[] m_IsRep0LongDecoders = new BitDecoder[Base.kNumStates << Base.kNumPosStatesBitsMax]; - - BitTreeDecoder[] m_PosSlotDecoder = new BitTreeDecoder[Base.kNumLenToPosStates]; - BitDecoder[] m_PosDecoders = new BitDecoder[Base.kNumFullDistances - Base.kEndPosModelIndex]; - - BitTreeDecoder m_PosAlignDecoder = new BitTreeDecoder(Base.kNumAlignBits); - - LenDecoder m_LenDecoder = new LenDecoder(); - LenDecoder m_RepLenDecoder = new LenDecoder(); - - LiteralDecoder m_LiteralDecoder = new LiteralDecoder(); - - uint m_DictionarySize; - uint m_DictionarySizeCheck; - - uint m_PosStateMask; - - public Decoder() - { - m_DictionarySize = 0xFFFFFFFF; - for (int i = 0; i < Base.kNumLenToPosStates; i++) - m_PosSlotDecoder[i] = new BitTreeDecoder(Base.kNumPosSlotBits); - } - - void SetDictionarySize(uint dictionarySize) - { - if (m_DictionarySize != dictionarySize) - { - m_DictionarySize = dictionarySize; - m_DictionarySizeCheck = Math.Max(m_DictionarySize, 1); - uint blockSize = Math.Max(m_DictionarySizeCheck, (1 << 12)); - m_OutWindow.Create(blockSize); - } - } - - void SetLiteralProperties(int lp, int lc) - { - if (lp > 8) - throw new InvalidParamException(); - if (lc > 8) - throw new InvalidParamException(); - m_LiteralDecoder.Create(lp, lc); - } - - void SetPosBitsProperties(int pb) - { - if (pb > Base.kNumPosStatesBitsMax) - throw new InvalidParamException(); - uint numPosStates = (uint)1 << pb; - m_LenDecoder.Create(numPosStates); - m_RepLenDecoder.Create(numPosStates); - m_PosStateMask = numPosStates - 1; - } - - bool _solid = false; - void Init(System.IO.Stream inStream, System.IO.Stream outStream) - { - m_RangeDecoder.Init(inStream); - m_OutWindow.Init(outStream, _solid); - - uint i; - for (i = 0; i < Base.kNumStates; i++) - { - for (uint j = 0; j <= m_PosStateMask; j++) - { - uint index = (i << Base.kNumPosStatesBitsMax) + j; - m_IsMatchDecoders[index].Init(); - m_IsRep0LongDecoders[index].Init(); - } - m_IsRepDecoders[i].Init(); - m_IsRepG0Decoders[i].Init(); - m_IsRepG1Decoders[i].Init(); - m_IsRepG2Decoders[i].Init(); - } - - m_LiteralDecoder.Init(); - for (i = 0; i < Base.kNumLenToPosStates; i++) - m_PosSlotDecoder[i].Init(); - // m_PosSpecDecoder.Init(); - for (i = 0; i < Base.kNumFullDistances - Base.kEndPosModelIndex; i++) - m_PosDecoders[i].Init(); - - m_LenDecoder.Init(); - m_RepLenDecoder.Init(); - m_PosAlignDecoder.Init(); - } - - public void Code(System.IO.Stream inStream, System.IO.Stream outStream, - Int64 inSize, Int64 outSize, ICodeProgress progress) - { - Init(inStream, outStream); - - Base.State state = new Base.State(); - state.Init(); - uint rep0 = 0, rep1 = 0, rep2 = 0, rep3 = 0; - - UInt64 nowPos64 = 0; - UInt64 outSize64 = (UInt64)outSize; - if (nowPos64 < outSize64) - { - if (m_IsMatchDecoders[state.Index << Base.kNumPosStatesBitsMax].Decode(m_RangeDecoder) != 0) - throw new DataErrorException(); - state.UpdateChar(); - byte b = m_LiteralDecoder.DecodeNormal(m_RangeDecoder, 0, 0); - m_OutWindow.PutByte(b); - nowPos64++; - } - while (nowPos64 < outSize64) - { - // UInt64 next = Math.Min(nowPos64 + (1 << 18), outSize64); - // while(nowPos64 < next) - { - uint posState = (uint)nowPos64 & m_PosStateMask; - if (m_IsMatchDecoders[(state.Index << Base.kNumPosStatesBitsMax) + posState].Decode(m_RangeDecoder) == 0) - { - byte b; - byte prevByte = m_OutWindow.GetByte(0); - if (!state.IsCharState()) - b = m_LiteralDecoder.DecodeWithMatchByte(m_RangeDecoder, - (uint)nowPos64, prevByte, m_OutWindow.GetByte(rep0)); - else - b = m_LiteralDecoder.DecodeNormal(m_RangeDecoder, (uint)nowPos64, prevByte); - m_OutWindow.PutByte(b); - state.UpdateChar(); - nowPos64++; - } - else - { - uint len; - if (m_IsRepDecoders[state.Index].Decode(m_RangeDecoder) == 1) - { - if (m_IsRepG0Decoders[state.Index].Decode(m_RangeDecoder) == 0) - { - if (m_IsRep0LongDecoders[(state.Index << Base.kNumPosStatesBitsMax) + posState].Decode(m_RangeDecoder) == 0) - { - state.UpdateShortRep(); - m_OutWindow.PutByte(m_OutWindow.GetByte(rep0)); - nowPos64++; - continue; - } - } - else - { - UInt32 distance; - if (m_IsRepG1Decoders[state.Index].Decode(m_RangeDecoder) == 0) - { - distance = rep1; - } - else - { - if (m_IsRepG2Decoders[state.Index].Decode(m_RangeDecoder) == 0) - distance = rep2; - else - { - distance = rep3; - rep3 = rep2; - } - rep2 = rep1; - } - rep1 = rep0; - rep0 = distance; - } - len = m_RepLenDecoder.Decode(m_RangeDecoder, posState) + Base.kMatchMinLen; - state.UpdateRep(); - } - else - { - rep3 = rep2; - rep2 = rep1; - rep1 = rep0; - len = Base.kMatchMinLen + m_LenDecoder.Decode(m_RangeDecoder, posState); - state.UpdateMatch(); - uint posSlot = m_PosSlotDecoder[Base.GetLenToPosState(len)].Decode(m_RangeDecoder); - if (posSlot >= Base.kStartPosModelIndex) - { - int numDirectBits = (int)((posSlot >> 1) - 1); - rep0 = ((2 | (posSlot & 1)) << numDirectBits); - if (posSlot < Base.kEndPosModelIndex) - rep0 += BitTreeDecoder.ReverseDecode(m_PosDecoders, - rep0 - posSlot - 1, m_RangeDecoder, numDirectBits); - else - { - rep0 += (m_RangeDecoder.DecodeDirectBits( - numDirectBits - Base.kNumAlignBits) << Base.kNumAlignBits); - rep0 += m_PosAlignDecoder.ReverseDecode(m_RangeDecoder); - } - } - else - rep0 = posSlot; - } - if (rep0 >= m_OutWindow.TrainSize + nowPos64 || rep0 >= m_DictionarySizeCheck) - { - if (rep0 == 0xFFFFFFFF) - break; - throw new DataErrorException(); - } - m_OutWindow.CopyBlock(rep0, len); - nowPos64 += len; - } - } - } - m_OutWindow.Flush(); - m_OutWindow.ReleaseStream(); - m_RangeDecoder.ReleaseStream(); - } - - public void SetDecoderProperties(byte[] properties) - { - if (properties.Length < 5) - throw new InvalidParamException(); - int lc = properties[0] % 9; - int remainder = properties[0] / 9; - int lp = remainder % 5; - int pb = remainder / 5; - if (pb > Base.kNumPosStatesBitsMax) - throw new InvalidParamException(); - UInt32 dictionarySize = 0; - for (int i = 0; i < 4; i++) - dictionarySize += ((UInt32)(properties[1 + i])) << (i * 8); - SetDictionarySize(dictionarySize); - SetLiteralProperties(lp, lc); - SetPosBitsProperties(pb); - } - - public bool Train(System.IO.Stream stream) - { - _solid = true; - return m_OutWindow.Train(stream); - } - - /* - public override bool CanRead { get { return true; }} - public override bool CanWrite { get { return true; }} - public override bool CanSeek { get { return true; }} - public override long Length { get { return 0; }} - public override long Position - { - get { return 0; } - set { } - } - public override void Flush() { } - public override int Read(byte[] buffer, int offset, int count) - { - return 0; - } - public override void Write(byte[] buffer, int offset, int count) - { - } - public override long Seek(long offset, System.IO.SeekOrigin origin) - { - return 0; - } - public override void SetLength(long value) {} - */ - } -} diff --git a/Editor/3rds/7zip/Compress/LZMA/LzmaDecoder.cs.meta b/Editor/3rds/7zip/Compress/LZMA/LzmaDecoder.cs.meta deleted file mode 100644 index 2725167..0000000 --- a/Editor/3rds/7zip/Compress/LZMA/LzmaDecoder.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: c60a9ce2c6df6774498e337ad69a356b -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/3rds/7zip/Compress/LZMA/LzmaEncoder.cs b/Editor/3rds/7zip/Compress/LZMA/LzmaEncoder.cs deleted file mode 100644 index 0237c51..0000000 --- a/Editor/3rds/7zip/Compress/LZMA/LzmaEncoder.cs +++ /dev/null @@ -1,1480 +0,0 @@ -// LzmaEncoder.cs - -using System; - -namespace SevenZip.Compression.LZMA -{ - using RangeCoder; - - public class Encoder : ICoder, ISetCoderProperties, IWriteCoderProperties - { - enum EMatchFinderType - { - BT2, - BT4, - }; - - const UInt32 kIfinityPrice = 0xFFFFFFF; - - static Byte[] g_FastPos = new Byte[1 << 11]; - - static Encoder() - { - const Byte kFastSlots = 22; - int c = 2; - g_FastPos[0] = 0; - g_FastPos[1] = 1; - for (Byte slotFast = 2; slotFast < kFastSlots; slotFast++) - { - UInt32 k = ((UInt32)1 << ((slotFast >> 1) - 1)); - for (UInt32 j = 0; j < k; j++, c++) - g_FastPos[c] = slotFast; - } - } - - static UInt32 GetPosSlot(UInt32 pos) - { - if (pos < (1 << 11)) - return g_FastPos[pos]; - if (pos < (1 << 21)) - return (UInt32)(g_FastPos[pos >> 10] + 20); - return (UInt32)(g_FastPos[pos >> 20] + 40); - } - - static UInt32 GetPosSlot2(UInt32 pos) - { - if (pos < (1 << 17)) - return (UInt32)(g_FastPos[pos >> 6] + 12); - if (pos < (1 << 27)) - return (UInt32)(g_FastPos[pos >> 16] + 32); - return (UInt32)(g_FastPos[pos >> 26] + 52); - } - - Base.State _state = new Base.State(); - Byte _previousByte; - UInt32[] _repDistances = new UInt32[Base.kNumRepDistances]; - - void BaseInit() - { - _state.Init(); - _previousByte = 0; - for (UInt32 i = 0; i < Base.kNumRepDistances; i++) - _repDistances[i] = 0; - } - - const int kDefaultDictionaryLogSize = 22; - const UInt32 kNumFastBytesDefault = 0x20; - - class LiteralEncoder - { - public struct Encoder2 - { - BitEncoder[] m_Encoders; - - public void Create() { m_Encoders = new BitEncoder[0x300]; } - - public void Init() { for (int i = 0; i < 0x300; i++) m_Encoders[i].Init(); } - - public void Encode(RangeCoder.Encoder rangeEncoder, byte symbol) - { - uint context = 1; - for (int i = 7; i >= 0; i--) - { - uint bit = (uint)((symbol >> i) & 1); - m_Encoders[context].Encode(rangeEncoder, bit); - context = (context << 1) | bit; - } - } - - public void EncodeMatched(RangeCoder.Encoder rangeEncoder, byte matchByte, byte symbol) - { - uint context = 1; - bool same = true; - for (int i = 7; i >= 0; i--) - { - uint bit = (uint)((symbol >> i) & 1); - uint state = context; - if (same) - { - uint matchBit = (uint)((matchByte >> i) & 1); - state += ((1 + matchBit) << 8); - same = (matchBit == bit); - } - m_Encoders[state].Encode(rangeEncoder, bit); - context = (context << 1) | bit; - } - } - - public uint GetPrice(bool matchMode, byte matchByte, byte symbol) - { - uint price = 0; - uint context = 1; - int i = 7; - if (matchMode) - { - for (; i >= 0; i--) - { - uint matchBit = (uint)(matchByte >> i) & 1; - uint bit = (uint)(symbol >> i) & 1; - price += m_Encoders[((1 + matchBit) << 8) + context].GetPrice(bit); - context = (context << 1) | bit; - if (matchBit != bit) - { - i--; - break; - } - } - } - for (; i >= 0; i--) - { - uint bit = (uint)(symbol >> i) & 1; - price += m_Encoders[context].GetPrice(bit); - context = (context << 1) | bit; - } - return price; - } - } - - Encoder2[] m_Coders; - int m_NumPrevBits; - int m_NumPosBits; - uint m_PosMask; - - public void Create(int numPosBits, int numPrevBits) - { - if (m_Coders != null && m_NumPrevBits == numPrevBits && m_NumPosBits == numPosBits) - return; - m_NumPosBits = numPosBits; - m_PosMask = ((uint)1 << numPosBits) - 1; - m_NumPrevBits = numPrevBits; - uint numStates = (uint)1 << (m_NumPrevBits + m_NumPosBits); - m_Coders = new Encoder2[numStates]; - for (uint i = 0; i < numStates; i++) - m_Coders[i].Create(); - } - - public void Init() - { - uint numStates = (uint)1 << (m_NumPrevBits + m_NumPosBits); - for (uint i = 0; i < numStates; i++) - m_Coders[i].Init(); - } - - public Encoder2 GetSubCoder(UInt32 pos, Byte prevByte) - { return m_Coders[((pos & m_PosMask) << m_NumPrevBits) + (uint)(prevByte >> (8 - m_NumPrevBits))]; } - } - - class LenEncoder - { - RangeCoder.BitEncoder _choice = new RangeCoder.BitEncoder(); - RangeCoder.BitEncoder _choice2 = new RangeCoder.BitEncoder(); - RangeCoder.BitTreeEncoder[] _lowCoder = new RangeCoder.BitTreeEncoder[Base.kNumPosStatesEncodingMax]; - RangeCoder.BitTreeEncoder[] _midCoder = new RangeCoder.BitTreeEncoder[Base.kNumPosStatesEncodingMax]; - RangeCoder.BitTreeEncoder _highCoder = new RangeCoder.BitTreeEncoder(Base.kNumHighLenBits); - - public LenEncoder() - { - for (UInt32 posState = 0; posState < Base.kNumPosStatesEncodingMax; posState++) - { - _lowCoder[posState] = new RangeCoder.BitTreeEncoder(Base.kNumLowLenBits); - _midCoder[posState] = new RangeCoder.BitTreeEncoder(Base.kNumMidLenBits); - } - } - - public void Init(UInt32 numPosStates) - { - _choice.Init(); - _choice2.Init(); - for (UInt32 posState = 0; posState < numPosStates; posState++) - { - _lowCoder[posState].Init(); - _midCoder[posState].Init(); - } - _highCoder.Init(); - } - - public void Encode(RangeCoder.Encoder rangeEncoder, UInt32 symbol, UInt32 posState) - { - if (symbol < Base.kNumLowLenSymbols) - { - _choice.Encode(rangeEncoder, 0); - _lowCoder[posState].Encode(rangeEncoder, symbol); - } - else - { - symbol -= Base.kNumLowLenSymbols; - _choice.Encode(rangeEncoder, 1); - if (symbol < Base.kNumMidLenSymbols) - { - _choice2.Encode(rangeEncoder, 0); - _midCoder[posState].Encode(rangeEncoder, symbol); - } - else - { - _choice2.Encode(rangeEncoder, 1); - _highCoder.Encode(rangeEncoder, symbol - Base.kNumMidLenSymbols); - } - } - } - - public void SetPrices(UInt32 posState, UInt32 numSymbols, UInt32[] prices, UInt32 st) - { - UInt32 a0 = _choice.GetPrice0(); - UInt32 a1 = _choice.GetPrice1(); - UInt32 b0 = a1 + _choice2.GetPrice0(); - UInt32 b1 = a1 + _choice2.GetPrice1(); - UInt32 i = 0; - for (i = 0; i < Base.kNumLowLenSymbols; i++) - { - if (i >= numSymbols) - return; - prices[st + i] = a0 + _lowCoder[posState].GetPrice(i); - } - for (; i < Base.kNumLowLenSymbols + Base.kNumMidLenSymbols; i++) - { - if (i >= numSymbols) - return; - prices[st + i] = b0 + _midCoder[posState].GetPrice(i - Base.kNumLowLenSymbols); - } - for (; i < numSymbols; i++) - prices[st + i] = b1 + _highCoder.GetPrice(i - Base.kNumLowLenSymbols - Base.kNumMidLenSymbols); - } - }; - - const UInt32 kNumLenSpecSymbols = Base.kNumLowLenSymbols + Base.kNumMidLenSymbols; - - class LenPriceTableEncoder : LenEncoder - { - UInt32[] _prices = new UInt32[Base.kNumLenSymbols << Base.kNumPosStatesBitsEncodingMax]; - UInt32 _tableSize; - UInt32[] _counters = new UInt32[Base.kNumPosStatesEncodingMax]; - - public void SetTableSize(UInt32 tableSize) { _tableSize = tableSize; } - - public UInt32 GetPrice(UInt32 symbol, UInt32 posState) - { - return _prices[posState * Base.kNumLenSymbols + symbol]; - } - - void UpdateTable(UInt32 posState) - { - SetPrices(posState, _tableSize, _prices, posState * Base.kNumLenSymbols); - _counters[posState] = _tableSize; - } - - public void UpdateTables(UInt32 numPosStates) - { - for (UInt32 posState = 0; posState < numPosStates; posState++) - UpdateTable(posState); - } - - public new void Encode(RangeCoder.Encoder rangeEncoder, UInt32 symbol, UInt32 posState) - { - base.Encode(rangeEncoder, symbol, posState); - if (--_counters[posState] == 0) - UpdateTable(posState); - } - } - - const UInt32 kNumOpts = 1 << 12; - class Optimal - { - public Base.State State; - - public bool Prev1IsChar; - public bool Prev2; - - public UInt32 PosPrev2; - public UInt32 BackPrev2; - - public UInt32 Price; - public UInt32 PosPrev; - public UInt32 BackPrev; - - public UInt32 Backs0; - public UInt32 Backs1; - public UInt32 Backs2; - public UInt32 Backs3; - - public void MakeAsChar() { BackPrev = 0xFFFFFFFF; Prev1IsChar = false; } - public void MakeAsShortRep() { BackPrev = 0; ; Prev1IsChar = false; } - public bool IsShortRep() { return (BackPrev == 0); } - }; - Optimal[] _optimum = new Optimal[kNumOpts]; - LZ.IMatchFinder _matchFinder = null; - RangeCoder.Encoder _rangeEncoder = new RangeCoder.Encoder(); - - RangeCoder.BitEncoder[] _isMatch = new RangeCoder.BitEncoder[Base.kNumStates << Base.kNumPosStatesBitsMax]; - RangeCoder.BitEncoder[] _isRep = new RangeCoder.BitEncoder[Base.kNumStates]; - RangeCoder.BitEncoder[] _isRepG0 = new RangeCoder.BitEncoder[Base.kNumStates]; - RangeCoder.BitEncoder[] _isRepG1 = new RangeCoder.BitEncoder[Base.kNumStates]; - RangeCoder.BitEncoder[] _isRepG2 = new RangeCoder.BitEncoder[Base.kNumStates]; - RangeCoder.BitEncoder[] _isRep0Long = new RangeCoder.BitEncoder[Base.kNumStates << Base.kNumPosStatesBitsMax]; - - RangeCoder.BitTreeEncoder[] _posSlotEncoder = new RangeCoder.BitTreeEncoder[Base.kNumLenToPosStates]; - - RangeCoder.BitEncoder[] _posEncoders = new RangeCoder.BitEncoder[Base.kNumFullDistances - Base.kEndPosModelIndex]; - RangeCoder.BitTreeEncoder _posAlignEncoder = new RangeCoder.BitTreeEncoder(Base.kNumAlignBits); - - LenPriceTableEncoder _lenEncoder = new LenPriceTableEncoder(); - LenPriceTableEncoder _repMatchLenEncoder = new LenPriceTableEncoder(); - - LiteralEncoder _literalEncoder = new LiteralEncoder(); - - UInt32[] _matchDistances = new UInt32[Base.kMatchMaxLen * 2 + 2]; - - UInt32 _numFastBytes = kNumFastBytesDefault; - UInt32 _longestMatchLength; - UInt32 _numDistancePairs; - - UInt32 _additionalOffset; - - UInt32 _optimumEndIndex; - UInt32 _optimumCurrentIndex; - - bool _longestMatchWasFound; - - UInt32[] _posSlotPrices = new UInt32[1 << (Base.kNumPosSlotBits + Base.kNumLenToPosStatesBits)]; - UInt32[] _distancesPrices = new UInt32[Base.kNumFullDistances << Base.kNumLenToPosStatesBits]; - UInt32[] _alignPrices = new UInt32[Base.kAlignTableSize]; - UInt32 _alignPriceCount; - - UInt32 _distTableSize = (kDefaultDictionaryLogSize * 2); - - int _posStateBits = 2; - UInt32 _posStateMask = (4 - 1); - int _numLiteralPosStateBits = 0; - int _numLiteralContextBits = 3; - - UInt32 _dictionarySize = (1 << kDefaultDictionaryLogSize); - UInt32 _dictionarySizePrev = 0xFFFFFFFF; - UInt32 _numFastBytesPrev = 0xFFFFFFFF; - - Int64 nowPos64; - bool _finished; - System.IO.Stream _inStream; - - EMatchFinderType _matchFinderType = EMatchFinderType.BT4; - bool _writeEndMark = false; - - bool _needReleaseMFStream; - - void Create() - { - if (_matchFinder == null) - { - LZ.BinTree bt = new LZ.BinTree(); - int numHashBytes = 4; - if (_matchFinderType == EMatchFinderType.BT2) - numHashBytes = 2; - bt.SetType(numHashBytes); - _matchFinder = bt; - } - _literalEncoder.Create(_numLiteralPosStateBits, _numLiteralContextBits); - - if (_dictionarySize == _dictionarySizePrev && _numFastBytesPrev == _numFastBytes) - return; - _matchFinder.Create(_dictionarySize, kNumOpts, _numFastBytes, Base.kMatchMaxLen + 1); - _dictionarySizePrev = _dictionarySize; - _numFastBytesPrev = _numFastBytes; - } - - public Encoder() - { - for (int i = 0; i < kNumOpts; i++) - _optimum[i] = new Optimal(); - for (int i = 0; i < Base.kNumLenToPosStates; i++) - _posSlotEncoder[i] = new RangeCoder.BitTreeEncoder(Base.kNumPosSlotBits); - } - - void SetWriteEndMarkerMode(bool writeEndMarker) - { - _writeEndMark = writeEndMarker; - } - - void Init() - { - BaseInit(); - _rangeEncoder.Init(); - - uint i; - for (i = 0; i < Base.kNumStates; i++) - { - for (uint j = 0; j <= _posStateMask; j++) - { - uint complexState = (i << Base.kNumPosStatesBitsMax) + j; - _isMatch[complexState].Init(); - _isRep0Long[complexState].Init(); - } - _isRep[i].Init(); - _isRepG0[i].Init(); - _isRepG1[i].Init(); - _isRepG2[i].Init(); - } - _literalEncoder.Init(); - for (i = 0; i < Base.kNumLenToPosStates; i++) - _posSlotEncoder[i].Init(); - for (i = 0; i < Base.kNumFullDistances - Base.kEndPosModelIndex; i++) - _posEncoders[i].Init(); - - _lenEncoder.Init((UInt32)1 << _posStateBits); - _repMatchLenEncoder.Init((UInt32)1 << _posStateBits); - - _posAlignEncoder.Init(); - - _longestMatchWasFound = false; - _optimumEndIndex = 0; - _optimumCurrentIndex = 0; - _additionalOffset = 0; - } - - void ReadMatchDistances(out UInt32 lenRes, out UInt32 numDistancePairs) - { - lenRes = 0; - numDistancePairs = _matchFinder.GetMatches(_matchDistances); - if (numDistancePairs > 0) - { - lenRes = _matchDistances[numDistancePairs - 2]; - if (lenRes == _numFastBytes) - lenRes += _matchFinder.GetMatchLen((int)lenRes - 1, _matchDistances[numDistancePairs - 1], - Base.kMatchMaxLen - lenRes); - } - _additionalOffset++; - } - - - void MovePos(UInt32 num) - { - if (num > 0) - { - _matchFinder.Skip(num); - _additionalOffset += num; - } - } - - UInt32 GetRepLen1Price(Base.State state, UInt32 posState) - { - return _isRepG0[state.Index].GetPrice0() + - _isRep0Long[(state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice0(); - } - - UInt32 GetPureRepPrice(UInt32 repIndex, Base.State state, UInt32 posState) - { - UInt32 price; - if (repIndex == 0) - { - price = _isRepG0[state.Index].GetPrice0(); - price += _isRep0Long[(state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice1(); - } - else - { - price = _isRepG0[state.Index].GetPrice1(); - if (repIndex == 1) - price += _isRepG1[state.Index].GetPrice0(); - else - { - price += _isRepG1[state.Index].GetPrice1(); - price += _isRepG2[state.Index].GetPrice(repIndex - 2); - } - } - return price; - } - - UInt32 GetRepPrice(UInt32 repIndex, UInt32 len, Base.State state, UInt32 posState) - { - UInt32 price = _repMatchLenEncoder.GetPrice(len - Base.kMatchMinLen, posState); - return price + GetPureRepPrice(repIndex, state, posState); - } - - UInt32 GetPosLenPrice(UInt32 pos, UInt32 len, UInt32 posState) - { - UInt32 price; - UInt32 lenToPosState = Base.GetLenToPosState(len); - if (pos < Base.kNumFullDistances) - price = _distancesPrices[(lenToPosState * Base.kNumFullDistances) + pos]; - else - price = _posSlotPrices[(lenToPosState << Base.kNumPosSlotBits) + GetPosSlot2(pos)] + - _alignPrices[pos & Base.kAlignMask]; - return price + _lenEncoder.GetPrice(len - Base.kMatchMinLen, posState); - } - - UInt32 Backward(out UInt32 backRes, UInt32 cur) - { - _optimumEndIndex = cur; - UInt32 posMem = _optimum[cur].PosPrev; - UInt32 backMem = _optimum[cur].BackPrev; - do - { - if (_optimum[cur].Prev1IsChar) - { - _optimum[posMem].MakeAsChar(); - _optimum[posMem].PosPrev = posMem - 1; - if (_optimum[cur].Prev2) - { - _optimum[posMem - 1].Prev1IsChar = false; - _optimum[posMem - 1].PosPrev = _optimum[cur].PosPrev2; - _optimum[posMem - 1].BackPrev = _optimum[cur].BackPrev2; - } - } - UInt32 posPrev = posMem; - UInt32 backCur = backMem; - - backMem = _optimum[posPrev].BackPrev; - posMem = _optimum[posPrev].PosPrev; - - _optimum[posPrev].BackPrev = backCur; - _optimum[posPrev].PosPrev = cur; - cur = posPrev; - } - while (cur > 0); - backRes = _optimum[0].BackPrev; - _optimumCurrentIndex = _optimum[0].PosPrev; - return _optimumCurrentIndex; - } - - UInt32[] reps = new UInt32[Base.kNumRepDistances]; - UInt32[] repLens = new UInt32[Base.kNumRepDistances]; - - - UInt32 GetOptimum(UInt32 position, out UInt32 backRes) - { - if (_optimumEndIndex != _optimumCurrentIndex) - { - UInt32 lenRes = _optimum[_optimumCurrentIndex].PosPrev - _optimumCurrentIndex; - backRes = _optimum[_optimumCurrentIndex].BackPrev; - _optimumCurrentIndex = _optimum[_optimumCurrentIndex].PosPrev; - return lenRes; - } - _optimumCurrentIndex = _optimumEndIndex = 0; - - UInt32 lenMain, numDistancePairs; - if (!_longestMatchWasFound) - { - ReadMatchDistances(out lenMain, out numDistancePairs); - } - else - { - lenMain = _longestMatchLength; - numDistancePairs = _numDistancePairs; - _longestMatchWasFound = false; - } - - UInt32 numAvailableBytes = _matchFinder.GetNumAvailableBytes() + 1; - if (numAvailableBytes < 2) - { - backRes = 0xFFFFFFFF; - return 1; - } - if (numAvailableBytes > Base.kMatchMaxLen) - numAvailableBytes = Base.kMatchMaxLen; - - UInt32 repMaxIndex = 0; - UInt32 i; - for (i = 0; i < Base.kNumRepDistances; i++) - { - reps[i] = _repDistances[i]; - repLens[i] = _matchFinder.GetMatchLen(0 - 1, reps[i], Base.kMatchMaxLen); - if (repLens[i] > repLens[repMaxIndex]) - repMaxIndex = i; - } - if (repLens[repMaxIndex] >= _numFastBytes) - { - backRes = repMaxIndex; - UInt32 lenRes = repLens[repMaxIndex]; - MovePos(lenRes - 1); - return lenRes; - } - - if (lenMain >= _numFastBytes) - { - backRes = _matchDistances[numDistancePairs - 1] + Base.kNumRepDistances; - MovePos(lenMain - 1); - return lenMain; - } - - Byte currentByte = _matchFinder.GetIndexByte(0 - 1); - Byte matchByte = _matchFinder.GetIndexByte((Int32)(0 - _repDistances[0] - 1 - 1)); - - if (lenMain < 2 && currentByte != matchByte && repLens[repMaxIndex] < 2) - { - backRes = (UInt32)0xFFFFFFFF; - return 1; - } - - _optimum[0].State = _state; - - UInt32 posState = (position & _posStateMask); - - _optimum[1].Price = _isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice0() + - _literalEncoder.GetSubCoder(position, _previousByte).GetPrice(!_state.IsCharState(), matchByte, currentByte); - _optimum[1].MakeAsChar(); - - UInt32 matchPrice = _isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice1(); - UInt32 repMatchPrice = matchPrice + _isRep[_state.Index].GetPrice1(); - - if (matchByte == currentByte) - { - UInt32 shortRepPrice = repMatchPrice + GetRepLen1Price(_state, posState); - if (shortRepPrice < _optimum[1].Price) - { - _optimum[1].Price = shortRepPrice; - _optimum[1].MakeAsShortRep(); - } - } - - UInt32 lenEnd = ((lenMain >= repLens[repMaxIndex]) ? lenMain : repLens[repMaxIndex]); - - if(lenEnd < 2) - { - backRes = _optimum[1].BackPrev; - return 1; - } - - _optimum[1].PosPrev = 0; - - _optimum[0].Backs0 = reps[0]; - _optimum[0].Backs1 = reps[1]; - _optimum[0].Backs2 = reps[2]; - _optimum[0].Backs3 = reps[3]; - - UInt32 len = lenEnd; - do - _optimum[len--].Price = kIfinityPrice; - while (len >= 2); - - for (i = 0; i < Base.kNumRepDistances; i++) - { - UInt32 repLen = repLens[i]; - if (repLen < 2) - continue; - UInt32 price = repMatchPrice + GetPureRepPrice(i, _state, posState); - do - { - UInt32 curAndLenPrice = price + _repMatchLenEncoder.GetPrice(repLen - 2, posState); - Optimal optimum = _optimum[repLen]; - if (curAndLenPrice < optimum.Price) - { - optimum.Price = curAndLenPrice; - optimum.PosPrev = 0; - optimum.BackPrev = i; - optimum.Prev1IsChar = false; - } - } - while (--repLen >= 2); - } - - UInt32 normalMatchPrice = matchPrice + _isRep[_state.Index].GetPrice0(); - - len = ((repLens[0] >= 2) ? repLens[0] + 1 : 2); - if (len <= lenMain) - { - UInt32 offs = 0; - while (len > _matchDistances[offs]) - offs += 2; - for (; ; len++) - { - UInt32 distance = _matchDistances[offs + 1]; - UInt32 curAndLenPrice = normalMatchPrice + GetPosLenPrice(distance, len, posState); - Optimal optimum = _optimum[len]; - if (curAndLenPrice < optimum.Price) - { - optimum.Price = curAndLenPrice; - optimum.PosPrev = 0; - optimum.BackPrev = distance + Base.kNumRepDistances; - optimum.Prev1IsChar = false; - } - if (len == _matchDistances[offs]) - { - offs += 2; - if (offs == numDistancePairs) - break; - } - } - } - - UInt32 cur = 0; - - while (true) - { - cur++; - if (cur == lenEnd) - return Backward(out backRes, cur); - UInt32 newLen; - ReadMatchDistances(out newLen, out numDistancePairs); - if (newLen >= _numFastBytes) - { - _numDistancePairs = numDistancePairs; - _longestMatchLength = newLen; - _longestMatchWasFound = true; - return Backward(out backRes, cur); - } - position++; - UInt32 posPrev = _optimum[cur].PosPrev; - Base.State state; - if (_optimum[cur].Prev1IsChar) - { - posPrev--; - if (_optimum[cur].Prev2) - { - state = _optimum[_optimum[cur].PosPrev2].State; - if (_optimum[cur].BackPrev2 < Base.kNumRepDistances) - state.UpdateRep(); - else - state.UpdateMatch(); - } - else - state = _optimum[posPrev].State; - state.UpdateChar(); - } - else - state = _optimum[posPrev].State; - if (posPrev == cur - 1) - { - if (_optimum[cur].IsShortRep()) - state.UpdateShortRep(); - else - state.UpdateChar(); - } - else - { - UInt32 pos; - if (_optimum[cur].Prev1IsChar && _optimum[cur].Prev2) - { - posPrev = _optimum[cur].PosPrev2; - pos = _optimum[cur].BackPrev2; - state.UpdateRep(); - } - else - { - pos = _optimum[cur].BackPrev; - if (pos < Base.kNumRepDistances) - state.UpdateRep(); - else - state.UpdateMatch(); - } - Optimal opt = _optimum[posPrev]; - if (pos < Base.kNumRepDistances) - { - if (pos == 0) - { - reps[0] = opt.Backs0; - reps[1] = opt.Backs1; - reps[2] = opt.Backs2; - reps[3] = opt.Backs3; - } - else if (pos == 1) - { - reps[0] = opt.Backs1; - reps[1] = opt.Backs0; - reps[2] = opt.Backs2; - reps[3] = opt.Backs3; - } - else if (pos == 2) - { - reps[0] = opt.Backs2; - reps[1] = opt.Backs0; - reps[2] = opt.Backs1; - reps[3] = opt.Backs3; - } - else - { - reps[0] = opt.Backs3; - reps[1] = opt.Backs0; - reps[2] = opt.Backs1; - reps[3] = opt.Backs2; - } - } - else - { - reps[0] = (pos - Base.kNumRepDistances); - reps[1] = opt.Backs0; - reps[2] = opt.Backs1; - reps[3] = opt.Backs2; - } - } - _optimum[cur].State = state; - _optimum[cur].Backs0 = reps[0]; - _optimum[cur].Backs1 = reps[1]; - _optimum[cur].Backs2 = reps[2]; - _optimum[cur].Backs3 = reps[3]; - UInt32 curPrice = _optimum[cur].Price; - - currentByte = _matchFinder.GetIndexByte(0 - 1); - matchByte = _matchFinder.GetIndexByte((Int32)(0 - reps[0] - 1 - 1)); - - posState = (position & _posStateMask); - - UInt32 curAnd1Price = curPrice + - _isMatch[(state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice0() + - _literalEncoder.GetSubCoder(position, _matchFinder.GetIndexByte(0 - 2)). - GetPrice(!state.IsCharState(), matchByte, currentByte); - - Optimal nextOptimum = _optimum[cur + 1]; - - bool nextIsChar = false; - if (curAnd1Price < nextOptimum.Price) - { - nextOptimum.Price = curAnd1Price; - nextOptimum.PosPrev = cur; - nextOptimum.MakeAsChar(); - nextIsChar = true; - } - - matchPrice = curPrice + _isMatch[(state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice1(); - repMatchPrice = matchPrice + _isRep[state.Index].GetPrice1(); - - if (matchByte == currentByte && - !(nextOptimum.PosPrev < cur && nextOptimum.BackPrev == 0)) - { - UInt32 shortRepPrice = repMatchPrice + GetRepLen1Price(state, posState); - if (shortRepPrice <= nextOptimum.Price) - { - nextOptimum.Price = shortRepPrice; - nextOptimum.PosPrev = cur; - nextOptimum.MakeAsShortRep(); - nextIsChar = true; - } - } - - UInt32 numAvailableBytesFull = _matchFinder.GetNumAvailableBytes() + 1; - numAvailableBytesFull = Math.Min(kNumOpts - 1 - cur, numAvailableBytesFull); - numAvailableBytes = numAvailableBytesFull; - - if (numAvailableBytes < 2) - continue; - if (numAvailableBytes > _numFastBytes) - numAvailableBytes = _numFastBytes; - if (!nextIsChar && matchByte != currentByte) - { - // try Literal + rep0 - UInt32 t = Math.Min(numAvailableBytesFull - 1, _numFastBytes); - UInt32 lenTest2 = _matchFinder.GetMatchLen(0, reps[0], t); - if (lenTest2 >= 2) - { - Base.State state2 = state; - state2.UpdateChar(); - UInt32 posStateNext = (position + 1) & _posStateMask; - UInt32 nextRepMatchPrice = curAnd1Price + - _isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice1() + - _isRep[state2.Index].GetPrice1(); - { - UInt32 offset = cur + 1 + lenTest2; - while (lenEnd < offset) - _optimum[++lenEnd].Price = kIfinityPrice; - UInt32 curAndLenPrice = nextRepMatchPrice + GetRepPrice( - 0, lenTest2, state2, posStateNext); - Optimal optimum = _optimum[offset]; - if (curAndLenPrice < optimum.Price) - { - optimum.Price = curAndLenPrice; - optimum.PosPrev = cur + 1; - optimum.BackPrev = 0; - optimum.Prev1IsChar = true; - optimum.Prev2 = false; - } - } - } - } - - UInt32 startLen = 2; // speed optimization - - for (UInt32 repIndex = 0; repIndex < Base.kNumRepDistances; repIndex++) - { - UInt32 lenTest = _matchFinder.GetMatchLen(0 - 1, reps[repIndex], numAvailableBytes); - if (lenTest < 2) - continue; - UInt32 lenTestTemp = lenTest; - do - { - while (lenEnd < cur + lenTest) - _optimum[++lenEnd].Price = kIfinityPrice; - UInt32 curAndLenPrice = repMatchPrice + GetRepPrice(repIndex, lenTest, state, posState); - Optimal optimum = _optimum[cur + lenTest]; - if (curAndLenPrice < optimum.Price) - { - optimum.Price = curAndLenPrice; - optimum.PosPrev = cur; - optimum.BackPrev = repIndex; - optimum.Prev1IsChar = false; - } - } - while(--lenTest >= 2); - lenTest = lenTestTemp; - - if (repIndex == 0) - startLen = lenTest + 1; - - // if (_maxMode) - if (lenTest < numAvailableBytesFull) - { - UInt32 t = Math.Min(numAvailableBytesFull - 1 - lenTest, _numFastBytes); - UInt32 lenTest2 = _matchFinder.GetMatchLen((Int32)lenTest, reps[repIndex], t); - if (lenTest2 >= 2) - { - Base.State state2 = state; - state2.UpdateRep(); - UInt32 posStateNext = (position + lenTest) & _posStateMask; - UInt32 curAndLenCharPrice = - repMatchPrice + GetRepPrice(repIndex, lenTest, state, posState) + - _isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice0() + - _literalEncoder.GetSubCoder(position + lenTest, - _matchFinder.GetIndexByte((Int32)lenTest - 1 - 1)).GetPrice(true, - _matchFinder.GetIndexByte((Int32)((Int32)lenTest - 1 - (Int32)(reps[repIndex] + 1))), - _matchFinder.GetIndexByte((Int32)lenTest - 1)); - state2.UpdateChar(); - posStateNext = (position + lenTest + 1) & _posStateMask; - UInt32 nextMatchPrice = curAndLenCharPrice + _isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice1(); - UInt32 nextRepMatchPrice = nextMatchPrice + _isRep[state2.Index].GetPrice1(); - - // for(; lenTest2 >= 2; lenTest2--) - { - UInt32 offset = lenTest + 1 + lenTest2; - while(lenEnd < cur + offset) - _optimum[++lenEnd].Price = kIfinityPrice; - UInt32 curAndLenPrice = nextRepMatchPrice + GetRepPrice(0, lenTest2, state2, posStateNext); - Optimal optimum = _optimum[cur + offset]; - if (curAndLenPrice < optimum.Price) - { - optimum.Price = curAndLenPrice; - optimum.PosPrev = cur + lenTest + 1; - optimum.BackPrev = 0; - optimum.Prev1IsChar = true; - optimum.Prev2 = true; - optimum.PosPrev2 = cur; - optimum.BackPrev2 = repIndex; - } - } - } - } - } - - if (newLen > numAvailableBytes) - { - newLen = numAvailableBytes; - for (numDistancePairs = 0; newLen > _matchDistances[numDistancePairs]; numDistancePairs += 2) ; - _matchDistances[numDistancePairs] = newLen; - numDistancePairs += 2; - } - if (newLen >= startLen) - { - normalMatchPrice = matchPrice + _isRep[state.Index].GetPrice0(); - while (lenEnd < cur + newLen) - _optimum[++lenEnd].Price = kIfinityPrice; - - UInt32 offs = 0; - while (startLen > _matchDistances[offs]) - offs += 2; - - for (UInt32 lenTest = startLen; ; lenTest++) - { - UInt32 curBack = _matchDistances[offs + 1]; - UInt32 curAndLenPrice = normalMatchPrice + GetPosLenPrice(curBack, lenTest, posState); - Optimal optimum = _optimum[cur + lenTest]; - if (curAndLenPrice < optimum.Price) - { - optimum.Price = curAndLenPrice; - optimum.PosPrev = cur; - optimum.BackPrev = curBack + Base.kNumRepDistances; - optimum.Prev1IsChar = false; - } - - if (lenTest == _matchDistances[offs]) - { - if (lenTest < numAvailableBytesFull) - { - UInt32 t = Math.Min(numAvailableBytesFull - 1 - lenTest, _numFastBytes); - UInt32 lenTest2 = _matchFinder.GetMatchLen((Int32)lenTest, curBack, t); - if (lenTest2 >= 2) - { - Base.State state2 = state; - state2.UpdateMatch(); - UInt32 posStateNext = (position + lenTest) & _posStateMask; - UInt32 curAndLenCharPrice = curAndLenPrice + - _isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice0() + - _literalEncoder.GetSubCoder(position + lenTest, - _matchFinder.GetIndexByte((Int32)lenTest - 1 - 1)). - GetPrice(true, - _matchFinder.GetIndexByte((Int32)lenTest - (Int32)(curBack + 1) - 1), - _matchFinder.GetIndexByte((Int32)lenTest - 1)); - state2.UpdateChar(); - posStateNext = (position + lenTest + 1) & _posStateMask; - UInt32 nextMatchPrice = curAndLenCharPrice + _isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice1(); - UInt32 nextRepMatchPrice = nextMatchPrice + _isRep[state2.Index].GetPrice1(); - - UInt32 offset = lenTest + 1 + lenTest2; - while (lenEnd < cur + offset) - _optimum[++lenEnd].Price = kIfinityPrice; - curAndLenPrice = nextRepMatchPrice + GetRepPrice(0, lenTest2, state2, posStateNext); - optimum = _optimum[cur + offset]; - if (curAndLenPrice < optimum.Price) - { - optimum.Price = curAndLenPrice; - optimum.PosPrev = cur + lenTest + 1; - optimum.BackPrev = 0; - optimum.Prev1IsChar = true; - optimum.Prev2 = true; - optimum.PosPrev2 = cur; - optimum.BackPrev2 = curBack + Base.kNumRepDistances; - } - } - } - offs += 2; - if (offs == numDistancePairs) - break; - } - } - } - } - } - - bool ChangePair(UInt32 smallDist, UInt32 bigDist) - { - const int kDif = 7; - return (smallDist < ((UInt32)(1) << (32 - kDif)) && bigDist >= (smallDist << kDif)); - } - - void WriteEndMarker(UInt32 posState) - { - if (!_writeEndMark) - return; - - _isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].Encode(_rangeEncoder, 1); - _isRep[_state.Index].Encode(_rangeEncoder, 0); - _state.UpdateMatch(); - UInt32 len = Base.kMatchMinLen; - _lenEncoder.Encode(_rangeEncoder, len - Base.kMatchMinLen, posState); - UInt32 posSlot = (1 << Base.kNumPosSlotBits) - 1; - UInt32 lenToPosState = Base.GetLenToPosState(len); - _posSlotEncoder[lenToPosState].Encode(_rangeEncoder, posSlot); - int footerBits = 30; - UInt32 posReduced = (((UInt32)1) << footerBits) - 1; - _rangeEncoder.EncodeDirectBits(posReduced >> Base.kNumAlignBits, footerBits - Base.kNumAlignBits); - _posAlignEncoder.ReverseEncode(_rangeEncoder, posReduced & Base.kAlignMask); - } - - void Flush(UInt32 nowPos) - { - ReleaseMFStream(); - WriteEndMarker(nowPos & _posStateMask); - _rangeEncoder.FlushData(); - _rangeEncoder.FlushStream(); - } - - public void CodeOneBlock(out Int64 inSize, out Int64 outSize, out bool finished) - { - inSize = 0; - outSize = 0; - finished = true; - - if (_inStream != null) - { - _matchFinder.SetStream(_inStream); - _matchFinder.Init(); - _needReleaseMFStream = true; - _inStream = null; - if (_trainSize > 0) - _matchFinder.Skip(_trainSize); - } - - if (_finished) - return; - _finished = true; - - - Int64 progressPosValuePrev = nowPos64; - if (nowPos64 == 0) - { - if (_matchFinder.GetNumAvailableBytes() == 0) - { - Flush((UInt32)nowPos64); - return; - } - UInt32 len, numDistancePairs; // it's not used - ReadMatchDistances(out len, out numDistancePairs); - UInt32 posState = (UInt32)(nowPos64) & _posStateMask; - _isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].Encode(_rangeEncoder, 0); - _state.UpdateChar(); - Byte curByte = _matchFinder.GetIndexByte((Int32)(0 - _additionalOffset)); - _literalEncoder.GetSubCoder((UInt32)(nowPos64), _previousByte).Encode(_rangeEncoder, curByte); - _previousByte = curByte; - _additionalOffset--; - nowPos64++; - } - if (_matchFinder.GetNumAvailableBytes() == 0) - { - Flush((UInt32)nowPos64); - return; - } - while (true) - { - UInt32 pos; - UInt32 len = GetOptimum((UInt32)nowPos64, out pos); - - UInt32 posState = ((UInt32)nowPos64) & _posStateMask; - UInt32 complexState = (_state.Index << Base.kNumPosStatesBitsMax) + posState; - if (len == 1 && pos == 0xFFFFFFFF) - { - _isMatch[complexState].Encode(_rangeEncoder, 0); - Byte curByte = _matchFinder.GetIndexByte((Int32)(0 - _additionalOffset)); - LiteralEncoder.Encoder2 subCoder = _literalEncoder.GetSubCoder((UInt32)nowPos64, _previousByte); - if (!_state.IsCharState()) - { - Byte matchByte = _matchFinder.GetIndexByte((Int32)(0 - _repDistances[0] - 1 - _additionalOffset)); - subCoder.EncodeMatched(_rangeEncoder, matchByte, curByte); - } - else - subCoder.Encode(_rangeEncoder, curByte); - _previousByte = curByte; - _state.UpdateChar(); - } - else - { - _isMatch[complexState].Encode(_rangeEncoder, 1); - if (pos < Base.kNumRepDistances) - { - _isRep[_state.Index].Encode(_rangeEncoder, 1); - if (pos == 0) - { - _isRepG0[_state.Index].Encode(_rangeEncoder, 0); - if (len == 1) - _isRep0Long[complexState].Encode(_rangeEncoder, 0); - else - _isRep0Long[complexState].Encode(_rangeEncoder, 1); - } - else - { - _isRepG0[_state.Index].Encode(_rangeEncoder, 1); - if (pos == 1) - _isRepG1[_state.Index].Encode(_rangeEncoder, 0); - else - { - _isRepG1[_state.Index].Encode(_rangeEncoder, 1); - _isRepG2[_state.Index].Encode(_rangeEncoder, pos - 2); - } - } - if (len == 1) - _state.UpdateShortRep(); - else - { - _repMatchLenEncoder.Encode(_rangeEncoder, len - Base.kMatchMinLen, posState); - _state.UpdateRep(); - } - UInt32 distance = _repDistances[pos]; - if (pos != 0) - { - for (UInt32 i = pos; i >= 1; i--) - _repDistances[i] = _repDistances[i - 1]; - _repDistances[0] = distance; - } - } - else - { - _isRep[_state.Index].Encode(_rangeEncoder, 0); - _state.UpdateMatch(); - _lenEncoder.Encode(_rangeEncoder, len - Base.kMatchMinLen, posState); - pos -= Base.kNumRepDistances; - UInt32 posSlot = GetPosSlot(pos); - UInt32 lenToPosState = Base.GetLenToPosState(len); - _posSlotEncoder[lenToPosState].Encode(_rangeEncoder, posSlot); - - if (posSlot >= Base.kStartPosModelIndex) - { - int footerBits = (int)((posSlot >> 1) - 1); - UInt32 baseVal = ((2 | (posSlot & 1)) << footerBits); - UInt32 posReduced = pos - baseVal; - - if (posSlot < Base.kEndPosModelIndex) - RangeCoder.BitTreeEncoder.ReverseEncode(_posEncoders, - baseVal - posSlot - 1, _rangeEncoder, footerBits, posReduced); - else - { - _rangeEncoder.EncodeDirectBits(posReduced >> Base.kNumAlignBits, footerBits - Base.kNumAlignBits); - _posAlignEncoder.ReverseEncode(_rangeEncoder, posReduced & Base.kAlignMask); - _alignPriceCount++; - } - } - UInt32 distance = pos; - for (UInt32 i = Base.kNumRepDistances - 1; i >= 1; i--) - _repDistances[i] = _repDistances[i - 1]; - _repDistances[0] = distance; - _matchPriceCount++; - } - _previousByte = _matchFinder.GetIndexByte((Int32)(len - 1 - _additionalOffset)); - } - _additionalOffset -= len; - nowPos64 += len; - if (_additionalOffset == 0) - { - // if (!_fastMode) - if (_matchPriceCount >= (1 << 7)) - FillDistancesPrices(); - if (_alignPriceCount >= Base.kAlignTableSize) - FillAlignPrices(); - inSize = nowPos64; - outSize = _rangeEncoder.GetProcessedSizeAdd(); - if (_matchFinder.GetNumAvailableBytes() == 0) - { - Flush((UInt32)nowPos64); - return; - } - - if (nowPos64 - progressPosValuePrev >= (1 << 12)) - { - _finished = false; - finished = false; - return; - } - } - } - } - - void ReleaseMFStream() - { - if (_matchFinder != null && _needReleaseMFStream) - { - _matchFinder.ReleaseStream(); - _needReleaseMFStream = false; - } - } - - void SetOutStream(System.IO.Stream outStream) { _rangeEncoder.SetStream(outStream); } - void ReleaseOutStream() { _rangeEncoder.ReleaseStream(); } - - void ReleaseStreams() - { - ReleaseMFStream(); - ReleaseOutStream(); - } - - void SetStreams(System.IO.Stream inStream, System.IO.Stream outStream, - Int64 inSize, Int64 outSize) - { - _inStream = inStream; - _finished = false; - Create(); - SetOutStream(outStream); - Init(); - - // if (!_fastMode) - { - FillDistancesPrices(); - FillAlignPrices(); - } - - _lenEncoder.SetTableSize(_numFastBytes + 1 - Base.kMatchMinLen); - _lenEncoder.UpdateTables((UInt32)1 << _posStateBits); - _repMatchLenEncoder.SetTableSize(_numFastBytes + 1 - Base.kMatchMinLen); - _repMatchLenEncoder.UpdateTables((UInt32)1 << _posStateBits); - - nowPos64 = 0; - } - - - public void Code(System.IO.Stream inStream, System.IO.Stream outStream, - Int64 inSize, Int64 outSize, ICodeProgress progress) - { - _needReleaseMFStream = false; - try - { - SetStreams(inStream, outStream, inSize, outSize); - while (true) - { - Int64 processedInSize; - Int64 processedOutSize; - bool finished; - CodeOneBlock(out processedInSize, out processedOutSize, out finished); - if (finished) - return; - if (progress != null) - { - progress.SetProgress(processedInSize, processedOutSize); - } - } - } - finally - { - ReleaseStreams(); - } - } - - const int kPropSize = 5; - Byte[] properties = new Byte[kPropSize]; - - public void WriteCoderProperties(System.IO.Stream outStream) - { - properties[0] = (Byte)((_posStateBits * 5 + _numLiteralPosStateBits) * 9 + _numLiteralContextBits); - for (int i = 0; i < 4; i++) - properties[1 + i] = (Byte)((_dictionarySize >> (8 * i)) & 0xFF); - outStream.Write(properties, 0, kPropSize); - } - - UInt32[] tempPrices = new UInt32[Base.kNumFullDistances]; - UInt32 _matchPriceCount; - - void FillDistancesPrices() - { - for (UInt32 i = Base.kStartPosModelIndex; i < Base.kNumFullDistances; i++) - { - UInt32 posSlot = GetPosSlot(i); - int footerBits = (int)((posSlot >> 1) - 1); - UInt32 baseVal = ((2 | (posSlot & 1)) << footerBits); - tempPrices[i] = BitTreeEncoder.ReverseGetPrice(_posEncoders, - baseVal - posSlot - 1, footerBits, i - baseVal); - } - - for (UInt32 lenToPosState = 0; lenToPosState < Base.kNumLenToPosStates; lenToPosState++) - { - UInt32 posSlot; - RangeCoder.BitTreeEncoder encoder = _posSlotEncoder[lenToPosState]; - - UInt32 st = (lenToPosState << Base.kNumPosSlotBits); - for (posSlot = 0; posSlot < _distTableSize; posSlot++) - _posSlotPrices[st + posSlot] = encoder.GetPrice(posSlot); - for (posSlot = Base.kEndPosModelIndex; posSlot < _distTableSize; posSlot++) - _posSlotPrices[st + posSlot] += ((((posSlot >> 1) - 1) - Base.kNumAlignBits) << RangeCoder.BitEncoder.kNumBitPriceShiftBits); - - UInt32 st2 = lenToPosState * Base.kNumFullDistances; - UInt32 i; - for (i = 0; i < Base.kStartPosModelIndex; i++) - _distancesPrices[st2 + i] = _posSlotPrices[st + i]; - for (; i < Base.kNumFullDistances; i++) - _distancesPrices[st2 + i] = _posSlotPrices[st + GetPosSlot(i)] + tempPrices[i]; - } - _matchPriceCount = 0; - } - - void FillAlignPrices() - { - for (UInt32 i = 0; i < Base.kAlignTableSize; i++) - _alignPrices[i] = _posAlignEncoder.ReverseGetPrice(i); - _alignPriceCount = 0; - } - - - static string[] kMatchFinderIDs = - { - "BT2", - "BT4", - }; - - static int FindMatchFinder(string s) - { - for (int m = 0; m < kMatchFinderIDs.Length; m++) - if (s == kMatchFinderIDs[m]) - return m; - return -1; - } - - public void SetCoderProperties(CoderPropID[] propIDs, object[] properties) - { - for (UInt32 i = 0; i < properties.Length; i++) - { - object prop = properties[i]; - switch (propIDs[i]) - { - case CoderPropID.NumFastBytes: - { - if (!(prop is Int32)) - throw new InvalidParamException(); - Int32 numFastBytes = (Int32)prop; - if (numFastBytes < 5 || numFastBytes > Base.kMatchMaxLen) - throw new InvalidParamException(); - _numFastBytes = (UInt32)numFastBytes; - break; - } - case CoderPropID.Algorithm: - { - /* - if (!(prop is Int32)) - throw new InvalidParamException(); - Int32 maximize = (Int32)prop; - _fastMode = (maximize == 0); - _maxMode = (maximize >= 2); - */ - break; - } - case CoderPropID.MatchFinder: - { - if (!(prop is String)) - throw new InvalidParamException(); - EMatchFinderType matchFinderIndexPrev = _matchFinderType; - int m = FindMatchFinder(((string)prop).ToUpper()); - if (m < 0) - throw new InvalidParamException(); - _matchFinderType = (EMatchFinderType)m; - if (_matchFinder != null && matchFinderIndexPrev != _matchFinderType) - { - _dictionarySizePrev = 0xFFFFFFFF; - _matchFinder = null; - } - break; - } - case CoderPropID.DictionarySize: - { - const int kDicLogSizeMaxCompress = 30; - if (!(prop is Int32)) - throw new InvalidParamException(); ; - Int32 dictionarySize = (Int32)prop; - if (dictionarySize < (UInt32)(1 << Base.kDicLogSizeMin) || - dictionarySize > (UInt32)(1 << kDicLogSizeMaxCompress)) - throw new InvalidParamException(); - _dictionarySize = (UInt32)dictionarySize; - int dicLogSize; - for (dicLogSize = 0; dicLogSize < (UInt32)kDicLogSizeMaxCompress; dicLogSize++) - if (dictionarySize <= ((UInt32)(1) << dicLogSize)) - break; - _distTableSize = (UInt32)dicLogSize * 2; - break; - } - case CoderPropID.PosStateBits: - { - if (!(prop is Int32)) - throw new InvalidParamException(); - Int32 v = (Int32)prop; - if (v < 0 || v > (UInt32)Base.kNumPosStatesBitsEncodingMax) - throw new InvalidParamException(); - _posStateBits = (int)v; - _posStateMask = (((UInt32)1) << (int)_posStateBits) - 1; - break; - } - case CoderPropID.LitPosBits: - { - if (!(prop is Int32)) - throw new InvalidParamException(); - Int32 v = (Int32)prop; - if (v < 0 || v > (UInt32)Base.kNumLitPosStatesBitsEncodingMax) - throw new InvalidParamException(); - _numLiteralPosStateBits = (int)v; - break; - } - case CoderPropID.LitContextBits: - { - if (!(prop is Int32)) - throw new InvalidParamException(); - Int32 v = (Int32)prop; - if (v < 0 || v > (UInt32)Base.kNumLitContextBitsMax) - throw new InvalidParamException(); ; - _numLiteralContextBits = (int)v; - break; - } - case CoderPropID.EndMarker: - { - if (!(prop is Boolean)) - throw new InvalidParamException(); - SetWriteEndMarkerMode((Boolean)prop); - break; - } - default: - throw new InvalidParamException(); - } - } - } - - uint _trainSize = 0; - public void SetTrainSize(uint trainSize) - { - _trainSize = trainSize; - } - - } -} diff --git a/Editor/3rds/7zip/Compress/LZMA/LzmaEncoder.cs.meta b/Editor/3rds/7zip/Compress/LZMA/LzmaEncoder.cs.meta deleted file mode 100644 index fedcb56..0000000 --- a/Editor/3rds/7zip/Compress/LZMA/LzmaEncoder.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 37dcefc9d952dc34f9fba085a160a968 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/3rds/7zip/Compress/RangeCoder.meta b/Editor/3rds/7zip/Compress/RangeCoder.meta deleted file mode 100644 index cf24bb3..0000000 --- a/Editor/3rds/7zip/Compress/RangeCoder.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 73c80167cede90a4a8fc4938bab053c8 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/3rds/7zip/Compress/RangeCoder/RangeCoder.cs b/Editor/3rds/7zip/Compress/RangeCoder/RangeCoder.cs deleted file mode 100644 index 949c6bb..0000000 --- a/Editor/3rds/7zip/Compress/RangeCoder/RangeCoder.cs +++ /dev/null @@ -1,234 +0,0 @@ -using System; - -namespace SevenZip.Compression.RangeCoder -{ - class Encoder - { - public const uint kTopValue = (1 << 24); - - System.IO.Stream Stream; - - public UInt64 Low; - public uint Range; - uint _cacheSize; - byte _cache; - - long StartPosition; - - public void SetStream(System.IO.Stream stream) - { - Stream = stream; - } - - public void ReleaseStream() - { - Stream = null; - } - - public void Init() - { - StartPosition = Stream.Position; - - Low = 0; - Range = 0xFFFFFFFF; - _cacheSize = 1; - _cache = 0; - } - - public void FlushData() - { - for (int i = 0; i < 5; i++) - ShiftLow(); - } - - public void FlushStream() - { - Stream.Flush(); - } - - public void CloseStream() - { - Stream.Close(); - } - - public void Encode(uint start, uint size, uint total) - { - Low += start * (Range /= total); - Range *= size; - while (Range < kTopValue) - { - Range <<= 8; - ShiftLow(); - } - } - - public void ShiftLow() - { - if ((uint)Low < (uint)0xFF000000 || (uint)(Low >> 32) == 1) - { - byte temp = _cache; - do - { - Stream.WriteByte((byte)(temp + (Low >> 32))); - temp = 0xFF; - } - while (--_cacheSize != 0); - _cache = (byte)(((uint)Low) >> 24); - } - _cacheSize++; - Low = ((uint)Low) << 8; - } - - public void EncodeDirectBits(uint v, int numTotalBits) - { - for (int i = numTotalBits - 1; i >= 0; i--) - { - Range >>= 1; - if (((v >> i) & 1) == 1) - Low += Range; - if (Range < kTopValue) - { - Range <<= 8; - ShiftLow(); - } - } - } - - public void EncodeBit(uint size0, int numTotalBits, uint symbol) - { - uint newBound = (Range >> numTotalBits) * size0; - if (symbol == 0) - Range = newBound; - else - { - Low += newBound; - Range -= newBound; - } - while (Range < kTopValue) - { - Range <<= 8; - ShiftLow(); - } - } - - public long GetProcessedSizeAdd() - { - return _cacheSize + - Stream.Position - StartPosition + 4; - // (long)Stream.GetProcessedSize(); - } - } - - class Decoder - { - public const uint kTopValue = (1 << 24); - public uint Range; - public uint Code; - // public Buffer.InBuffer Stream = new Buffer.InBuffer(1 << 16); - public System.IO.Stream Stream; - - public void Init(System.IO.Stream stream) - { - // Stream.Init(stream); - Stream = stream; - - Code = 0; - Range = 0xFFFFFFFF; - for (int i = 0; i < 5; i++) - Code = (Code << 8) | (byte)Stream.ReadByte(); - } - - public void ReleaseStream() - { - // Stream.ReleaseStream(); - Stream = null; - } - - public void CloseStream() - { - Stream.Close(); - } - - public void Normalize() - { - while (Range < kTopValue) - { - Code = (Code << 8) | (byte)Stream.ReadByte(); - Range <<= 8; - } - } - - public void Normalize2() - { - if (Range < kTopValue) - { - Code = (Code << 8) | (byte)Stream.ReadByte(); - Range <<= 8; - } - } - - public uint GetThreshold(uint total) - { - return Code / (Range /= total); - } - - public void Decode(uint start, uint size, uint total) - { - Code -= start * Range; - Range *= size; - Normalize(); - } - - public uint DecodeDirectBits(int numTotalBits) - { - uint range = Range; - uint code = Code; - uint result = 0; - for (int i = numTotalBits; i > 0; i--) - { - range >>= 1; - /* - result <<= 1; - if (code >= range) - { - code -= range; - result |= 1; - } - */ - uint t = (code - range) >> 31; - code -= range & (t - 1); - result = (result << 1) | (1 - t); - - if (range < kTopValue) - { - code = (code << 8) | (byte)Stream.ReadByte(); - range <<= 8; - } - } - Range = range; - Code = code; - return result; - } - - public uint DecodeBit(uint size0, int numTotalBits) - { - uint newBound = (Range >> numTotalBits) * size0; - uint symbol; - if (Code < newBound) - { - symbol = 0; - Range = newBound; - } - else - { - symbol = 1; - Code -= newBound; - Range -= newBound; - } - Normalize(); - return symbol; - } - - // ulong GetProcessedSize() {return Stream.GetProcessedSize(); } - } -} diff --git a/Editor/3rds/7zip/Compress/RangeCoder/RangeCoder.cs.meta b/Editor/3rds/7zip/Compress/RangeCoder/RangeCoder.cs.meta deleted file mode 100644 index fdbc75b..0000000 --- a/Editor/3rds/7zip/Compress/RangeCoder/RangeCoder.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: a855cbfe314340a43b3d71672dcbb058 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/3rds/7zip/Compress/RangeCoder/RangeCoderBit.cs b/Editor/3rds/7zip/Compress/RangeCoder/RangeCoderBit.cs deleted file mode 100644 index 4f0346d..0000000 --- a/Editor/3rds/7zip/Compress/RangeCoder/RangeCoderBit.cs +++ /dev/null @@ -1,117 +0,0 @@ -using System; - -namespace SevenZip.Compression.RangeCoder -{ - struct BitEncoder - { - public const int kNumBitModelTotalBits = 11; - public const uint kBitModelTotal = (1 << kNumBitModelTotalBits); - const int kNumMoveBits = 5; - const int kNumMoveReducingBits = 2; - public const int kNumBitPriceShiftBits = 6; - - uint Prob; - - public void Init() { Prob = kBitModelTotal >> 1; } - - public void UpdateModel(uint symbol) - { - if (symbol == 0) - Prob += (kBitModelTotal - Prob) >> kNumMoveBits; - else - Prob -= (Prob) >> kNumMoveBits; - } - - public void Encode(Encoder encoder, uint symbol) - { - // encoder.EncodeBit(Prob, kNumBitModelTotalBits, symbol); - // UpdateModel(symbol); - uint newBound = (encoder.Range >> kNumBitModelTotalBits) * Prob; - if (symbol == 0) - { - encoder.Range = newBound; - Prob += (kBitModelTotal - Prob) >> kNumMoveBits; - } - else - { - encoder.Low += newBound; - encoder.Range -= newBound; - Prob -= (Prob) >> kNumMoveBits; - } - if (encoder.Range < Encoder.kTopValue) - { - encoder.Range <<= 8; - encoder.ShiftLow(); - } - } - - private static UInt32[] ProbPrices = new UInt32[kBitModelTotal >> kNumMoveReducingBits]; - - static BitEncoder() - { - const int kNumBits = (kNumBitModelTotalBits - kNumMoveReducingBits); - for (int i = kNumBits - 1; i >= 0; i--) - { - UInt32 start = (UInt32)1 << (kNumBits - i - 1); - UInt32 end = (UInt32)1 << (kNumBits - i); - for (UInt32 j = start; j < end; j++) - ProbPrices[j] = ((UInt32)i << kNumBitPriceShiftBits) + - (((end - j) << kNumBitPriceShiftBits) >> (kNumBits - i - 1)); - } - } - - public uint GetPrice(uint symbol) - { - return ProbPrices[(((Prob - symbol) ^ ((-(int)symbol))) & (kBitModelTotal - 1)) >> kNumMoveReducingBits]; - } - public uint GetPrice0() { return ProbPrices[Prob >> kNumMoveReducingBits]; } - public uint GetPrice1() { return ProbPrices[(kBitModelTotal - Prob) >> kNumMoveReducingBits]; } - } - - struct BitDecoder - { - public const int kNumBitModelTotalBits = 11; - public const uint kBitModelTotal = (1 << kNumBitModelTotalBits); - const int kNumMoveBits = 5; - - uint Prob; - - public void UpdateModel(int numMoveBits, uint symbol) - { - if (symbol == 0) - Prob += (kBitModelTotal - Prob) >> numMoveBits; - else - Prob -= (Prob) >> numMoveBits; - } - - public void Init() { Prob = kBitModelTotal >> 1; } - - public uint Decode(RangeCoder.Decoder rangeDecoder) - { - uint newBound = (uint)(rangeDecoder.Range >> kNumBitModelTotalBits) * (uint)Prob; - if (rangeDecoder.Code < newBound) - { - rangeDecoder.Range = newBound; - Prob += (kBitModelTotal - Prob) >> kNumMoveBits; - if (rangeDecoder.Range < Decoder.kTopValue) - { - rangeDecoder.Code = (rangeDecoder.Code << 8) | (byte)rangeDecoder.Stream.ReadByte(); - rangeDecoder.Range <<= 8; - } - return 0; - } - else - { - rangeDecoder.Range -= newBound; - rangeDecoder.Code -= newBound; - Prob -= (Prob) >> kNumMoveBits; - if (rangeDecoder.Range < Decoder.kTopValue) - { - rangeDecoder.Code = (rangeDecoder.Code << 8) | (byte)rangeDecoder.Stream.ReadByte(); - rangeDecoder.Range <<= 8; - } - return 1; - } - } - } -} diff --git a/Editor/3rds/7zip/Compress/RangeCoder/RangeCoderBit.cs.meta b/Editor/3rds/7zip/Compress/RangeCoder/RangeCoderBit.cs.meta deleted file mode 100644 index 2a0f148..0000000 --- a/Editor/3rds/7zip/Compress/RangeCoder/RangeCoderBit.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: f3fd3305ff6e02448a7b0470cfe65b77 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/3rds/7zip/Compress/RangeCoder/RangeCoderBitTree.cs b/Editor/3rds/7zip/Compress/RangeCoder/RangeCoderBitTree.cs deleted file mode 100644 index 4b4506f..0000000 --- a/Editor/3rds/7zip/Compress/RangeCoder/RangeCoderBitTree.cs +++ /dev/null @@ -1,157 +0,0 @@ -using System; - -namespace SevenZip.Compression.RangeCoder -{ - struct BitTreeEncoder - { - BitEncoder[] Models; - int NumBitLevels; - - public BitTreeEncoder(int numBitLevels) - { - NumBitLevels = numBitLevels; - Models = new BitEncoder[1 << numBitLevels]; - } - - public void Init() - { - for (uint i = 1; i < (1 << NumBitLevels); i++) - Models[i].Init(); - } - - public void Encode(Encoder rangeEncoder, UInt32 symbol) - { - UInt32 m = 1; - for (int bitIndex = NumBitLevels; bitIndex > 0; ) - { - bitIndex--; - UInt32 bit = (symbol >> bitIndex) & 1; - Models[m].Encode(rangeEncoder, bit); - m = (m << 1) | bit; - } - } - - public void ReverseEncode(Encoder rangeEncoder, UInt32 symbol) - { - UInt32 m = 1; - for (UInt32 i = 0; i < NumBitLevels; i++) - { - UInt32 bit = symbol & 1; - Models[m].Encode(rangeEncoder, bit); - m = (m << 1) | bit; - symbol >>= 1; - } - } - - public UInt32 GetPrice(UInt32 symbol) - { - UInt32 price = 0; - UInt32 m = 1; - for (int bitIndex = NumBitLevels; bitIndex > 0; ) - { - bitIndex--; - UInt32 bit = (symbol >> bitIndex) & 1; - price += Models[m].GetPrice(bit); - m = (m << 1) + bit; - } - return price; - } - - public UInt32 ReverseGetPrice(UInt32 symbol) - { - UInt32 price = 0; - UInt32 m = 1; - for (int i = NumBitLevels; i > 0; i--) - { - UInt32 bit = symbol & 1; - symbol >>= 1; - price += Models[m].GetPrice(bit); - m = (m << 1) | bit; - } - return price; - } - - public static UInt32 ReverseGetPrice(BitEncoder[] Models, UInt32 startIndex, - int NumBitLevels, UInt32 symbol) - { - UInt32 price = 0; - UInt32 m = 1; - for (int i = NumBitLevels; i > 0; i--) - { - UInt32 bit = symbol & 1; - symbol >>= 1; - price += Models[startIndex + m].GetPrice(bit); - m = (m << 1) | bit; - } - return price; - } - - public static void ReverseEncode(BitEncoder[] Models, UInt32 startIndex, - Encoder rangeEncoder, int NumBitLevels, UInt32 symbol) - { - UInt32 m = 1; - for (int i = 0; i < NumBitLevels; i++) - { - UInt32 bit = symbol & 1; - Models[startIndex + m].Encode(rangeEncoder, bit); - m = (m << 1) | bit; - symbol >>= 1; - } - } - } - - struct BitTreeDecoder - { - BitDecoder[] Models; - int NumBitLevels; - - public BitTreeDecoder(int numBitLevels) - { - NumBitLevels = numBitLevels; - Models = new BitDecoder[1 << numBitLevels]; - } - - public void Init() - { - for (uint i = 1; i < (1 << NumBitLevels); i++) - Models[i].Init(); - } - - public uint Decode(RangeCoder.Decoder rangeDecoder) - { - uint m = 1; - for (int bitIndex = NumBitLevels; bitIndex > 0; bitIndex--) - m = (m << 1) + Models[m].Decode(rangeDecoder); - return m - ((uint)1 << NumBitLevels); - } - - public uint ReverseDecode(RangeCoder.Decoder rangeDecoder) - { - uint m = 1; - uint symbol = 0; - for (int bitIndex = 0; bitIndex < NumBitLevels; bitIndex++) - { - uint bit = Models[m].Decode(rangeDecoder); - m <<= 1; - m += bit; - symbol |= (bit << bitIndex); - } - return symbol; - } - - public static uint ReverseDecode(BitDecoder[] Models, UInt32 startIndex, - RangeCoder.Decoder rangeDecoder, int NumBitLevels) - { - uint m = 1; - uint symbol = 0; - for (int bitIndex = 0; bitIndex < NumBitLevels; bitIndex++) - { - uint bit = Models[startIndex + m].Decode(rangeDecoder); - m <<= 1; - m += bit; - symbol |= (bit << bitIndex); - } - return symbol; - } - } -} diff --git a/Editor/3rds/7zip/Compress/RangeCoder/RangeCoderBitTree.cs.meta b/Editor/3rds/7zip/Compress/RangeCoder/RangeCoderBitTree.cs.meta deleted file mode 100644 index df4ba12..0000000 --- a/Editor/3rds/7zip/Compress/RangeCoder/RangeCoderBitTree.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ef79f786b772db344a4792a5cba382ff -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/3rds/7zip/ICoder.cs b/Editor/3rds/7zip/ICoder.cs deleted file mode 100644 index c8b95c8..0000000 --- a/Editor/3rds/7zip/ICoder.cs +++ /dev/null @@ -1,157 +0,0 @@ -// ICoder.h - -using System; - -namespace SevenZip -{ - /// - /// The exception that is thrown when an error in input stream occurs during decoding. - /// - class DataErrorException : ApplicationException - { - public DataErrorException(): base("Data Error") { } - } - - /// - /// The exception that is thrown when the value of an argument is outside the allowable range. - /// - class InvalidParamException : ApplicationException - { - public InvalidParamException(): base("Invalid Parameter") { } - } - - public interface ICodeProgress - { - /// - /// Callback progress. - /// - /// - /// input size. -1 if unknown. - /// - /// - /// output size. -1 if unknown. - /// - void SetProgress(Int64 inSize, Int64 outSize); - }; - - public interface ICoder - { - /// - /// Codes streams. - /// - /// - /// input Stream. - /// - /// - /// output Stream. - /// - /// - /// input Size. -1 if unknown. - /// - /// - /// output Size. -1 if unknown. - /// - /// - /// callback progress reference. - /// - /// - /// if input stream is not valid - /// - void Code(System.IO.Stream inStream, System.IO.Stream outStream, - Int64 inSize, Int64 outSize, ICodeProgress progress); - }; - - /* - public interface ICoder2 - { - void Code(ISequentialInStream []inStreams, - const UInt64 []inSizes, - ISequentialOutStream []outStreams, - UInt64 []outSizes, - ICodeProgress progress); - }; - */ - - /// - /// Provides the fields that represent properties idenitifiers for compressing. - /// - public enum CoderPropID - { - /// - /// Specifies default property. - /// - DefaultProp = 0, - /// - /// Specifies size of dictionary. - /// - DictionarySize, - /// - /// Specifies size of memory for PPM*. - /// - UsedMemorySize, - /// - /// Specifies order for PPM methods. - /// - Order, - /// - /// Specifies Block Size. - /// - BlockSize, - /// - /// Specifies number of postion state bits for LZMA (0 <= x <= 4). - /// - PosStateBits, - /// - /// Specifies number of literal context bits for LZMA (0 <= x <= 8). - /// - LitContextBits, - /// - /// Specifies number of literal position bits for LZMA (0 <= x <= 4). - /// - LitPosBits, - /// - /// Specifies number of fast bytes for LZ*. - /// - NumFastBytes, - /// - /// Specifies match finder. LZMA: "BT2", "BT4" or "BT4B". - /// - MatchFinder, - /// - /// Specifies the number of match finder cyckes. - /// - MatchFinderCycles, - /// - /// Specifies number of passes. - /// - NumPasses, - /// - /// Specifies number of algorithm. - /// - Algorithm, - /// - /// Specifies the number of threads. - /// - NumThreads, - /// - /// Specifies mode with end marker. - /// - EndMarker - }; - - - public interface ISetCoderProperties - { - void SetCoderProperties(CoderPropID[] propIDs, object[] properties); - }; - - public interface IWriteCoderProperties - { - void WriteCoderProperties(System.IO.Stream outStream); - } - - public interface ISetDecoderProperties - { - void SetDecoderProperties(byte[] properties); - } -} diff --git a/Editor/3rds/7zip/ICoder.cs.meta b/Editor/3rds/7zip/ICoder.cs.meta deleted file mode 100644 index f4ca52a..0000000 --- a/Editor/3rds/7zip/ICoder.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 9f4fba00efa28594ea18888f574d028a -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/3rds/UnityFS.meta b/Editor/3rds/UnityFS.meta deleted file mode 100644 index bee3c03..0000000 --- a/Editor/3rds/UnityFS.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 59ab7ccacd9a9944bb9456da235d6760 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/3rds/UnityFS/ArchiveFlags.cs b/Editor/3rds/UnityFS/ArchiveFlags.cs deleted file mode 100644 index 6f46f5d..0000000 --- a/Editor/3rds/UnityFS/ArchiveFlags.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; - -namespace UnityFS -{ - [Flags] - public enum ArchiveFlags - { - CompressionTypeMask = 0x3f, - BlocksAndDirectoryInfoCombined = 0x40, - BlocksInfoAtTheEnd = 0x80, - OldWebPluginCompatibility = 0x100, - BlockInfoNeedPaddingAtStart = 0x200 - } -} diff --git a/Editor/3rds/UnityFS/ArchiveFlags.cs.meta b/Editor/3rds/UnityFS/ArchiveFlags.cs.meta deleted file mode 100644 index 95b0a25..0000000 --- a/Editor/3rds/UnityFS/ArchiveFlags.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 099de05eebdffaf4baeed3290dc98aaf -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/3rds/UnityFS/BinaryReaderExtensions.cs b/Editor/3rds/UnityFS/BinaryReaderExtensions.cs deleted file mode 100644 index 848d820..0000000 --- a/Editor/3rds/UnityFS/BinaryReaderExtensions.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Text; - -namespace UnityFS -{ - public static class BinaryReaderExtensions - { - - public static void AlignStream(this BinaryReader reader, int alignment) - { - var pos = reader.BaseStream.Position; - var mod = pos % alignment; - if (mod != 0) - { - reader.BaseStream.Position += alignment - mod; - } - } - - public static string ReadAlignedString(this BinaryReader reader) - { - var length = reader.ReadInt32(); - if (length > 0 && length <= reader.BaseStream.Length - reader.BaseStream.Position) - { - var stringData = reader.ReadBytes(length); - var result = Encoding.UTF8.GetString(stringData); - reader.AlignStream(4); - return result; - } - return ""; - } - - public static string ReadStringToNull(this BinaryReader reader, int maxLength = 32767) - { - var bytes = new List(); - int count = 0; - while (reader.BaseStream.Position != reader.BaseStream.Length && count < maxLength) - { - var b = reader.ReadByte(); - if (b == 0) - { - break; - } - bytes.Add(b); - count++; - } - return Encoding.UTF8.GetString(bytes.ToArray()); - } - } -} diff --git a/Editor/3rds/UnityFS/BinaryReaderExtensions.cs.meta b/Editor/3rds/UnityFS/BinaryReaderExtensions.cs.meta deleted file mode 100644 index 224d27e..0000000 --- a/Editor/3rds/UnityFS/BinaryReaderExtensions.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: a84e427dd05adde44b4345b3fd49007a -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/3rds/UnityFS/BinaryWriterExtensions.cs b/Editor/3rds/UnityFS/BinaryWriterExtensions.cs deleted file mode 100644 index 8015515..0000000 --- a/Editor/3rds/UnityFS/BinaryWriterExtensions.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System; -using System.IO; -using System.Text; - -namespace UnityFS -{ - public static class BinaryWriterExtensions - { - public static void AlignStream(this BinaryWriter writer, int alignment) - { - var pos = writer.BaseStream.Position; - var mod = pos % alignment; - if (mod != 0) - { - writer.Write(new byte[alignment - mod]); - } - } - - public static void WriteAlignedString(this BinaryWriter writer, string str) - { - var bytes = Encoding.UTF8.GetBytes(str); - writer.Write(bytes.Length); - writer.Write(bytes); - writer.AlignStream(4); - } - - public static void WriteNullEndString(this BinaryWriter writer, string str) - { - writer.Write(Encoding.UTF8.GetBytes(str)); - writer.Write((byte)0); - } - } -} diff --git a/Editor/3rds/UnityFS/BinaryWriterExtensions.cs.meta b/Editor/3rds/UnityFS/BinaryWriterExtensions.cs.meta deleted file mode 100644 index 053416c..0000000 --- a/Editor/3rds/UnityFS/BinaryWriterExtensions.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 02eda21769c083346a5bd9b7dca49427 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/3rds/UnityFS/BundleFileInfo.cs b/Editor/3rds/UnityFS/BundleFileInfo.cs deleted file mode 100644 index d2a9eab..0000000 --- a/Editor/3rds/UnityFS/BundleFileInfo.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace UnityFS -{ - public class BundleSubFile - { - public string file; - public byte[] data; - } - - public class BundleFileInfo - { - public string signature; - public uint version; - public string unityVersion; - public string unityRevision; - public ArchiveFlags flags; - public List files; - } -} diff --git a/Editor/3rds/UnityFS/BundleFileInfo.cs.meta b/Editor/3rds/UnityFS/BundleFileInfo.cs.meta deleted file mode 100644 index b33b9b2..0000000 --- a/Editor/3rds/UnityFS/BundleFileInfo.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 1a72550a949e322419b9c5d6e4fe495d -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/3rds/UnityFS/BundleFileReader.cs b/Editor/3rds/UnityFS/BundleFileReader.cs deleted file mode 100644 index 1804cf4..0000000 --- a/Editor/3rds/UnityFS/BundleFileReader.cs +++ /dev/null @@ -1,212 +0,0 @@ -using LZ4; -using System; -using System.IO; -using System.Linq; -using UnityEngine; - -namespace UnityFS -{ - - public class BundleFileReader - { - - private Header m_Header; - private StorageBlock[] m_BlocksInfo; - private Node[] m_DirectoryInfo; - - private StreamFile[] fileList; - - public BundleFileReader() - { - - } - - public void Load(EndianBinaryReader reader) - { - Debug.Log($"reader. pos:{reader.Position} length:{reader.BaseStream.Length}"); - m_Header = new Header(); - m_Header.signature = reader.ReadStringToNull(); - m_Header.version = reader.ReadUInt32(); - m_Header.unityVersion = reader.ReadStringToNull(); - m_Header.unityRevision = reader.ReadStringToNull(); - System.Diagnostics.Debug.Assert(m_Header.signature == "UnityFS"); - - - m_Header.size = reader.ReadInt64(); - Debug.Log($"header size:{m_Header.size}"); - m_Header.compressedBlocksInfoSize = reader.ReadUInt32(); - m_Header.uncompressedBlocksInfoSize = reader.ReadUInt32(); - m_Header.flags = (ArchiveFlags)reader.ReadUInt32(); - if (m_Header.signature != "UnityFS") - { - reader.ReadByte(); - } - - ReadMetadata(reader); - using (var blocksStream = CreateBlocksStream()) - { - ReadBlocks(reader, blocksStream); - ReadFiles(blocksStream); - } - } - - public BundleFileInfo CreateBundleFileInfo() - { - return new BundleFileInfo - { - signature = m_Header.signature, - version = m_Header.version, - unityVersion = m_Header.unityVersion, - unityRevision = m_Header.unityRevision, - files = fileList.Select(f => new BundleSubFile { file = f.path, data = f.stream.ReadAllBytes() }).ToList(), - }; - } - - private byte[] ReadBlocksInfoAndDirectoryMetadataUnCompressedBytes(EndianBinaryReader reader) - { - byte[] metadataUncompressBytes; - if (m_Header.version >= 7) - { - reader.AlignStream(16); - } - if ((m_Header.flags & ArchiveFlags.BlocksInfoAtTheEnd) != 0) - { - var position = reader.Position; - reader.Position = reader.BaseStream.Length - m_Header.compressedBlocksInfoSize; - metadataUncompressBytes = reader.ReadBytes((int)m_Header.compressedBlocksInfoSize); - reader.Position = position; - } - else //0x40 BlocksAndDirectoryInfoCombined - { - metadataUncompressBytes = reader.ReadBytes((int)m_Header.compressedBlocksInfoSize); - } - return metadataUncompressBytes; - } - - private byte[] DecompressBytes(CompressionType compressionType, byte[] compressedBytes, uint uncompressedSize) - { - switch (compressionType) - { - case CompressionType.None: - { - return compressedBytes; - } - case CompressionType.Lzma: - { - var uncompressedStream = new MemoryStream((int)(uncompressedSize)); - using (var compressedStream = new MemoryStream(compressedBytes)) - { - ComparessHelper.Decompress7Zip(compressedStream, uncompressedStream, m_Header.compressedBlocksInfoSize, m_Header.uncompressedBlocksInfoSize); - } - return uncompressedStream.ReadAllBytes(); - } - case CompressionType.Lz4: - case CompressionType.Lz4HC: - { - var uncompressedBytes = new byte[uncompressedSize]; - var numWrite = LZ4Codec.Decode(compressedBytes, 0, compressedBytes.Length, uncompressedBytes, 0, uncompressedBytes.Length, true); - if (numWrite != uncompressedSize) - { - throw new IOException($"Lz4 decompression error, write {numWrite} bytes but expected {uncompressedSize} bytes"); - } - return uncompressedBytes; - } - default: - throw new IOException($"Unsupported compression type {compressionType}"); - } - } - - private void ReadMetadata(EndianBinaryReader reader) - { - byte[] compressMetadataBytes = ReadBlocksInfoAndDirectoryMetadataUnCompressedBytes(reader); - MemoryStream metadataStream = new MemoryStream(DecompressBytes((CompressionType)(m_Header.flags & ArchiveFlags.CompressionTypeMask), compressMetadataBytes, m_Header.uncompressedBlocksInfoSize)); - using (var blocksInfoReader = new EndianBinaryReader(metadataStream)) - { - var uncompressedDataHash = blocksInfoReader.ReadBytes(16); - var blocksInfoCount = blocksInfoReader.ReadInt32(); - m_BlocksInfo = new StorageBlock[blocksInfoCount]; - for (int i = 0; i < blocksInfoCount; i++) - { - m_BlocksInfo[i] = new StorageBlock - { - uncompressedSize = blocksInfoReader.ReadUInt32(), - compressedSize = blocksInfoReader.ReadUInt32(), - flags = (StorageBlockFlags)blocksInfoReader.ReadUInt16() - }; - } - - var nodesCount = blocksInfoReader.ReadInt32(); - m_DirectoryInfo = new Node[nodesCount]; - for (int i = 0; i < nodesCount; i++) - { - m_DirectoryInfo[i] = new Node - { - offset = blocksInfoReader.ReadInt64(), - size = blocksInfoReader.ReadInt64(), - flags = blocksInfoReader.ReadUInt32(), - path = blocksInfoReader.ReadStringToNull(), - }; - } - } - if (m_Header.flags.HasFlag(ArchiveFlags.BlockInfoNeedPaddingAtStart)) - { - reader.AlignStream(16); - } - } - - - private Stream CreateBlocksStream() - { - Stream blocksStream; - var uncompressedSizeSum = m_BlocksInfo.Sum(x => x.uncompressedSize); - if (uncompressedSizeSum >= int.MaxValue) - { - throw new Exception($"too fig file"); - } - else - { - blocksStream = new MemoryStream((int)uncompressedSizeSum); - } - return blocksStream; - } - - public void ReadFiles(Stream blocksStream) - { - fileList = new StreamFile[m_DirectoryInfo.Length]; - for (int i = 0; i < m_DirectoryInfo.Length; i++) - { - var node = m_DirectoryInfo[i]; - var file = new StreamFile(); - fileList[i] = file; - file.path = node.path; - file.fileName = Path.GetFileName(node.path); - if (node.size >= int.MaxValue) - { - throw new Exception($"exceed max file size"); - /*var memoryMappedFile = MemoryMappedFile.CreateNew(null, entryinfo_size); - file.stream = memoryMappedFile.CreateViewStream();*/ - //var extractPath = path + "_unpacked" + Path.DirectorySeparatorChar; - //Directory.CreateDirectory(extractPath); - //file.stream = new FileStream(extractPath + file.fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite); - } - file.stream = new MemoryStream((int)node.size); - blocksStream.Position = node.offset; - blocksStream.CopyTo(file.stream, node.size); - file.stream.Position = 0; - } - } - - private void ReadBlocks(EndianBinaryReader reader, Stream blocksStream) - { - foreach (var blockInfo in m_BlocksInfo) - { - var compressedSize = (int)blockInfo.compressedSize; - byte[] compressedBlockBytes = reader.ReadBytes(compressedSize); - var compressionType = (CompressionType)(blockInfo.flags & StorageBlockFlags.CompressionTypeMask); - byte[] uncompressedBlockBytes = DecompressBytes(compressionType, compressedBlockBytes, blockInfo.uncompressedSize); - blocksStream.Write(uncompressedBlockBytes, 0, uncompressedBlockBytes.Length); - } - blocksStream.Position = 0; - } - } -} diff --git a/Editor/3rds/UnityFS/BundleFileReader.cs.meta b/Editor/3rds/UnityFS/BundleFileReader.cs.meta deleted file mode 100644 index 8b3cfae..0000000 --- a/Editor/3rds/UnityFS/BundleFileReader.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: f9b938458cc610e4d8a910c4499693cf -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/3rds/UnityFS/BundleFileWriter.cs b/Editor/3rds/UnityFS/BundleFileWriter.cs deleted file mode 100644 index 7e039cb..0000000 --- a/Editor/3rds/UnityFS/BundleFileWriter.cs +++ /dev/null @@ -1,112 +0,0 @@ -using LZ4; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using UnityEngine; - -namespace UnityFS -{ - public class BundleFileWriter - { - private readonly BundleFileInfo _bundle; - - private readonly List _files = new List(); - private readonly List _blocks = new List(); - - private readonly EndianBinaryWriter _blockDirectoryMetadataStream = new EndianBinaryWriter(new MemoryStream()); - private byte[] _blockBytes; - - public BundleFileWriter(BundleFileInfo bundle) - { - _bundle = bundle; - } - - public void Write(EndianBinaryWriter output) - { - InitBlockAndDirectories(); - - output.WriteNullEndString(_bundle.signature); - output.Write(_bundle.version); - output.WriteNullEndString(_bundle.unityVersion); - output.WriteNullEndString(_bundle.unityRevision); - - BuildBlockDirectoryMetadata(); - - - long sizePos = output.Position; - output.Write(0L); - output.Write((uint)_blockDirectoryMetadataStream.Length); - output.Write((uint)_blockDirectoryMetadataStream.Length); - ArchiveFlags flags = ArchiveFlags.BlocksAndDirectoryInfoCombined | (uint)CompressionType.None; - output.Write((uint)flags); - - if (_bundle.version >= 7) - { - output.AlignStream(16); - } - byte[] metadataBytes = _blockDirectoryMetadataStream.BaseStream.ReadAllBytes(); - output.Write(metadataBytes, 0, metadataBytes.Length); - - byte[] dataBytes = _blockBytes; - output.Write(dataBytes, 0, dataBytes.Length); - - output.Position = sizePos; - output.Write(output.Length); - } - - private void InitBlockAndDirectories() - { - var dataStream = new MemoryStream(); - foreach(var file in _bundle.files) - { - byte[] data = file.data; - _files.Add(new Node { path = file.file, flags = 0, offset = dataStream.Length, size = data.LongLength }); - dataStream.Write(data, 0, data.Length); - } - byte[] dataBytes = dataStream.ToArray(); - - var compressedBlockStream = new MemoryStream(dataBytes.Length / 2); - int blockByteSize = 128 * 1024; - long dataSize = dataBytes.Length; - byte[] tempCompressBlock = new byte[blockByteSize * 2]; - for(long i = 0, blockNum = (dataSize + blockByteSize - 1) / blockByteSize; i < blockNum; i++) - { - long curBlockSize = Math.Min(dataSize, blockByteSize); - dataSize -= curBlockSize; - - int compressedSize = LZ4Codec.Encode(dataBytes, (int)(i * blockByteSize), (int)curBlockSize, tempCompressBlock, 0, tempCompressBlock.Length); - compressedBlockStream.Write(tempCompressBlock, 0, compressedSize); - _blocks.Add(new StorageBlock { flags = (StorageBlockFlags)(int)CompressionType.Lz4, compressedSize = (uint)compressedSize, uncompressedSize = (uint)curBlockSize }); - //Debug.Log($"== block[{i}] uncompressedSize:{curBlockSize} compressedSize:{compressedSize} totalblocksize:{compressedBlockStream.Length}"); - } - _blockBytes = compressedBlockStream.ToArray(); - } - - private void BuildBlockDirectoryMetadata() - { - var hash = new byte[16]; - _blockDirectoryMetadataStream.Write(hash, 0, 16); - - _blockDirectoryMetadataStream.Write((uint)_blocks.Count); - foreach(var b in _blocks) - { - _blockDirectoryMetadataStream.Write(b.uncompressedSize); - _blockDirectoryMetadataStream.Write(b.compressedSize); - _blockDirectoryMetadataStream.Write((ushort)b.flags); - } - - _blockDirectoryMetadataStream.Write((uint)_files.Count); - foreach(var f in _files) - { - _blockDirectoryMetadataStream.Write(f.offset); - _blockDirectoryMetadataStream.Write(f.size); - _blockDirectoryMetadataStream.Write(f.flags); - _blockDirectoryMetadataStream.WriteNullEndString(f.path); - } - //Debug.Log($"block and directory metadata size:{_blockDirectoryMetadataStream.Length}"); - } - } -} diff --git a/Editor/3rds/UnityFS/BundleFileWriter.cs.meta b/Editor/3rds/UnityFS/BundleFileWriter.cs.meta deleted file mode 100644 index 98d7466..0000000 --- a/Editor/3rds/UnityFS/BundleFileWriter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: d6705163b267de54a868f5e84f6c7024 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/3rds/UnityFS/CompressionType.cs b/Editor/3rds/UnityFS/CompressionType.cs deleted file mode 100644 index 032103b..0000000 --- a/Editor/3rds/UnityFS/CompressionType.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace UnityFS -{ - public enum CompressionType - { - None, - Lzma, - Lz4, - Lz4HC, - Lzham - } -} diff --git a/Editor/3rds/UnityFS/CompressionType.cs.meta b/Editor/3rds/UnityFS/CompressionType.cs.meta deleted file mode 100644 index ce8a30f..0000000 --- a/Editor/3rds/UnityFS/CompressionType.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ddcd6644c83d2a94f9668d6e913bd80e -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/3rds/UnityFS/EndianBinaryReader.cs b/Editor/3rds/UnityFS/EndianBinaryReader.cs deleted file mode 100644 index d6716a8..0000000 --- a/Editor/3rds/UnityFS/EndianBinaryReader.cs +++ /dev/null @@ -1,107 +0,0 @@ -using System; -using System.IO; - -namespace UnityFS -{ - public class EndianBinaryReader : BinaryReader - { - private readonly byte[] buffer; - - public EndianType Endian; - - public EndianBinaryReader(Stream stream, EndianType endian = EndianType.BigEndian) : base(stream) - { - Endian = endian; - buffer = new byte[8]; - } - - public long Position - { - get => BaseStream.Position; - set => BaseStream.Position = value; - } - - private unsafe void ReadBufferBigEndian(byte* dst, byte[] src, int size) - { - System.Diagnostics.Debug.Assert(BitConverter.IsLittleEndian); - for (int i = 0; i < size; i++) - { - dst[i] = src[size - i - 1]; - } - } - - public override short ReadInt16() - { - return (short)ReadUInt16(); - } - - public unsafe override ushort ReadUInt16() - { - if (Endian == EndianType.BigEndian) - { - Read(buffer, 0, 2); - ushort x = 0; - ReadBufferBigEndian((byte*)&x, buffer, 2); - return x; - } - return base.ReadUInt16(); - } - - public override int ReadInt32() - { - return (int)ReadUInt32(); - } - - public unsafe override uint ReadUInt32() - { - if (Endian == EndianType.BigEndian) - { - Read(buffer, 0, 4); - uint x = 0; - ReadBufferBigEndian((byte*)&x, buffer, 4); - return x; - } - return base.ReadUInt32(); - } - - public override long ReadInt64() - { - return (long)ReadUInt64(); - } - - public unsafe override ulong ReadUInt64() - { - if (Endian == EndianType.BigEndian) - { - Read(buffer, 0, 8); - - ulong x = 0; - ReadBufferBigEndian((byte*)&x, buffer, 8); - return x; - } - return base.ReadUInt64(); - } - - public override float ReadSingle() - { - if (Endian == EndianType.BigEndian) - { - Read(buffer, 0, 4); - Array.Reverse(buffer, 0, 4); - return BitConverter.ToSingle(buffer, 0); - } - return base.ReadSingle(); - } - - public override double ReadDouble() - { - if (Endian == EndianType.BigEndian) - { - Read(buffer, 0, 8); - Array.Reverse(buffer); - return BitConverter.ToDouble(buffer, 0); - } - return base.ReadDouble(); - } - } -} diff --git a/Editor/3rds/UnityFS/EndianBinaryReader.cs.meta b/Editor/3rds/UnityFS/EndianBinaryReader.cs.meta deleted file mode 100644 index 53183c0..0000000 --- a/Editor/3rds/UnityFS/EndianBinaryReader.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 9b02c037f0fa1014da65773804248d8d -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/3rds/UnityFS/EndianBinaryWriter.cs b/Editor/3rds/UnityFS/EndianBinaryWriter.cs deleted file mode 100644 index 03938a9..0000000 --- a/Editor/3rds/UnityFS/EndianBinaryWriter.cs +++ /dev/null @@ -1,107 +0,0 @@ -using System; -using System.IO; - -namespace UnityFS -{ - public class EndianBinaryWriter : BinaryWriter - { - private readonly byte[] buffer; - - public EndianType Endian; - - public EndianBinaryWriter(Stream stream, EndianType endian = EndianType.BigEndian) : base(stream) - { - Endian = endian; - buffer = new byte[8]; - } - - public long Position - { - get => BaseStream.Position; - set => BaseStream.Position = value; - } - - public long Length => BaseStream.Length; - - public override void Write(short x) - { - Write((ushort)x); - } - - private unsafe void WriteBufferBigEndian(byte[] dst, byte* src, int size) - { - System.Diagnostics.Debug.Assert(BitConverter.IsLittleEndian); - for(int i = 0; i < size; i++) - { - dst[i] = src[size - i - 1]; - } - } - - public unsafe override void Write(ushort x) - { - if (Endian == EndianType.BigEndian) - { - WriteBufferBigEndian(buffer, (byte*)&x, 2); - Write(buffer, 0, 2); - return; - } - base.Write(x); - } - - public override void Write(int x) - { - Write((uint)x); - } - - public unsafe override void Write(uint x) - { - if (Endian == EndianType.BigEndian) - { - WriteBufferBigEndian(buffer, (byte*)&x, 4); - Write(buffer, 0, 4); - return; - } - base.Write(x); - } - - public override void Write(long x) - { - Write((ulong)x); - } - - public unsafe override void Write(ulong x) - { - if (Endian == EndianType.BigEndian) - { - WriteBufferBigEndian(buffer, (byte*)&x, 8); - Write(buffer, 0, 8); - return; - } - base.Write(x); - } - - public override void Write(float x) - { - if (Endian == EndianType.BigEndian) - { - var buf = BitConverter.GetBytes(x); - Array.Reverse(buf, 0, 4); - Write(buf, 0, 4); - return; - } - base.Write(x); - } - - public override void Write(double x) - { - if (Endian == EndianType.BigEndian) - { - var buf = BitConverter.GetBytes(x); - Array.Reverse(buf, 0, 8); - Write(buf, 0, 8); - return; - } - base.Write(x); - } - } -} diff --git a/Editor/3rds/UnityFS/EndianBinaryWriter.cs.meta b/Editor/3rds/UnityFS/EndianBinaryWriter.cs.meta deleted file mode 100644 index cff8503..0000000 --- a/Editor/3rds/UnityFS/EndianBinaryWriter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 4107364c7434b2042ad647b28e322513 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/3rds/UnityFS/EndianType.cs b/Editor/3rds/UnityFS/EndianType.cs deleted file mode 100644 index 53e740f..0000000 --- a/Editor/3rds/UnityFS/EndianType.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace UnityFS -{ - public enum EndianType - { - LittleEndian, - BigEndian - } -} diff --git a/Editor/3rds/UnityFS/EndianType.cs.meta b/Editor/3rds/UnityFS/EndianType.cs.meta deleted file mode 100644 index c878edc..0000000 --- a/Editor/3rds/UnityFS/EndianType.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 2f6cbab4506c18248b410a164be891d2 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/3rds/UnityFS/GlobalgamedatasPatcher.cs b/Editor/3rds/UnityFS/GlobalgamedatasPatcher.cs deleted file mode 100644 index 193b1f2..0000000 --- a/Editor/3rds/UnityFS/GlobalgamedatasPatcher.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using UnityEngine; -using UnityFS; - -namespace HybridCLR.Editor.UnityBinFileReader -{ - public class Dataunity3dPatcher - { - - public void ApplyPatch(string dataunity3dFile, List hotUpdateAssemblies) - { - var reader = new BundleFileReader(); - using (var fs = new EndianBinaryReader(new MemoryStream(File.ReadAllBytes(dataunity3dFile)))) - { - reader.Load(fs); - } - - var info = reader.CreateBundleFileInfo(); - //Debug.Log($"name:{info.signature} version:{info.version} files:{info.files.Count}"); - //foreach (var file in info.files) - //{ - // Debug.Log($"file:{file.file} size:{file.data.Length}"); - //} - - var globalgamemanagersFile = info.files.Find(f => f.file == "globalgamemanagers"); - //Debug.LogFormat("gobalgamemanagers origin size:{0}", globalgamemanagersFile.data.Length); - - var ggdBinFile = new UnityBinFile(); - ggdBinFile.LoadFromStream(new MemoryStream(globalgamemanagersFile.data)); - ggdBinFile.AddScriptingAssemblies(hotUpdateAssemblies); - byte[] patchedGlobalgamedatasBytes = ggdBinFile.CreatePatchedBytes(); - //Debug.LogFormat("gobalgamemanagers post patche size:{0}", patchedGlobalgamedatasBytes.Length); - globalgamemanagersFile.data = patchedGlobalgamedatasBytes; - - var writer = new BundleFileWriter(info); - var output = new MemoryStream(); - writer.Write(new EndianBinaryWriter(output)); - Debug.Log($"patch file:{dataunity3dFile} size:{output.Length}"); - - //string bakFile = dataunity3dFile + ".bak"; - //if (!File.Exists(bakFile)) - //{ - // File.Copy(dataunity3dFile, bakFile); - //} - File.WriteAllBytes(dataunity3dFile, output.ToArray()); - } - } -} diff --git a/Editor/3rds/UnityFS/GlobalgamedatasPatcher.cs.meta b/Editor/3rds/UnityFS/GlobalgamedatasPatcher.cs.meta deleted file mode 100644 index b33d83c..0000000 --- a/Editor/3rds/UnityFS/GlobalgamedatasPatcher.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 653a22d285c79f44a8113c5571b2d26b -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/3rds/UnityFS/Header.cs b/Editor/3rds/UnityFS/Header.cs deleted file mode 100644 index 2715cce..0000000 --- a/Editor/3rds/UnityFS/Header.cs +++ /dev/null @@ -1,14 +0,0 @@ -namespace UnityFS -{ - public class Header - { - public string signature; - public uint version; - public string unityVersion; - public string unityRevision; - public long size; - public uint compressedBlocksInfoSize; - public uint uncompressedBlocksInfoSize; - public ArchiveFlags flags; - } -} diff --git a/Editor/3rds/UnityFS/Header.cs.meta b/Editor/3rds/UnityFS/Header.cs.meta deleted file mode 100644 index e5a516a..0000000 --- a/Editor/3rds/UnityFS/Header.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: f121e0520fa65c240884d43fd00b3c2a -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/3rds/UnityFS/Node.cs b/Editor/3rds/UnityFS/Node.cs deleted file mode 100644 index d9cfd97..0000000 --- a/Editor/3rds/UnityFS/Node.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace UnityFS -{ - public class Node - { - public long offset; - public long size; - public uint flags; - public string path; - } -} diff --git a/Editor/3rds/UnityFS/Node.cs.meta b/Editor/3rds/UnityFS/Node.cs.meta deleted file mode 100644 index 0736374..0000000 --- a/Editor/3rds/UnityFS/Node.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: e3eea8a6a32b6ac4ba609b39715e25e2 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/3rds/UnityFS/ScriptingAssembliesJsonPatcher.cs b/Editor/3rds/UnityFS/ScriptingAssembliesJsonPatcher.cs deleted file mode 100644 index 71b9ab3..0000000 --- a/Editor/3rds/UnityFS/ScriptingAssembliesJsonPatcher.cs +++ /dev/null @@ -1,50 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using UnityEngine; - -namespace UnityFS -{ - public class ScriptingAssembliesJsonPatcher - { - [Serializable] - private class ScriptingAssemblies - { - public List names; - public List types; - } - - private string _file; - ScriptingAssemblies _scriptingAssemblies; - - public void Load(string file) - { - _file = file; - string content = File.ReadAllText(file); - _scriptingAssemblies = JsonUtility.FromJson(content); - } - - public void AddScriptingAssemblies(List assemblies) - { - foreach (string name in assemblies) - { - if (!_scriptingAssemblies.names.Contains(name)) - { - _scriptingAssemblies.names.Add(name); - _scriptingAssemblies.types.Add(16); // user dll type - Debug.Log($"[PatchScriptAssembliesJson] add hotfix assembly:{name} to {_file}"); - } - } - } - - public void Save(string jsonFile) - { - string content = JsonUtility.ToJson(_scriptingAssemblies); - - File.WriteAllText(jsonFile, content); - } - } -} diff --git a/Editor/3rds/UnityFS/ScriptingAssembliesJsonPatcher.cs.meta b/Editor/3rds/UnityFS/ScriptingAssembliesJsonPatcher.cs.meta deleted file mode 100644 index b1d4449..0000000 --- a/Editor/3rds/UnityFS/ScriptingAssembliesJsonPatcher.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 8f2dd29d56a640d4ebd1c2fd374b7638 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/3rds/UnityFS/SevenZipHelper.cs b/Editor/3rds/UnityFS/SevenZipHelper.cs deleted file mode 100644 index 2d17669..0000000 --- a/Editor/3rds/UnityFS/SevenZipHelper.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System; -using System.IO; -using SevenZip.Compression.LZMA; - - -namespace UnityFS -{ - public static class ComparessHelper - { - public static MemoryStream Decompress7Zip(MemoryStream inStream) - { - var decoder = new Decoder(); - - inStream.Seek(0, SeekOrigin.Begin); - var newOutStream = new MemoryStream(); - - var properties = new byte[5]; - if (inStream.Read(properties, 0, 5) != 5) - throw new Exception("input .lzma is too short"); - long outSize = 0; - for (var i = 0; i < 8; i++) - { - var v = inStream.ReadByte(); - if (v < 0) - throw new Exception("Can't Read 1"); - outSize |= ((long)(byte)v) << (8 * i); - } - decoder.SetDecoderProperties(properties); - - var compressedSize = inStream.Length - inStream.Position; - decoder.Code(inStream, newOutStream, compressedSize, outSize, null); - - newOutStream.Position = 0; - return newOutStream; - } - - public static void Decompress7Zip(Stream compressedStream, Stream decompressedStream, long compressedSize, long decompressedSize) - { - var basePosition = compressedStream.Position; - var decoder = new Decoder(); - var properties = new byte[5]; - if (compressedStream.Read(properties, 0, 5) != 5) - throw new Exception("input .lzma is too short"); - decoder.SetDecoderProperties(properties); - decoder.Code(compressedStream, decompressedStream, compressedSize - 5, decompressedSize, null); - compressedStream.Position = basePosition + compressedSize; - } - } -} diff --git a/Editor/3rds/UnityFS/SevenZipHelper.cs.meta b/Editor/3rds/UnityFS/SevenZipHelper.cs.meta deleted file mode 100644 index 77f375b..0000000 --- a/Editor/3rds/UnityFS/SevenZipHelper.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 6606a654e10b3ba48b76b566b903b353 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/3rds/UnityFS/StorageBlock.cs b/Editor/3rds/UnityFS/StorageBlock.cs deleted file mode 100644 index 148c4d1..0000000 --- a/Editor/3rds/UnityFS/StorageBlock.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace UnityFS -{ - public class StorageBlock - { - public uint compressedSize; - public uint uncompressedSize; - public StorageBlockFlags flags; - } -} diff --git a/Editor/3rds/UnityFS/StorageBlock.cs.meta b/Editor/3rds/UnityFS/StorageBlock.cs.meta deleted file mode 100644 index e1e8ad9..0000000 --- a/Editor/3rds/UnityFS/StorageBlock.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 40dc58bec5631f14c9c17c8a486496d4 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/3rds/UnityFS/StorageBlockFlags.cs b/Editor/3rds/UnityFS/StorageBlockFlags.cs deleted file mode 100644 index 619fcac..0000000 --- a/Editor/3rds/UnityFS/StorageBlockFlags.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System; - -namespace UnityFS -{ - [Flags] - public enum StorageBlockFlags - { - CompressionTypeMask = 0x3f, - Streamed = 0x40 - } -} diff --git a/Editor/3rds/UnityFS/StorageBlockFlags.cs.meta b/Editor/3rds/UnityFS/StorageBlockFlags.cs.meta deleted file mode 100644 index d3f199d..0000000 --- a/Editor/3rds/UnityFS/StorageBlockFlags.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 79b9ed6799d3caf459cf2dfae5765a23 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/3rds/UnityFS/StreamExtensions.cs b/Editor/3rds/UnityFS/StreamExtensions.cs deleted file mode 100644 index ecffd07..0000000 --- a/Editor/3rds/UnityFS/StreamExtensions.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System.IO; - -namespace UnityFS -{ - public static class StreamExtensions - { - private const int BufferSize = 81920; - - public static void CopyTo(this Stream source, Stream destination, long size) - { - var buffer = new byte[BufferSize]; - for (var left = size; left > 0; left -= BufferSize) - { - int toRead = BufferSize < left ? BufferSize : (int)left; - int read = source.Read(buffer, 0, toRead); - destination.Write(buffer, 0, read); - if (read != toRead) - { - return; - } - } - } - - public static byte[] ReadAllBytes(this Stream source) - { - source.Position = 0; - var bytes = new byte[source.Length]; - source.Read(bytes, 0, bytes.Length); - return bytes; - } - } -} diff --git a/Editor/3rds/UnityFS/StreamExtensions.cs.meta b/Editor/3rds/UnityFS/StreamExtensions.cs.meta deleted file mode 100644 index a06440e..0000000 --- a/Editor/3rds/UnityFS/StreamExtensions.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 2262fbf5672028a48b0c63821d7ff0c0 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/3rds/UnityFS/StreamFile.cs b/Editor/3rds/UnityFS/StreamFile.cs deleted file mode 100644 index 0fffc06..0000000 --- a/Editor/3rds/UnityFS/StreamFile.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System.IO; - -namespace UnityFS -{ - public class StreamFile - { - public string path; - public string fileName; - public Stream stream; - } -} diff --git a/Editor/3rds/UnityFS/StreamFile.cs.meta b/Editor/3rds/UnityFS/StreamFile.cs.meta deleted file mode 100644 index 7c14e8d..0000000 --- a/Editor/3rds/UnityFS/StreamFile.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: fad7df04825c947489aad0d5d0c191a7 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/3rds/UnityFS/UnityBinFile.cs b/Editor/3rds/UnityFS/UnityBinFile.cs deleted file mode 100644 index ad4ad5f..0000000 --- a/Editor/3rds/UnityFS/UnityBinFile.cs +++ /dev/null @@ -1,124 +0,0 @@ -using System.Collections; -using System.Collections.Generic; -using System.IO; -using UnityEngine; -using System.Text; -using System.Reflection; -using System; -using System.Linq; - -namespace UnityFS -{ - /// - /// Unity 生成的二进制文件(本代码不支持5.x之前的版本) - /// - public unsafe class UnityBinFile - { - /* - * MonoManager: idx: 6; - * type: metaData.types[objects[6].typeID] - */ - public const int kMonoManagerIdx = 6; - - public FileHeader header; - public MetaData metaData; - public ScriptsData scriptsData; - - private Stream _originStream; - - public void LoadFromStream(Stream source) - { - _originStream = source; - using (var br = new BinaryReader(source, Encoding.UTF8, true)) - { - header.LoadFromStream(br); - // 按理说 metaData 应该新开一个buffer来避免加载时的对齐逻辑问题,但由于 sizeof(Header) = 20,已经对齐到4了,所以可以连续读 - metaData.LoadFromStream(br, header.dataOffset); - scriptsData = metaData.GetScriptData(br); - } - } - - public void Load(string path) - { - LoadFromStream(new MemoryStream(File.ReadAllBytes(path))); - } - - public void AddScriptingAssemblies(List assemblies) - { - foreach (string name in assemblies) - { - if (!scriptsData.dllNames.Contains(name)) - { - scriptsData.dllNames.Add(name); - scriptsData.dllTypes.Add(16); // user dll type - Debug.Log($"[PatchScriptAssembliesJson] add dll:{name} to globalgamemanagers"); - } - } - } - - public byte[] CreatePatchedBytes() - { - var fsR = _originStream; - fsR.Position = 0; - var brR = new BinaryReader(fsR, Encoding.UTF8, true); - - var ms = new MemoryStream((int)(header.fileSize * 1.5f)); - var bw = new BinaryWriter(ms, Encoding.UTF8, true); - - /* - * 开始写入data - * dll名称列表存储于 data 区段,修改其数据并不会影响 MetaData 大小,因此 dataOffset 不会改变 - */ - ms.Position = header.dataOffset; - - Dictionary newObjInfos = new Dictionary(); - foreach (var kv in metaData.objects) - { - long objID = kv.Key; - ObjectInfo objInfo = kv.Value; - - byte[] buff = new byte[objInfo.size]; - fsR.Position = objInfo.realPos; - brR.Read(buff, 0, buff.Length); - - - {// unity 的数据偏移貌似会对齐到 8 - int newPos = (((int)ms.Position + 7) >> 3) << 3; - int gapSize = newPos - (int)ms.Position; - - for (int i = 0; i < gapSize; i++) - bw.Write((byte)0); - - objInfo.dataPos = (uint)ms.Position - header.dataOffset; // 重定位数据偏移 - } - - if (objID != kMonoManagerIdx) - bw.Write(buff, 0, buff.Length); - else - objInfo.size = (uint)scriptsData.SaveToStream(bw); - - newObjInfos.Add(objID, objInfo); - } - - metaData.objects = newObjInfos; - header.fileSize = (uint)ms.Position; - - ms.Position = 0; - header.SaveToStream(bw); - metaData.SaveToStream(bw); - - brR.Close(); - - // 写入新文件 - ms.Position = 0; - return ms.ToArray(); - } - - public void Save(string newPath) - { - byte[] patchedBytes = CreatePatchedBytes(); - File.WriteAllBytes(newPath, patchedBytes); - } - } - -} diff --git a/Editor/3rds/UnityFS/UnityBinFile.cs.meta b/Editor/3rds/UnityFS/UnityBinFile.cs.meta deleted file mode 100644 index 457dbb7..0000000 --- a/Editor/3rds/UnityFS/UnityBinFile.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 7f9902041e9a1ff4c9f2d65d6384530d -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/3rds/UnityFS/UnityBinFileDefines.cs b/Editor/3rds/UnityFS/UnityBinFileDefines.cs deleted file mode 100644 index 637dc4e..0000000 --- a/Editor/3rds/UnityFS/UnityBinFileDefines.cs +++ /dev/null @@ -1,397 +0,0 @@ -using System.Collections; -using System.Collections.Generic; -using System.IO; -using UnityEngine; -using static UnityFS.UnityBinUtils; - -namespace UnityFS -{ - public struct FileHeader - { - public const int kSize = 20; - - public uint dataSize => fileSize - metadataSize; - - public uint metadataSize; - public uint fileSize; - public uint version; - public uint dataOffset; - public byte endianess; - - public void LoadFromStream(BinaryReader br) - { - long startPos = br.BaseStream.Position; - metadataSize = br.ReadUInt32(); - fileSize = br.ReadUInt32(); - version = br.ReadUInt32(); - dataOffset = br.ReadUInt32(); - endianess = br.ReadByte(); - br.BaseStream.Position = startPos + kSize; - - SwapEndianess(); - } - - public long SaveToStream(BinaryWriter bw) - { - SwapEndianess(); - - long startPos = bw.BaseStream.Position; - bw.Write(metadataSize); - bw.Write(fileSize); - bw.Write(version); - bw.Write(dataOffset); - bw.Write(endianess); - bw.BaseStream.Position = startPos + kSize; - return kSize; - } - - void SwapEndianess() - { - SwapUInt(ref metadataSize); - SwapUInt(ref fileSize); - SwapUInt(ref version); - SwapUInt(ref dataOffset); - } - } - - public struct MetaData - { - public long dataStartPos; - - public string version; - public uint platform; - public bool enableTypeTree; - public int typeCount; - public ObjectType[] types; - public int objectCount; - public Dictionary objects; - public int scriptTypeCount; - public ScriptType[] scriptTypes; - public int externalsCount; - public ExternalInfo[] externals; - -#if UNITY_2019_2_OR_NEWER - public int refTypeCount; - public ObjectType[] refTypes; -#endif - public string dummyStr; - - public void LoadFromStream(BinaryReader br, uint dataOffset) - { - long startPos = br.BaseStream.Position; - dataStartPos = startPos; - - version = br.ReadRawString(); - platform = br.ReadUInt32(); - enableTypeTree = br.ReadBoolean(); - typeCount = br.ReadInt32(); - types = new ObjectType[typeCount]; - - for (int i = 0; i < typeCount; i++) - { - types[i].LoadFromStream(br); - } - - objectCount = br.ReadInt32(); - objects = new Dictionary(); - for(int i = 0; i < objectCount; i++) - { - long id = br.AlignedReadInt64(); - ObjectInfo objInfo = new ObjectInfo(); - objInfo.LoadFromStream(br); - objInfo.realPos = objInfo.dataPos + dataOffset; - - objects.Add(id, objInfo); - } - - scriptTypeCount = br.ReadInt32(); - scriptTypes = new ScriptType[scriptTypeCount]; - for(int i = 0; i < scriptTypeCount; i++) - { - scriptTypes[i].LoadFromStream(br); - } - - externalsCount = br.ReadInt32(); - externals = new ExternalInfo[externalsCount]; - for(int i = 0; i < externalsCount; i++) - { - externals[i].LoadFromStream(br); - } - -#if UNITY_2019_2_OR_NEWER - refTypeCount = br.ReadInt32(); - refTypes = new ObjectType[refTypeCount]; - for(int i = 0; i < refTypeCount; i++) - { - refTypes[i].LoadFromStream(br); - } -#endif - dummyStr = br.ReadRawString(); - } - - public long SaveToStream(BinaryWriter bw) - { - long startPos = bw.BaseStream.Position; - bw.WriteRawString(version); - bw.Write(platform); - bw.Write(enableTypeTree); - - bw.Write(typeCount); - foreach(var type in types) - type.SaveToStream(bw); - - bw.Write(objectCount); - foreach (var kv in objects) - { - bw.AlignedWriteInt64(kv.Key); - kv.Value.SaveToStream(bw); - } - - bw.Write(scriptTypeCount); - foreach(var st in scriptTypes) - st.SaveToStream(bw); - - bw.Write(externalsCount); - foreach(var external in externals) - external.SaveToStream(bw); - -#if UNITY_2019_2_OR_NEWER - bw.Write(refTypeCount); - foreach(var refT in refTypes) - refT.SaveToStream(bw); -#endif - - bw.WriteRawString(dummyStr); - - return bw.BaseStream.Position - startPos; - } - - public ScriptsData GetScriptData(BinaryReader br) - { - ObjectInfo objInfo = objects[UnityBinFile.kMonoManagerIdx]; - br.BaseStream.Seek(objInfo.realPos, SeekOrigin.Begin); - - ScriptsData data = new ScriptsData(); - data.LoadFromStream(br); - return data; - } - } - - public struct ObjectType - { - public int typeID; - public bool isStriped; - public short scriptTypeIndex; - - public bool needReadScriptHash; // dont save - - public Hash scriptSigHash; - public Hash typeHash; - - public void LoadFromStream(BinaryReader br) - { - typeID = br.ReadInt32(); - isStriped = br.ReadBoolean(); - scriptTypeIndex = br.ReadInt16(); - - needReadScriptHash = typeID == -1 || typeID == 0x72; - if(needReadScriptHash) - scriptSigHash.LoadFromStream(br); - - typeHash.LoadFromStream(br); - - // GlobalManagers does not has TypeTrees - } - - public long SaveToStream(BinaryWriter bw) - { - long startPos = bw.BaseStream.Position; - bw.Write(typeID); - bw.Write(isStriped); - bw.Write(scriptTypeIndex); - - if(needReadScriptHash) - scriptSigHash.SaveToStream(bw); - - typeHash.SaveToStream(bw); - return bw.BaseStream.Position - startPos; - } - - public int Size() - { - int ret = 0; - ret += sizeof(int); - ret += sizeof(bool); - ret += sizeof(short); - - if (needReadScriptHash) - ret += Hash.kSize; - - ret += Hash.kSize; - return ret; - } - } - - public struct ObjectInfo - { - public const int kSize = 12; - - public uint dataPos; - public uint size; - public uint typeID; - - public uint realPos; // dataPos + Header.dataOffset; // dont save - - public void LoadFromStream(BinaryReader br) - { - dataPos = br.ReadUInt32(); - size = br.ReadUInt32(); - typeID = br.ReadUInt32(); - } - - public long SaveToStream(BinaryWriter bw) - { - bw.Write(dataPos); - bw.Write(size); - bw.Write(typeID); - return kSize; - } - } - - public struct ScriptType - { - public int localFileIndex; - public long localIdentifierOfBin; - - public void LoadFromStream(BinaryReader br) - { - localFileIndex = br.ReadInt32(); - localIdentifierOfBin = br.AlignedReadInt64(); - } - - public long SaveToStream(BinaryWriter bw) - { - long startPos = bw.BaseStream.Position; - bw.Write(localFileIndex); - bw.AlignedWriteInt64(localIdentifierOfBin); - return bw.BaseStream.Position - startPos; - } - } - - public struct ExternalInfo - { - public string dummy; - public Hash guid; - public int type; - public string name; - - public void LoadFromStream(BinaryReader br) - { - dummy = br.ReadRawString(); - guid.LoadFromStream(br); - type = br.ReadInt32(); - name = br.ReadRawString(); - } - - public long SaveToStream(BinaryWriter bw) - { - long startPos = bw.BaseStream.Position; - bw.WriteRawString(dummy); - guid.SaveToStream(bw); - bw.Write(type); - bw.WriteRawString(name); - return bw.BaseStream.Position - startPos; - } - } - - public struct ScriptsData - { - public ScriptID[] scriptIDs; - public List dllNames; - public List dllTypes; // 16 is user type - - public void LoadFromStream(BinaryReader br) - { - { - int count = br.ReadInt32(); - scriptIDs = new ScriptID[count]; - for(int i = 0; i < count; i++) - scriptIDs[i].LoadFromStream(br); - } - { - int count = br.ReadInt32(); - dllNames = new List(count); - for (var i = 0; i < count; i++) - dllNames.Add(br.ReadSizeString()); - } - { - int count = br.ReadInt32(); - dllTypes = new List(count); - for(var i = 0; i < count; i++) - dllTypes.Add(br.ReadInt32()); - } - } - - public long SaveToStream(BinaryWriter bw) - { - long startPos = bw.BaseStream.Position; - bw.Write(scriptIDs.Length); - for(int i = 0; i < scriptIDs.Length; i++) - scriptIDs[i].SaveToStream(bw); - - bw.Write(dllNames.Count); - for(int i = 0, imax = dllNames.Count; i < imax; i++) - bw.WriteSizeString(dllNames[i]); - - bw.Write(dllTypes.Count); - for(int i = 0, imax = dllTypes.Count; i < imax; i++) - bw.Write(dllTypes[i]); - - return bw.BaseStream.Position - startPos; - } - } - - public struct ScriptID - { - public int fileID; - public long pathID; // localIdentifier - - public void LoadFromStream(BinaryReader br) - { - fileID = br.ReadInt32(); - pathID = br.ReadInt64(); - } - - public long SaveToStream(BinaryWriter bw) - { - bw.Write(fileID); - bw.Write(pathID); - return 4 + 8; - } - } - - public struct Hash - { - public const int kSize = 16; - - public int[] data; - - public void LoadFromStream(BinaryReader br) - { - data = new int[4]; - for(int i = 0; i < data.Length; i++) - { - data[i] = br.ReadInt32(); - } - } - - public long SaveToStream(BinaryWriter bw) - { - for(int i = 0; i < data.Length; i++) - { - bw.Write(data[i]); - } - return kSize; - } - } -} diff --git a/Editor/3rds/UnityFS/UnityBinFileDefines.cs.meta b/Editor/3rds/UnityFS/UnityBinFileDefines.cs.meta deleted file mode 100644 index 89a829a..0000000 --- a/Editor/3rds/UnityFS/UnityBinFileDefines.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 10655ce82e730324db6ae297f77df04b -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/3rds/UnityFS/UnityBinUtils.cs b/Editor/3rds/UnityFS/UnityBinUtils.cs deleted file mode 100644 index edeefb3..0000000 --- a/Editor/3rds/UnityFS/UnityBinUtils.cs +++ /dev/null @@ -1,78 +0,0 @@ -using System.Collections; -using System.Collections.Generic; -using System.IO; -using UnityEngine; -using System.Text; - -namespace UnityFS -{ - public static class UnityBinUtils - { - public static void SwapUInt(ref uint val) - { - val = (val >> 24) | ((val >> 8) & 0x0000ff00) | ((val << 8) & 0x00ff0000) | (val << 24); - } - - public static string ReadRawString(this BinaryReader br) - { - long startPos = br.BaseStream.Position; - while (true) - { - byte val = br.ReadByte(); - if(val == 0) - break; - } - int size = (int)(br.BaseStream.Position - startPos); - br.BaseStream.Position = startPos; - - byte[] buffer = br.ReadBytes(size); - string ret = Encoding.UTF8.GetString(buffer, 0, size - 1); - - return ret; - } - - public static void WriteRawString(this BinaryWriter bw, string str) - { - byte[] buffer = Encoding.UTF8.GetBytes(str); - bw.Write(buffer, 0, buffer.Length); - bw.Write((byte)0); - } - - public static string ReadSizeString(this BinaryReader br) - { - int size = br.ReadInt32(); - byte[] buff = br.ReadBytes(size); - br.BaseStream.AlignOffset4(); - - string ret = Encoding.UTF8.GetString(buff); - return ret; - } - - public static void WriteSizeString(this BinaryWriter bw, string str) - { - byte[] buff = Encoding.UTF8.GetBytes(str); - bw.Write(buff.Length); - bw.Write(buff, 0, buff.Length); - bw.BaseStream.AlignOffset4(); - } - - public static void AlignOffset4(this Stream stream) - { - int offset = (((int)stream.Position + 3) >> 2) << 2; - stream.Position = offset; - } - - public static long AlignedReadInt64(this BinaryReader br) - { - br.BaseStream.AlignOffset4(); - return br.ReadInt64(); - } - - public static void AlignedWriteInt64(this BinaryWriter bw, long val) - { - bw.BaseStream.AlignOffset4(); - bw.Write(val); - } - } -} - diff --git a/Editor/3rds/UnityFS/UnityBinUtils.cs.meta b/Editor/3rds/UnityFS/UnityBinUtils.cs.meta deleted file mode 100644 index 4be54e7..0000000 --- a/Editor/3rds/UnityFS/UnityBinUtils.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 12a24c30a3914be418be10cfebfa9649 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/3rds/UnityHook/CodePatcher.cs b/Editor/3rds/UnityHook/CodePatcher.cs index 6ec2fa7..3cbb5db 100644 --- a/Editor/3rds/UnityHook/CodePatcher.cs +++ b/Editor/3rds/UnityHook/CodePatcher.cs @@ -1,9 +1,5 @@ using DotNetDetour; using System; -using System.Collections; -using System.Collections.Generic; -using UnityEngine; -using System.Linq; namespace MonoHook { @@ -11,16 +7,16 @@ namespace MonoHook { public bool isValid { get; protected set; } - protected void* _pTarget, _pReplace, _pProxy; - protected int _jmpCodeSize; - protected byte[] _targetHeaderBackup; + protected void* _pTarget, _pReplace, _pProxy; + protected int _jmpCodeSize; + protected byte[] _targetHeaderBackup; public CodePatcher(IntPtr target, IntPtr replace, IntPtr proxy, int jmpCodeSize) { - _pTarget = target.ToPointer(); - _pReplace = replace.ToPointer(); - _pProxy = proxy.ToPointer(); - _jmpCodeSize = jmpCodeSize; + _pTarget = target.ToPointer(); + _pReplace = replace.ToPointer(); + _pProxy = proxy.ToPointer(); + _jmpCodeSize = jmpCodeSize; } public void ApplyPatch() @@ -47,7 +43,7 @@ namespace MonoHook if (_targetHeaderBackup != null) return; - uint requireSize = LDasm.SizeofMinNumByte(_pTarget, _jmpCodeSize); + uint requireSize = LDasm.SizeofMinNumByte(_pTarget, _jmpCodeSize); _targetHeaderBackup = new byte[requireSize]; fixed (void* ptr = _targetHeaderBackup) @@ -76,8 +72,8 @@ namespace MonoHook HookUtils.MemCpy_Jit(_pProxy, _targetHeaderBackup); // jmp to target's new position - long jmpFrom = (long)_pProxy + _targetHeaderBackup.Length; - long jmpTo = (long)_pTarget + _targetHeaderBackup.Length; + long jmpFrom = (long)_pProxy + _targetHeaderBackup.Length; + long jmpTo = (long)_pTarget + _targetHeaderBackup.Length; byte[] buff = GenJmpCode((void*)jmpFrom, (void*)jmpTo); HookUtils.MemCpy_Jit((void*)jmpFrom, buff); @@ -121,7 +117,7 @@ namespace MonoHook byte[] ret = new byte[s_jmpCode.Length]; int val = (int)jmpTo - (int)jmpFrom - 5; - fixed(void * p = &ret[0]) + fixed (void* p = &ret[0]) { byte* ptr = (byte*)p; *ptr = 0xE9; diff --git a/Editor/3rds/UnityHook/HookPool.cs b/Editor/3rds/UnityHook/HookPool.cs index 34a0599..16c9e76 100644 --- a/Editor/3rds/UnityHook/HookPool.cs +++ b/Editor/3rds/UnityHook/HookPool.cs @@ -1,11 +1,7 @@ -using System.Collections; -using System.Collections.Generic; -using System.Reflection; -using UnityEngine; +using System.Collections.Generic; using System.Linq; -using System.IO; +using System.Reflection; #if UNITY_EDITOR -using UnityEditor; #endif namespace MonoHook @@ -60,7 +56,7 @@ namespace MonoHook var list = _hooks.Values.ToList(); foreach (var hook in list) { - if(hook.tag == tag) + if (hook.tag == tag) hook.Uninstall(); } } diff --git a/Editor/3rds/UnityHook/HookUtils.cs b/Editor/3rds/UnityHook/HookUtils.cs index 7a5b8b0..054eff5 100644 --- a/Editor/3rds/UnityHook/HookUtils.cs +++ b/Editor/3rds/UnityHook/HookUtils.cs @@ -15,7 +15,7 @@ namespace MonoHook static DelegateFlushICache flush_icache; private static readonly long _Pagesize; - + static HookUtils() { PropertyInfo p_SystemPageSize = typeof(Environment).GetProperty("SystemPageSize"); @@ -73,9 +73,9 @@ namespace MonoHook public static KeyValuePair 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(startPage, endPage); } @@ -110,7 +110,7 @@ namespace MonoHook count++; } } - END:; + END:; return sb.ToString(); } diff --git a/Editor/3rds/UnityHook/LDasm.cs b/Editor/3rds/UnityHook/LDasm.cs index d87ab91..f533225 100644 --- a/Editor/3rds/UnityHook/LDasm.cs +++ b/Editor/3rds/UnityHook/LDasm.cs @@ -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; } /// @@ -733,14 +733,14 @@ namespace DotNetDetour s = rexw = pr_66 = pr_67 = 0; /* dummy check */ - if ((int)code==0) + if ((int)code == 0) return 0; /* init output data */ //memset(ld, 0, sizeof(ldasm_data)); /* phase 1: parse prefixies */ - while ((cflags(*p) & OP_PREFIX)!=0) + while ((cflags(*p) & OP_PREFIX) != 0) { if (*p == 0x66) pr_66 = 1; @@ -783,19 +783,20 @@ namespace DotNetDetour op = *p++; s++; ld.opcd_size++; f = cflags_ex(op); - if ((f & OP_INVALID)!=0) + if ((f & OP_INVALID) != 0) { ld.flags |= F_INVALID; return s; } /* for SSE instructions */ - if ((f & OP_EXTENDED)!=0) + if ((f & OP_EXTENDED) != 0) { op = *p++; s++; ld.opcd_size++; } } - else { + else + { f = cflags(op); /* pr_66 = pr_67 for opcodes A0-A3 */ if (op >= 0xA0 && op <= 0xA3) @@ -803,7 +804,7 @@ namespace DotNetDetour } /* phase 3: parse ModR/M, SIB and DISP */ - if ((f & OP_MODRM)!=0) + if ((f & OP_MODRM) != 0) { byte mod = (byte)(*p >> 6); byte ro = (byte)((*p & 0x38) >> 3); @@ -819,7 +820,7 @@ namespace DotNetDetour f |= OP_DATA_I16_I32_I64; /* is SIB byte exist? */ - if (mod != 3 && rm == 4 && !(!is64 && pr_67!=0)) + if (mod != 3 && rm == 4 && !(!is64 && pr_67 != 0)) { ld.sib = *p++; s++; ld.flags |= F_SIB; @@ -833,40 +834,41 @@ namespace DotNetDetour switch (mod) { - case 0: + case 0: + if (is64) + { + if (rm == 5) + { + ld.disp_size = 4; if (is64) - { - if (rm == 5) - { - ld.disp_size = 4; - if (is64) - ld.flags |= F_RELATIVE; - } - } - else if (pr_67!=0) - { - if (rm == 6) - ld.disp_size = 2; - } - else { - if (rm == 5) - ld.disp_size = 4; - } - break; - case 1: - ld.disp_size = 1; - break; - case 2: - if (is64) - ld.disp_size = 4; - else if (pr_67!=0) - ld.disp_size = 2; - else - ld.disp_size = 4; - break; + ld.flags |= F_RELATIVE; + } + } + else if (pr_67 != 0) + { + if (rm == 6) + ld.disp_size = 2; + } + else + { + if (rm == 5) + ld.disp_size = 4; + } + break; + case 1: + ld.disp_size = 1; + break; + case 2: + if (is64) + ld.disp_size = 4; + else if (pr_67 != 0) + ld.disp_size = 2; + else + ld.disp_size = 4; + break; } - if (ld.disp_size>0) + if (ld.disp_size > 0) { ld.disp_offset = (byte)(p - (byte*)code); p += ld.disp_size; @@ -876,20 +878,20 @@ namespace DotNetDetour } /* phase 4: parse immediate data */ - if (rexw!=0 && (f & OP_DATA_I16_I32_I64)!=0) + if (rexw != 0 && (f & OP_DATA_I16_I32_I64) != 0) ld.imm_size = 8; - else if ((f & OP_DATA_I16_I32)!=0 || (f & OP_DATA_I16_I32_I64)!=0) + else if ((f & OP_DATA_I16_I32) != 0 || (f & OP_DATA_I16_I32_I64) != 0) ld.imm_size = (byte)(4 - (pr_66 << 1)); /* if exist, add OP_DATA_I16 and OP_DATA_I8 size */ ld.imm_size += (byte)(f & 3); - if ((ld.imm_size)!=0) + if ((ld.imm_size) != 0) { s += ld.imm_size; ld.imm_offset = (byte)(p - (byte*)code); ld.flags |= F_IMM; - if ((f & OP_RELATIVE)!=0) + if ((f & OP_RELATIVE) != 0) ld.flags |= F_RELATIVE; } diff --git a/Editor/3rds/UnityHook/LICENSE b/Editor/3rds/UnityHook/LICENSE new file mode 100644 index 0000000..31bcbd7 --- /dev/null +++ b/Editor/3rds/UnityHook/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Misaka Mikoto + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/Editor/3rds/7zip/Compress.meta b/Editor/3rds/UnityHook/LICENSE.meta similarity index 67% rename from Editor/3rds/7zip/Compress.meta rename to Editor/3rds/UnityHook/LICENSE.meta index b67e6ba..1233d71 100644 --- a/Editor/3rds/7zip/Compress.meta +++ b/Editor/3rds/UnityHook/LICENSE.meta @@ -1,6 +1,5 @@ fileFormatVersion: 2 -guid: 4b6765bf0d03fd243b47d74c9b73c38b -folderAsset: yes +guid: 9298d9b76a5b2074da06bd90eb3bb6fd DefaultImporter: externalObjects: {} userData: diff --git a/Editor/3rds/UnityHook/MethodHook.cs b/Editor/3rds/UnityHook/MethodHook.cs index 2c7c862..d86a1b2 100644 --- a/Editor/3rds/UnityHook/MethodHook.cs +++ b/Editor/3rds/UnityHook/MethodHook.cs @@ -6,15 +6,11 @@ using DotNetDetour; using System; -using System.Diagnostics; using System.Reflection; using System.Runtime.InteropServices; -using Unity.Collections.LowLevel.Unsafe; #if UNITY_EDITOR -using UnityEditor; #endif using UnityEngine; -using System.Runtime.CompilerServices; /* @@ -110,9 +106,9 @@ namespace MonoHook /// 如果还需要调用原始目标方法,可以通过此参数的方法调用,如果不需要可以填 null public MethodHook(MethodBase targetMethod, MethodBase replacementMethod, MethodBase proxyMethod, string data = "") { - this.targetMethod = targetMethod; - this.replacementMethod = replacementMethod; - this.proxyMethod = proxyMethod; + this.targetMethod = targetMethod; + this.replacementMethod = replacementMethod; + this.proxyMethod = proxyMethod; this.tag = data; CheckMethod(); @@ -219,8 +215,8 @@ namespace MonoHook private void CreateCodePatcher() { long addrOffset = Math.Abs(_targetPtr.ToInt64() - _proxyPtr.ToInt64()); - - if(_proxyPtr != IntPtr.Zero) + + if (_proxyPtr != IntPtr.Zero) addrOffset = Math.Max(addrOffset, Math.Abs(_targetPtr.ToInt64() - _proxyPtr.ToInt64())); if (LDasm.IsARM()) @@ -238,7 +234,7 @@ namespace MonoHook { if (IntPtr.Size == 8) { - if(addrOffset < 0x7fffffff) // 2G + if (addrOffset < 0x7fffffff) // 2G _codePatcher = new CodePatcher_x64_near(_targetPtr, _replacementPtr, _proxyPtr); else _codePatcher = new CodePatcher_x64_far(_targetPtr, _replacementPtr, _proxyPtr); @@ -263,7 +259,7 @@ namespace MonoHook if (proxyMethod != null && _proxyPtr == null) return false; - if(_replacementPtr == _targetPtr) + if (_replacementPtr == _targetPtr) { throw new Exception($"the addresses of target method {targetMethod.Name} and replacement method {replacementMethod.Name} can not be same"); } diff --git a/Editor/ABI.meta b/Editor/ABI.meta deleted file mode 100644 index 0557322..0000000 --- a/Editor/ABI.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: d26c8b77c84f09442a05f2c67e5e09b8 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/ABI/ParamInfo.cs b/Editor/ABI/ParamInfo.cs deleted file mode 100644 index fc2cc7f..0000000 --- a/Editor/ABI/ParamInfo.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace HybridCLR.Editor.ABI -{ - - public class ParamInfo - { - public TypeInfo Type { get; set; } - - public int Index { get; set; } - - } - - public class ReturnInfo - { - public TypeInfo Type { get; set; } - - public bool IsVoid => Type.PorType == ParamOrReturnType.VOID; - - public override string ToString() - { - return Type.GetTypeName(); - } - } -} diff --git a/Editor/ABI/ParamOrReturnType.cs b/Editor/ABI/ParamOrReturnType.cs deleted file mode 100644 index f8a478c..0000000 --- a/Editor/ABI/ParamOrReturnType.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace HybridCLR.Editor.ABI -{ - public enum ParamOrReturnType - { - VOID, - I1, - U1, - I2, - U2, - I4, - U4, - I8, - U8, - R4, - R8, - I, - U, - TYPEDBYREF, - STRUCT, - } -} diff --git a/Editor/ABI/PlatformABI.cs b/Editor/ABI/PlatformABI.cs deleted file mode 100644 index 62fdb16..0000000 --- a/Editor/ABI/PlatformABI.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace HybridCLR.Editor.ABI -{ - public enum PlatformABI - { - Universal32, - Universal64, - Arm64, - WebGL32, - } -} diff --git a/Editor/ABI/PlatformABI.cs.meta b/Editor/ABI/PlatformABI.cs.meta deleted file mode 100644 index bea367c..0000000 --- a/Editor/ABI/PlatformABI.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: b9f06ff0612105b4ea20e0309e759e24 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/ABI/TypeCreator.cs b/Editor/ABI/TypeCreator.cs deleted file mode 100644 index 12af7ae..0000000 --- a/Editor/ABI/TypeCreator.cs +++ /dev/null @@ -1,102 +0,0 @@ -using dnlib.DotNet; -using HybridCLR.Editor.Meta; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using UnityEngine; - -namespace HybridCLR.Editor.ABI -{ - public class TypeCreator - { - private readonly Dictionary _typeInfoCache = new Dictionary(TypeEqualityComparer.Instance); - - private int _nextStructId = 0; - - public TypeInfo CreateTypeInfo(TypeSig type) - { - type = type.RemovePinnedAndModifiers(); - if (!_typeInfoCache.TryGetValue(type, out var typeInfo)) - { - typeInfo = CreateTypeInfo0(type); - _typeInfoCache.Add(type, typeInfo); - } - return typeInfo; - } - - TypeInfo CreateTypeInfo0(TypeSig type) - { - type = type.RemovePinnedAndModifiers(); - if (type.IsByRef) - { - return TypeInfo.s_u; - } - switch (type.ElementType) - { - case ElementType.Void: return TypeInfo.s_void; - case ElementType.Boolean: return TypeInfo.s_u1; - case ElementType.I1: return TypeInfo.s_i1; - case ElementType.U1: return TypeInfo.s_u1; - case ElementType.I2: return TypeInfo.s_i2; - case ElementType.Char: - case ElementType.U2: return TypeInfo.s_u2; - case ElementType.I4: return TypeInfo.s_i4; - case ElementType.U4: return TypeInfo.s_u4; - case ElementType.I8: return TypeInfo.s_i8; - case ElementType.U8: return TypeInfo.s_u8; - case ElementType.R4: return TypeInfo.s_r4; - case ElementType.R8: return TypeInfo.s_r8; - case ElementType.I: return TypeInfo.s_i; - case ElementType.U: - case ElementType.String: - case ElementType.Ptr: - case ElementType.ByRef: - case ElementType.Class: - case ElementType.Array: - case ElementType.SZArray: - case ElementType.FnPtr: - case ElementType.Object: - case ElementType.Module: - case ElementType.Var: - case ElementType.MVar: - return TypeInfo.s_u; - case ElementType.TypedByRef: return TypeInfo.s_typedByRef; - case ElementType.ValueType: - { - TypeDef typeDef = type.ToTypeDefOrRef().ResolveTypeDef(); - if (typeDef == null) - { - throw new Exception($"type:{type} definition could not be found. Please try `HybridCLR/Genergate/LinkXml`, then Build once to generate the AOT dll, and then regenerate the bridge function"); - } - if (typeDef.IsEnum) - { - return CreateTypeInfo(typeDef.GetEnumUnderlyingType()); - } - return CreateValueType(type); - } - case ElementType.GenericInst: - { - GenericInstSig gis = (GenericInstSig)type; - if (!gis.GenericType.IsValueType) - { - return TypeInfo.s_u; - } - TypeDef typeDef = gis.GenericType.ToTypeDefOrRef().ResolveTypeDef(); - if (typeDef.IsEnum) - { - return CreateTypeInfo(typeDef.GetEnumUnderlyingType()); - } - return CreateValueType(type); - } - default: throw new NotSupportedException($"{type.ElementType}"); - } - } - - protected TypeInfo CreateValueType(TypeSig type) - { - return new TypeInfo(ParamOrReturnType.STRUCT, type, _nextStructId++); - } - } -} diff --git a/Editor/ABI/TypeInfo.cs b/Editor/ABI/TypeInfo.cs deleted file mode 100644 index 6d0b404..0000000 --- a/Editor/ABI/TypeInfo.cs +++ /dev/null @@ -1,116 +0,0 @@ -using dnlib.DotNet; -using HybridCLR.Editor.Meta; -using System; -using System.Collections.Generic; -using System.Reflection; -using UnityEngine; - -namespace HybridCLR.Editor.ABI -{ - public class TypeInfo : IEquatable - { - - public static readonly TypeInfo s_void = new TypeInfo(ParamOrReturnType.VOID); - public static readonly TypeInfo s_i1 = new TypeInfo(ParamOrReturnType.I1); - public static readonly TypeInfo s_u1 = new TypeInfo(ParamOrReturnType.U1); - public static readonly TypeInfo s_i2 = new TypeInfo(ParamOrReturnType.I2); - public static readonly TypeInfo s_u2 = new TypeInfo(ParamOrReturnType.U2); - public static readonly TypeInfo s_i4 = new TypeInfo(ParamOrReturnType.I4); - public static readonly TypeInfo s_u4 = new TypeInfo(ParamOrReturnType.U4); - public static readonly TypeInfo s_i8 = new TypeInfo(ParamOrReturnType.I8); - public static readonly TypeInfo s_u8 = new TypeInfo(ParamOrReturnType.U8); - public static readonly TypeInfo s_r4 = new TypeInfo(ParamOrReturnType.R4); - public static readonly TypeInfo s_r8 = new TypeInfo(ParamOrReturnType.R8); - public static readonly TypeInfo s_i = new TypeInfo(ParamOrReturnType.I); - public static readonly TypeInfo s_u = new TypeInfo(ParamOrReturnType.U); - public static readonly TypeInfo s_typedByRef = new TypeInfo(ParamOrReturnType.TYPEDBYREF); - - public const string strTypedByRef = "typedbyref"; - - public TypeInfo(ParamOrReturnType portype, TypeSig klass = null, int typeId = 0) - { - PorType = portype; - Klass = klass; - _typeId = typeId; - } - - public ParamOrReturnType PorType { get; } - - public TypeSig Klass { get; } - - public bool IsStruct => PorType == ParamOrReturnType.STRUCT; - - public bool IsPrimitiveType => PorType <= ParamOrReturnType.U; - - private readonly int _typeId; - - public int TypeId => _typeId; - - public bool Equals(TypeInfo other) - { - return PorType == other.PorType && TypeEqualityComparer.Instance.Equals(Klass, other.Klass); - } - - public override bool Equals(object obj) - { - return Equals((TypeInfo)obj); - } - - public override int GetHashCode() - { - return (int)PorType * 23 + (Klass != null ? TypeEqualityComparer.Instance.GetHashCode(Klass) : 0); - } - - public bool NeedExpandValue() - { - return PorType >= ParamOrReturnType.I1 && PorType <= ParamOrReturnType.U2; - } - - public string CreateSigName() - { - switch (PorType) - { - case ParamOrReturnType.VOID: return "v"; - case ParamOrReturnType.I1: return "i1"; - case ParamOrReturnType.U1: return "u1"; - case ParamOrReturnType.I2: return "i2"; - case ParamOrReturnType.U2: return "u2"; - case ParamOrReturnType.I4: return "i4"; - case ParamOrReturnType.U4: return "u4"; - case ParamOrReturnType.I8: return "i8"; - case ParamOrReturnType.U8: return "u8"; - case ParamOrReturnType.R4: return "r4"; - case ParamOrReturnType.R8: return "r8"; - case ParamOrReturnType.I: return "i"; - case ParamOrReturnType.U: return "u"; - case ParamOrReturnType.TYPEDBYREF: return strTypedByRef; - case ParamOrReturnType.STRUCT: return $"s{_typeId}"; - default: throw new NotSupportedException(PorType.ToString()); - }; - } - - public string GetTypeName() - { - switch (PorType) - { - case ParamOrReturnType.VOID: return "void"; - case ParamOrReturnType.I1: return "int8_t"; - case ParamOrReturnType.U1: return "uint8_t"; - case ParamOrReturnType.I2: return "int16_t"; - case ParamOrReturnType.U2: return "uint16_t"; - case ParamOrReturnType.I4: return "int32_t"; - case ParamOrReturnType.U4: return "uint32_t"; - case ParamOrReturnType.I8: return "int64_t"; - case ParamOrReturnType.U8: return "uint64_t"; - case ParamOrReturnType.R4: return "float"; - case ParamOrReturnType.R8: return "double"; - case ParamOrReturnType.I: return "intptr_t"; - case ParamOrReturnType.U: return "uintptr_t"; - case ParamOrReturnType.TYPEDBYREF: return "Il2CppTypedRef"; - case ParamOrReturnType.STRUCT: return $"__struct_{_typeId}__"; - default: throw new NotImplementedException(PorType.ToString()); - }; - } - - } -} diff --git a/Editor/ABI/ValueTypeSizeAligmentCalculator.cs b/Editor/ABI/ValueTypeSizeAligmentCalculator.cs deleted file mode 100644 index a97dd02..0000000 --- a/Editor/ABI/ValueTypeSizeAligmentCalculator.cs +++ /dev/null @@ -1,181 +0,0 @@ -using dnlib.DotNet; -using HybridCLR.Editor.Meta; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Runtime.InteropServices; -using System.Text; -using System.Threading.Tasks; -using UnityEngine; - -namespace HybridCLR.Editor.ABI -{ - public class ValueTypeSizeAligmentCalculator - { - public static ValueTypeSizeAligmentCalculator Caculator64 { get; } = new ValueTypeSizeAligmentCalculator(false); - - public static ValueTypeSizeAligmentCalculator Caculator32 { get; } = new ValueTypeSizeAligmentCalculator(true); - - public ValueTypeSizeAligmentCalculator(bool arch32) - { - _referenceSize = arch32 ? 4 : 8; - } - - private readonly int _referenceSize; - - private static bool IsIgnoreField(FieldDef field) - { - var ignoreAttr = field.CustomAttributes.Where(a => a.AttributeType.FullName == "UnityEngine.Bindings.IgnoreAttribute").FirstOrDefault(); - if (ignoreAttr == null) - { - return false; - } - CANamedArgument arg = ignoreAttr.GetProperty("DoesNotContributeToSize"); - if(arg != null && (bool)arg.Value) - { - //Debug.Log($"IgnoreField.DoesNotContributeToSize = true:{field}"); - return true; - } - return false; - } - - private (int Size, int Aligment) SizeAndAligmentOfStruct(TypeSig type) - { - int totalSize = 0; - int packAligment = 8; - int maxAligment = 1; - - TypeDef typeDef = type.ToTypeDefOrRef().ResolveTypeDefThrow(); - - List 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()); - } - } - } -} diff --git a/Editor/ABI/ValueTypeSizeAligmentCalculator.cs.meta b/Editor/ABI/ValueTypeSizeAligmentCalculator.cs.meta deleted file mode 100644 index 4b83d63..0000000 --- a/Editor/ABI/ValueTypeSizeAligmentCalculator.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: b7af32bdf1cf55c42bfc449820d401cb -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/BuildProcessors/AddLil2cppSourceCodeToXcodeproj2019.cs b/Editor/BuildProcessors/AddLil2cppSourceCodeToXcodeproj2019.cs deleted file mode 100644 index b879aff..0000000 --- a/Editor/BuildProcessors/AddLil2cppSourceCodeToXcodeproj2019.cs +++ /dev/null @@ -1,258 +0,0 @@ -using System; -using HybridCLR.Editor.Installer; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using UnityEditor; -using System.Reflection; -using HybridCLR.Editor.Settings; -#if UNITY_2019 && (UNITY_IOS || UNITY_TVOS) -using UnityEditor.Build; -using UnityEditor.Callbacks; -using UnityEditor.iOS.Xcode; -using UnityEngine; - -namespace HybridCLR.Editor.BuildProcessors -{ - public static class AddLil2cppSourceCodeToXcodeproj2019 - { - [PostProcessBuild] - public static void OnPostProcessBuild(BuildTarget target, string pathToBuiltProject) - { - if (!HybridCLRSettings.Instance.enable) - return; - /* - * 1. 生成lump,并且添加到工程 - 3. 将libil2cpp目录复制到 Library/. 删除旧的. search paths里修改 libil2cpp/include为libil2cpp - 3. Libraries/bdwgc/include -> Libraries/external/bdwgc/include - 4. 将external目录复制到 Library/external。删除旧目录 - 5. 将Library/external/baselib/Platforms/OSX改名为 IOS 全大写 - 6. 将 external/zlib下c 文件添加到工程 - 7. 移除libil2cpp.a - 8. Include path add libil2cpp/os/ClassLibraryPAL/brotli/include - 9. add external/xxHash - 10. add "#include " to Classes/Prefix.pch - */ - - string pbxprojFile = BuildProcessorUtil.GetXcodeProjectFile(pathToBuiltProject); - 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() - { - "-DIL2CPP_MONO_DEBUGGER_DISABLED", - }; - ModifyPBXProject(pathToBuiltProject, pbxprojFile, lumpFiles, extraSources, cflags); - AddSystemHeaderToPrefixPch(pathToBuiltProject); - } - - private static void AddSystemHeaderToPrefixPch(string pathToBuiltProject) - { - // 如果不将 stdio.h 添加到 Prefix.pch, zutil.c会有编译错误 - string prefixPchFile = $"{pathToBuiltProject}/Classes/Prefix.pch"; - string fileContent = File.ReadAllText(prefixPchFile, Encoding.UTF8); - if (!fileContent.Contains("stdio.h")) - { - string newFileContent = fileContent + "\n#include \n"; - File.WriteAllText(prefixPchFile, newFileContent, Encoding.UTF8); - UnityEngine.Debug.Log($"append header to {prefixPchFile}"); - } - } - - private static string GetRelativePathFromProj(string path) - { - return path.Substring(path.IndexOf("Libraries", StringComparison.Ordinal)).Replace('\\', '/'); - } - - private static void ModifyPBXProject(string pathToBuiltProject, string pbxprojFile, List lumpFiles, List extraFiles, List cflags) - { - var proj = new PBXProject(); - proj.ReadFromFile(pbxprojFile); - string targetGUID = proj.GetUnityFrameworkTargetGuid(); - // 移除旧的libil2cpp.a - var libil2cppGUID = proj.FindFileGuidByProjectPath("Libraries/libil2cpp.a"); - if (!string.IsNullOrEmpty(libil2cppGUID)) - { - proj.RemoveFileFromBuild(targetGUID, libil2cppGUID); - proj.RemoveFile(libil2cppGUID); - File.Delete(Path.Combine(pathToBuiltProject, "Libraries", "libil2cpp.a")); - } - - //var lumpGroupGuid = proj.AddFile("Lumps", $"Classes/Lumps", PBXSourceTree.Group); - - foreach (var lumpFile in lumpFiles) - { - string lumpFileName = Path.GetFileName(lumpFile.lumpFile); - string projPathOfFile = $"Classes/Lumps/{lumpFileName}"; - string relativePathOfFile = GetRelativePathFromProj(lumpFile.lumpFile); - string lumpGuid = proj.FindFileGuidByProjectPath(projPathOfFile); - if (!string.IsNullOrEmpty(lumpGuid)) - { - proj.RemoveFileFromBuild(targetGUID, lumpGuid); - proj.RemoveFile(lumpGuid); - } - lumpGuid = proj.AddFile(relativePathOfFile, projPathOfFile, PBXSourceTree.Source); - proj.AddFileToBuild(targetGUID, lumpGuid); - } - - foreach (var extraFile in extraFiles) - { - string projPathOfFile = $"Classes/Extrals/{Path.GetFileName(extraFile)}"; - string extraFileGuid = proj.FindFileGuidByProjectPath(projPathOfFile); - if (!string.IsNullOrEmpty(extraFileGuid)) - { - proj.RemoveFileFromBuild(targetGUID, extraFileGuid); - proj.RemoveFile(extraFileGuid); - //Debug.LogWarning($"remove exist extra file:{projPathOfFile} guid:{extraFileGuid}"); - } - var lumpGuid = proj.AddFile(GetRelativePathFromProj(extraFile), projPathOfFile, PBXSourceTree.Source); - proj.AddFileToBuild(targetGUID, lumpGuid); - } - - foreach(var configName in proj.BuildConfigNames()) - { - //Debug.Log($"build config:{bcn}"); - string configGuid = proj.BuildConfigByName(targetGUID, configName); - string headerSearchPaths = "HEADER_SEARCH_PATHS"; - string hspProp = proj.GetBuildPropertyForConfig(configGuid, headerSearchPaths); - //Debug.Log($"config guid:{configGuid} prop:{hspProp}"); - string newPro = hspProp.Replace("libil2cpp/include", "libil2cpp") - .Replace("Libraries/bdwgc", "Libraries/external/bdwgc"); - - //if (!newPro.Contains("Libraries/libil2cpp/os/ClassLibraryPAL/brotli/include")) - //{ - // newPro += " $(SRCROOT)/Libraries/libil2cpp/os/ClassLibraryPAL/brotli/include"; - //} - if (!newPro.Contains("Libraries/external/xxHash")) - { - newPro += " $(SRCROOT)/Libraries/external/xxHash"; - } - newPro += " $(SRCR00T)/Libraries/external/mono"; - //Debug.Log($"config:{bcn} new prop:{newPro}"); - proj.SetBuildPropertyForConfig(configGuid, headerSearchPaths, newPro); - - string cflagKey = "OTHER_CFLAGS"; - string cfProp = proj.GetBuildPropertyForConfig(configGuid, cflagKey); - foreach (var flag in cflags) - { - if (!cfProp.Contains(flag)) - { - cfProp += " " + flag; - } - } - if (configName.Contains("Debug") && !cfProp.Contains("-DIL2CPP_DEBUG=")) - { - cfProp += " -DIL2CPP_DEBUG=1 -DDEBUG=1"; - } - proj.SetBuildPropertyForConfig(configGuid, cflagKey, cfProp); - - } - proj.WriteToFile(pbxprojFile); - } - - private static void CopyLibil2cppToXcodeProj(string srcLibil2cppDir, string dstLibil2cppDir) - { - BashUtil.RemoveDir(dstLibil2cppDir); - BashUtil.CopyDir(srcLibil2cppDir, dstLibil2cppDir, true); - } - - - private static void CopyExternalToXcodeProj(string srcExternalDir, string dstExternalDir) - { - BashUtil.RemoveDir(dstExternalDir); - BashUtil.CopyDir(srcExternalDir, dstExternalDir, true); - - //string baselibPlatfromsDir = $"{dstExternalDir}/baselib/Platforms"; - //BashUtil.RemoveDir($"{baselibPlatfromsDir}/IOS"); - //BashUtil.CopyDir($"{baselibPlatfromsDir}/OSX", $"{baselibPlatfromsDir}/IOS", true); - } - - class LumpFile - { - public List cppFiles = new List(); - - 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(); - 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 CreateLumps(string libil2cppDir, string outputDir) - { - BashUtil.RecreateDir(outputDir); - - string il2cppConfigFile = $"{libil2cppDir}/il2cpp-config.h"; - var lumpFiles = new List(); - int lumpFileIndex = 0; - foreach (var cppDir in Directory.GetDirectories(libil2cppDir, "*", SearchOption.AllDirectories).Concat(new string[] {libil2cppDir})) - { - var lumpFile = new LumpFile($"{outputDir}/lump_{Path.GetFileName(cppDir)}_{lumpFileIndex}.cpp", il2cppConfigFile); - foreach (var file in Directory.GetFiles(cppDir, "*.cpp", SearchOption.TopDirectoryOnly)) - { - lumpFile.cppFiles.Add(file); - } - lumpFile.SaveFile(); - lumpFiles.Add(lumpFile); - ++lumpFileIndex; - } - - var mmFiles = Directory.GetFiles(libil2cppDir, "*.mm", SearchOption.AllDirectories); - if (mmFiles.Length > 0) - { - var lumpFile = new LumpFile($"{outputDir}/lump_mm.mm", il2cppConfigFile); - foreach (var file in mmFiles) - { - lumpFile.cppFiles.Add(file); - } - lumpFile.SaveFile(); - lumpFiles.Add(lumpFile); - } - return lumpFiles; - } - - private static List GetExtraSourceFiles(string externalDir, string libil2cppDir) - { - var files = new List(); - 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 \ No newline at end of file diff --git a/Editor/BuildProcessors/AddLil2cppSourceCodeToXcodeproj2019.cs.meta b/Editor/BuildProcessors/AddLil2cppSourceCodeToXcodeproj2019.cs.meta deleted file mode 100644 index 64df093..0000000 --- a/Editor/BuildProcessors/AddLil2cppSourceCodeToXcodeproj2019.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: d2f62ca12f2eb4f2fba8e9cb51279421 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/BuildProcessors/AddLil2cppSourceCodeToXcodeproj2020Or2021.cs b/Editor/BuildProcessors/AddLil2cppSourceCodeToXcodeproj2020Or2021.cs deleted file mode 100644 index a7ebc3a..0000000 --- a/Editor/BuildProcessors/AddLil2cppSourceCodeToXcodeproj2020Or2021.cs +++ /dev/null @@ -1,244 +0,0 @@ -using System; -using HybridCLR.Editor.Installer; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using UnityEditor; -using System.Reflection; -using HybridCLR.Editor.Settings; -#if (UNITY_2020 || UNITY_2021) && (UNITY_IOS || UNITY_TVOS) -using UnityEditor.Build; -using UnityEditor.Callbacks; -using UnityEditor.iOS.Xcode; -using UnityEngine; - -namespace HybridCLR.Editor.BuildProcessors -{ - public static class AddLil2cppSourceCodeToXcodeproj2020Or2021 - { - - [PostProcessBuild] - public static void OnPostProcessBuild(BuildTarget target, string pathToBuiltProject) - { - if (!HybridCLRSettings.Instance.enable) - return; - /* - * 1. 生成lump,并且添加到工程 - 3. 将libil2cpp目录复制到 Library/. 删除旧的. search paths里修改 libil2cpp/include为libil2cpp - 3. Libraries/bdwgc/include -> Libraries/external/bdwgc/include - 4. 将external目录复制到 Library/external。删除旧目录 - 5. 将Library/external/baselib/Platforms/OSX改名为 IOS 全大写 - 6. 将 external/zlib下c 文件添加到工程 - 7. 移除libil2cpp.a - 8. Include path add libil2cpp/os/ClassLibraryPAL/brotli/include - 9. add external/xxHash - */ - - string pbxprojFile = BuildProcessorUtil.GetXcodeProjectFile(pathToBuiltProject); - 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() - { - "-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 lumpFiles, List extraFiles, List cflags) - { - var proj = new PBXProject(); - proj.ReadFromFile(pbxprojFile); - string targetGUID = proj.GetUnityFrameworkTargetGuid(); - // 移除旧的libil2cpp.a - var libil2cppGUID = proj.FindFileGuidByProjectPath("Libraries/libil2cpp.a"); - if (!string.IsNullOrEmpty(libil2cppGUID)) - { - proj.RemoveFileFromBuild(targetGUID, libil2cppGUID); - proj.RemoveFile(libil2cppGUID); - File.Delete(Path.Combine(pathToBuiltProject, "Libraries", "libil2cpp.a")); - } - - //var lumpGroupGuid = proj.AddFile("Lumps", $"Classes/Lumps", PBXSourceTree.Group); - - foreach (var lumpFile in lumpFiles) - { - string lumpFileName = Path.GetFileName(lumpFile.lumpFile); - string projPathOfFile = $"Classes/Lumps/{lumpFileName}"; - string relativePathOfFile = GetRelativePathFromProj(lumpFile.lumpFile); - string lumpGuid = proj.FindFileGuidByProjectPath(projPathOfFile); - if (!string.IsNullOrEmpty(lumpGuid)) - { - proj.RemoveFileFromBuild(targetGUID, lumpGuid); - proj.RemoveFile(lumpGuid); - } - lumpGuid = proj.AddFile(relativePathOfFile, projPathOfFile, PBXSourceTree.Source); - proj.AddFileToBuild(targetGUID, lumpGuid); - } - - foreach (var extraFile in extraFiles) - { - string projPathOfFile = $"Classes/Extrals/{Path.GetFileName(extraFile)}"; - string extraFileGuid = proj.FindFileGuidByProjectPath(projPathOfFile); - if (!string.IsNullOrEmpty(extraFileGuid)) - { - proj.RemoveFileFromBuild(targetGUID, extraFileGuid); - proj.RemoveFile(extraFileGuid); - //Debug.LogWarning($"remove exist extra file:{projPathOfFile} guid:{extraFileGuid}"); - } - var lumpGuid = proj.AddFile(GetRelativePathFromProj(extraFile), projPathOfFile, PBXSourceTree.Source); - proj.AddFileToBuild(targetGUID, lumpGuid); - } - - foreach(var configName in proj.BuildConfigNames()) - { - //Debug.Log($"build config:{bcn}"); - string configGuid = proj.BuildConfigByName(targetGUID, configName); - string headerSearchPaths = "HEADER_SEARCH_PATHS"; - string hspProp = proj.GetBuildPropertyForConfig(configGuid, headerSearchPaths); - //Debug.Log($"config guid:{configGuid} prop:{hspProp}"); - string newPro = hspProp.Replace("libil2cpp/include", "libil2cpp") - .Replace("Libraries/bdwgc", "Libraries/external/bdwgc"); - - if (!newPro.Contains("Libraries/libil2cpp/os/ClassLibraryPAL/brotli/include")) - { - newPro += " $(SRCROOT)/Libraries/libil2cpp/os/ClassLibraryPAL/brotli/include"; - } - if (!newPro.Contains("Libraries/external/xxHash")) - { - newPro += " $(SRCROOT)/Libraries/external/xxHash"; - } - newPro += " $(SRCR00T)/Libraries/external/mono"; - //Debug.Log($"config:{bcn} new prop:{newPro}"); - proj.SetBuildPropertyForConfig(configGuid, headerSearchPaths, newPro); - - string cflagKey = "OTHER_CFLAGS"; - string cfProp = proj.GetBuildPropertyForConfig(configGuid, cflagKey); - foreach (var flag in cflags) - { - if (!cfProp.Contains(flag)) - { - cfProp += " " + flag; - } - } - if (configName.Contains("Debug") && !cfProp.Contains("-DIL2CPP_DEBUG=")) - { - cfProp += " -DIL2CPP_DEBUG=1 -DDEBUG=1"; - } - proj.SetBuildPropertyForConfig(configGuid, cflagKey, cfProp); - - } - proj.WriteToFile(pbxprojFile); - } - - private static void CopyLibil2cppToXcodeProj(string srcLibil2cppDir, string dstLibil2cppDir) - { - BashUtil.RemoveDir(dstLibil2cppDir); - BashUtil.CopyDir(srcLibil2cppDir, dstLibil2cppDir, true); - } - - - private static void CopyExternalToXcodeProj(string srcExternalDir, string dstExternalDir) - { - BashUtil.RemoveDir(dstExternalDir); - BashUtil.CopyDir(srcExternalDir, dstExternalDir, true); - - string baselibPlatfromsDir = $"{dstExternalDir}/baselib/Platforms"; - BashUtil.RemoveDir($"{baselibPlatfromsDir}/IOS"); - BashUtil.CopyDir($"{baselibPlatfromsDir}/OSX", $"{baselibPlatfromsDir}/IOS", true); - } - - class LumpFile - { - public List cppFiles = new List(); - - 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(); - 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 CreateLumps(string libil2cppDir, string outputDir) - { - BashUtil.RecreateDir(outputDir); - - string il2cppConfigFile = $"{libil2cppDir}/il2cpp-config.h"; - var lumpFiles = new List(); - int lumpFileIndex = 0; - foreach (var cppDir in Directory.GetDirectories(libil2cppDir, "*", SearchOption.AllDirectories).Concat(new string[] {libil2cppDir})) - { - var lumpFile = new LumpFile($"{outputDir}/lump_{Path.GetFileName(cppDir)}_{lumpFileIndex}.cpp", il2cppConfigFile); - foreach (var file in Directory.GetFiles(cppDir, "*.cpp", SearchOption.TopDirectoryOnly)) - { - lumpFile.cppFiles.Add(file); - } - lumpFile.SaveFile(); - lumpFiles.Add(lumpFile); - ++lumpFileIndex; - } - - var mmFiles = Directory.GetFiles(libil2cppDir, "*.mm", SearchOption.AllDirectories); - if (mmFiles.Length > 0) - { - var lumpFile = new LumpFile($"{outputDir}/lump_mm.mm", il2cppConfigFile); - foreach (var file in mmFiles) - { - lumpFile.cppFiles.Add(file); - } - lumpFile.SaveFile(); - lumpFiles.Add(lumpFile); - } - return lumpFiles; - } - - private static List GetExtraSourceFiles(string externalDir, string libil2cppDir) - { - var files = new List(); - 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 \ No newline at end of file diff --git a/Editor/BuildProcessors/AddLil2cppSourceCodeToXcodeproj2020Or2021.cs.meta b/Editor/BuildProcessors/AddLil2cppSourceCodeToXcodeproj2020Or2021.cs.meta deleted file mode 100644 index 7eba538..0000000 --- a/Editor/BuildProcessors/AddLil2cppSourceCodeToXcodeproj2020Or2021.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 61948fcb1bc40ba47b8c10b0ae801ebb -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/BuildProcessors/AddLil2cppSourceCodeToXcodeproj2022OrNewer.cs b/Editor/BuildProcessors/AddLil2cppSourceCodeToXcodeproj2022OrNewer.cs index 084e388..b875ea9 100644 --- a/Editor/BuildProcessors/AddLil2cppSourceCodeToXcodeproj2022OrNewer.cs +++ b/Editor/BuildProcessors/AddLil2cppSourceCodeToXcodeproj2022OrNewer.cs @@ -1,16 +1,26 @@ -using HybridCLR.Editor.Installer; -using HybridCLR.Editor.Settings; -using System.IO; -using System.Text; -using System.Text.RegularExpressions; -using UnityEditor; -using UnityEditor.Build; -using UnityEditor.Callbacks; -using UnityEngine; +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. #if UNITY_2022 && (UNITY_IOS || UNITY_TVOS || UNITY_VISIONOS) -namespace HybridCLR.Editor.BuildProcessors +namespace HybridCLR.BuildProcessors { public static class AddLil2cppSourceCodeToXcodeproj2022OrNewer { diff --git a/Editor/BuildProcessors/AddLil2cppSourceCodeToXcodeproj2023OrNewer.cs b/Editor/BuildProcessors/AddLil2cppSourceCodeToXcodeproj2023OrNewer.cs index a3c880c..083776f 100644 --- a/Editor/BuildProcessors/AddLil2cppSourceCodeToXcodeproj2023OrNewer.cs +++ b/Editor/BuildProcessors/AddLil2cppSourceCodeToXcodeproj2023OrNewer.cs @@ -1,17 +1,28 @@ -using HybridCLR.Editor.Installer; -using HybridCLR.Editor.Settings; -using System.IO; -using System.Text; -using UnityEditor; -using UnityEditor.Build; -using UnityEditor.Callbacks; -using UnityEngine; +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. #if UNITY_2023_1_OR_NEWER && (UNITY_IOS || UNITY_TVOS || UNITY_VISIONOS) -namespace HybridCLR.Editor.BuildProcessors +namespace HybridCLR.BuildProcessors { - public static class AddLil2cppSourceCodeToXcodeproj2022OrNewer + public static class AddLil2cppSourceCodeToXcodeproj2023OrNewer { [PostProcessBuild] diff --git a/Editor/BuildProcessors/BuildProcessorUtil.cs b/Editor/BuildProcessors/BuildProcessorUtil.cs deleted file mode 100644 index 7bb4f77..0000000 --- a/Editor/BuildProcessors/BuildProcessorUtil.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; -using System.IO; -using UnityEditor.Build; - -namespace HybridCLR.Editor.BuildProcessors -{ - - public static class BuildProcessorUtil - { - - public static string GetXcodeProjectFile(string pathToBuiltProject) - { - foreach (string dir in Directory.GetDirectories(pathToBuiltProject, "*.xcodeproj", SearchOption.TopDirectoryOnly)) - { - string pbxprojFile = $"{dir}/project.pbxproj"; - if (File.Exists(pbxprojFile)) - { - return pbxprojFile; - } - } - throw new BuildFailedException($"can't find xxxx.xcodeproj/project.pbxproj in {pathToBuiltProject}"); - } - } -} - diff --git a/Editor/BuildProcessors/CheckSettings.cs b/Editor/BuildProcessors/CheckSettings.cs index 5a0fe55..11b4593 100644 --- a/Editor/BuildProcessors/CheckSettings.cs +++ b/Editor/BuildProcessors/CheckSettings.cs @@ -1,18 +1,33 @@ -using HybridCLR.Editor.Settings; +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using HybridCLR.Settings; using System; -using System.Collections.Generic; using System.IO; -using System.Linq; -using System.Text; using System.Text.RegularExpressions; -using System.Threading.Tasks; using UnityEditor; using UnityEditor.Build; using UnityEditor.Build.Reporting; using UnityEngine; -using static UnityEngine.GraphicsBuffer; -namespace HybridCLR.Editor.BuildProcessors +namespace HybridCLR.BuildProcessors { internal class CheckSettings : IPreprocessBuildWithReport { @@ -82,7 +97,7 @@ namespace HybridCLR.Editor.BuildProcessors if (!DisableMethodBridgeDevelopmentFlagChecking) { - string methodBridgeFile = $"{SettingsUtil.GeneratedCppDir}/MethodBridge.cpp"; + string methodBridgeFile = $"{SettingsUtil.GeneratedCppDir}/MethodBridge.inc"; var match = Regex.Match(File.ReadAllText(methodBridgeFile), @"// DEVELOPMENT=(\d)"); if (match.Success) { @@ -90,12 +105,12 @@ namespace HybridCLR.Editor.BuildProcessors int developmentFlagInEditorSettings = EditorUserBuildSettings.development ? 1 : 0; if (developmentFlagInMethodBridge != developmentFlagInEditorSettings) { - Debug.LogError($"[CheckSettings] MethodBridge.cpp DEVELOPMENT flag:{developmentFlagInMethodBridge} is inconsistent with EditorUserBuildSettings.development:{developmentFlagInEditorSettings}. Please run 'HybridCLR/Generate/All' before building."); + 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.cpp DEVELOPMENT flag not found. Please run 'HybridCLR/Generate/All' before building."); + Debug.LogError("[CheckSettings] MethodBridge.inc DEVELOPMENT flag not found. Please run 'HybridCLR/Generate/All' before building."); } } } diff --git a/Editor/BuildProcessors/CopyStrippedAOTAssemblies.cs b/Editor/BuildProcessors/CopyStrippedAOTAssemblies.cs index b69d430..93a4a67 100644 --- a/Editor/BuildProcessors/CopyStrippedAOTAssemblies.cs +++ b/Editor/BuildProcessors/CopyStrippedAOTAssemblies.cs @@ -1,25 +1,36 @@ -using HybridCLR.Editor.Installer; -using System; -using System.Collections.Generic; +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using HybridCLR.Utils; using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using UnityEditor; using UnityEditor.Build; using UnityEditor.Build.Reporting; -using UnityEditor.UnityLinker; using UnityEngine; #if !UNITY_2021_1_OR_NEWER using UnityEditor.Il2Cpp; #endif -namespace HybridCLR.Editor.BuildProcessors +namespace HybridCLR.BuildProcessors { internal class CopyStrippedAOTAssemblies : IPostprocessBuildWithReport, IPreprocessBuildWithReport -#if !UNITY_2021_1_OR_NEWER - , IIl2CppProcessor -#endif { public int callbackOrder => 0; @@ -30,24 +41,24 @@ namespace HybridCLR.Editor.BuildProcessors string projectDir = SettingsUtil.ProjectDir; switch (target) { - case BuildTarget.StandaloneWindows: - case BuildTarget.StandaloneWindows64: - return $"{projectDir}/Library/Bee/artifacts/WinPlayerBuildProgram/ManagedStripped"; - case BuildTarget.StandaloneLinux64: - return $"{projectDir}/Library/Bee/artifacts/LinuxPlayerBuildProgram/ManagedStripped"; - case BuildTarget.WSAPlayer: - return $"{projectDir}/Library/Bee/artifacts/UWPPlayerBuildProgram/ManagedStripped"; - case BuildTarget.Android: - return $"{projectDir}/Library/Bee/artifacts/Android/ManagedStripped"; + case BuildTarget.StandaloneWindows: + case BuildTarget.StandaloneWindows64: + return $"{projectDir}/Library/Bee/artifacts/WinPlayerBuildProgram/ManagedStripped"; + case BuildTarget.StandaloneLinux64: + return $"{projectDir}/Library/Bee/artifacts/LinuxPlayerBuildProgram/ManagedStripped"; + case BuildTarget.WSAPlayer: + return $"{projectDir}/Library/Bee/artifacts/UWPPlayerBuildProgram/ManagedStripped"; + case BuildTarget.Android: + return $"{projectDir}/Library/Bee/artifacts/Android/ManagedStripped"; #if TUANJIE_2022_3_OR_NEWER case BuildTarget.HMIAndroid: return $"{projectDir}/Library/Bee/artifacts/HMIAndroid/ManagedStripped"; #endif - case BuildTarget.iOS: + case BuildTarget.iOS: #if UNITY_TVOS case BuildTarget.tvOS: #endif - return $"{projectDir}/Library/Bee/artifacts/iOS/ManagedStripped"; + return $"{projectDir}/Library/Bee/artifacts/iOS/ManagedStripped"; #if UNITY_VISIONOS case BuildTarget.VisionOS: #if UNITY_6000_0_OR_NEWER @@ -56,17 +67,17 @@ namespace HybridCLR.Editor.BuildProcessors return $"{projectDir}/Library/Bee/artifacts/iOS/ManagedStripped"; #endif #endif - case BuildTarget.WebGL: - return $"{projectDir}/Library/Bee/artifacts/WebGL/ManagedStripped"; - case BuildTarget.StandaloneOSX: - return $"{projectDir}/Library/Bee/artifacts/MacStandalonePlayerBuildProgram/ManagedStripped"; - case BuildTarget.PS4: - return $"{projectDir}/Library/Bee/artifacts/PS4PlayerBuildProgram/ManagedStripped"; - case BuildTarget.PS5: - return $"{projectDir}/Library/Bee/artifacts/PS5PlayerBuildProgram/ManagedStripped"; - case BuildTarget.GameCoreXboxOne: - case BuildTarget.GameCoreXboxSeries: - return $"{projectDir}/Library/Bee/artifacts/GameCorePlayerBuildProgram/ManagedStripped"; + case BuildTarget.WebGL: + return $"{projectDir}/Library/Bee/artifacts/WebGL/ManagedStripped"; + case BuildTarget.StandaloneOSX: + return $"{projectDir}/Library/Bee/artifacts/MacStandalonePlayerBuildProgram/ManagedStripped"; + case BuildTarget.PS4: + return $"{projectDir}/Library/Bee/artifacts/PS4PlayerBuildProgram/ManagedStripped"; + case BuildTarget.PS5: + return $"{projectDir}/Library/Bee/artifacts/PS5PlayerBuildProgram/ManagedStripped"; + case BuildTarget.GameCoreXboxOne: + case BuildTarget.GameCoreXboxSeries: + return $"{projectDir}/Library/Bee/artifacts/GameCorePlayerBuildProgram/ManagedStripped"; #if UNITY_WEIXINMINIGAME case BuildTarget.WeixinMiniGame: return $"{projectDir}/Library/Bee/artifacts/WeixinMiniGame/ManagedStripped"; @@ -75,7 +86,7 @@ namespace HybridCLR.Editor.BuildProcessors case BuildTarget.OpenHarmony: return $"{projectDir}/Library/Bee/artifacts/OpenHarmonyPlayerBuildProgram/ManagedStripped"; #endif - default: return ""; + default: return ""; } } #else @@ -131,7 +142,7 @@ namespace HybridCLR.Editor.BuildProcessors { BuildTarget target = report.summary.platform; var dstPath = SettingsUtil.GetAssembliesPostIl2CppStripDir(target); - BashUtil.RecreateDir(dstPath); + DirectoryUtil.RecreateDir(dstPath); } } } diff --git a/Editor/BuildProcessors/FilterHotFixAssemblies.cs b/Editor/BuildProcessors/FilterHotFixAssemblies.cs index 1cb56b6..a71604a 100644 --- a/Editor/BuildProcessors/FilterHotFixAssemblies.cs +++ b/Editor/BuildProcessors/FilterHotFixAssemblies.cs @@ -1,18 +1,37 @@ -using HybridCLR.Editor.Meta; +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + + +using HybridCLR.Utils; using System; using System.Collections.Generic; using System.IO; using System.Linq; -using System.Text; -using System.Threading.Tasks; using UnityEditor; using UnityEditor.Build; using UnityEngine; -namespace HybridCLR.Editor.BuildProcessors +namespace HybridCLR.BuildProcessors { /// - /// 将热更新dll从Build过程中过滤,防止打包到主工程中 + /// Filter hot update assemblies from build process to prevent them from being packaged into the main project /// internal class FilterHotFixAssemblies : IFilterBuildAssemblies { @@ -27,9 +46,8 @@ namespace HybridCLR.Editor.BuildProcessors } List allHotUpdateDllNames = SettingsUtil.HotUpdateAssemblyNamesExcludePreserved; - // 检查是否重复填写 var hotUpdateDllSet = new HashSet(); - foreach(var hotUpdateDll in allHotUpdateDllNames) + foreach (var hotUpdateDll in allHotUpdateDllNames) { if (string.IsNullOrWhiteSpace(hotUpdateDll)) { @@ -42,17 +60,15 @@ namespace HybridCLR.Editor.BuildProcessors } var assResolver = MetaUtil.CreateHotUpdateAssemblyResolver(EditorUserBuildSettings.activeBuildTarget, allHotUpdateDllNames); - // 检查是否填写了正确的dll名称 foreach (var hotUpdateDllName in allHotUpdateDllNames) { - if (assemblies.Select(Path.GetFileNameWithoutExtension).All(ass => ass != hotUpdateDllName) + if (assemblies.Select(Path.GetFileNameWithoutExtension).All(ass => ass != hotUpdateDllName) && string.IsNullOrEmpty(assResolver.ResolveAssembly(hotUpdateDllName, false))) { throw new BuildFailedException($"hot update assembly:{hotUpdateDllName} doesn't exist"); } } - // 将热更dll从打包列表中移除 return assemblies.Where(ass => { string assName = Path.GetFileNameWithoutExtension(ass); diff --git a/Editor/3rds/UnityHook/HybridCLRHooks.meta b/Editor/BuildProcessors/Hooks.meta similarity index 100% rename from Editor/3rds/UnityHook/HybridCLRHooks.meta rename to Editor/BuildProcessors/Hooks.meta diff --git a/Editor/3rds/UnityHook/HybridCLRHooks/CopyStrippedAOTAssembliesHook.cs b/Editor/BuildProcessors/Hooks/CopyStrippedAOTAssembliesHook.cs similarity index 65% rename from Editor/3rds/UnityHook/HybridCLRHooks/CopyStrippedAOTAssembliesHook.cs rename to Editor/BuildProcessors/Hooks/CopyStrippedAOTAssembliesHook.cs index d494552..3a86401 100644 --- a/Editor/3rds/UnityHook/HybridCLRHooks/CopyStrippedAOTAssembliesHook.cs +++ b/Editor/BuildProcessors/Hooks/CopyStrippedAOTAssembliesHook.cs @@ -1,16 +1,34 @@ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Reflection; -using UnityEngine; -using UnityEditor; -using System.Runtime.CompilerServices; -using MonoHook; -using HybridCLR.Editor.BuildProcessors; -using System.IO; +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. -namespace HybridCLR.MonoHook + +using MonoHook; +using System; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using System.Runtime.CompilerServices; +using UnityEditor; +using UnityEngine; + +namespace HybridCLR.BuildProcessors.Hooks { #if UNITY_2021_1_OR_NEWER && !UNITY_2023_1_OR_NEWER [InitializeOnLoad] @@ -43,7 +61,7 @@ namespace HybridCLR.MonoHook return false; } UnityEngine.Debug.Log($"== StripAssembliesTo outputDir:{outputFolder}"); - string outputStrippedDir = HybridCLR.Editor.SettingsUtil.GetAssembliesPostIl2CppStripDir(EditorUserBuildSettings.activeBuildTarget); + string outputStrippedDir = HybridCLR.SettingsUtil.GetAssembliesPostIl2CppStripDir(EditorUserBuildSettings.activeBuildTarget); Directory.CreateDirectory(outputStrippedDir); foreach (var aotDll in Directory.GetFiles(outputFolder, "*.dll")) { diff --git a/Editor/3rds/UnityHook/HybridCLRHooks/CopyStrippedAOTAssembliesHook.cs.meta b/Editor/BuildProcessors/Hooks/CopyStrippedAOTAssembliesHook.cs.meta similarity index 100% rename from Editor/3rds/UnityHook/HybridCLRHooks/CopyStrippedAOTAssembliesHook.cs.meta rename to Editor/BuildProcessors/Hooks/CopyStrippedAOTAssembliesHook.cs.meta diff --git a/Editor/3rds/UnityHook/HybridCLRHooks/GetIl2CppFolderHook.cs b/Editor/BuildProcessors/Hooks/GetIl2CppFolderHook.cs similarity index 60% rename from Editor/3rds/UnityHook/HybridCLRHooks/GetIl2CppFolderHook.cs rename to Editor/BuildProcessors/Hooks/GetIl2CppFolderHook.cs index fbaf8bf..0cb22ea 100644 --- a/Editor/3rds/UnityHook/HybridCLRHooks/GetIl2CppFolderHook.cs +++ b/Editor/BuildProcessors/Hooks/GetIl2CppFolderHook.cs @@ -1,16 +1,32 @@ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Reflection; -using UnityEngine; -using UnityEditor; -using System.Runtime.CompilerServices; -using MonoHook; -using HybridCLR.Editor.BuildProcessors; -using System.IO; +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. -namespace HybridCLR.MonoHook + +using MonoHook; +using System; +using System.Reflection; +using System.Runtime.CompilerServices; +using UnityEditor; +using UnityEngine; + +namespace HybridCLR.BuildProcessors.Hooks { #if UNITY_2022 || UNITY_2023_1_OR_NEWER [InitializeOnLoad] diff --git a/Editor/3rds/UnityHook/HybridCLRHooks/GetIl2CppFolderHook.cs.meta b/Editor/BuildProcessors/Hooks/GetIl2CppFolderHook.cs.meta similarity index 100% rename from Editor/3rds/UnityHook/HybridCLRHooks/GetIl2CppFolderHook.cs.meta rename to Editor/BuildProcessors/Hooks/GetIl2CppFolderHook.cs.meta diff --git a/Editor/3rds/UnityHook/HybridCLRHooks/PatchScriptingAssembliesJsonHook.cs b/Editor/BuildProcessors/Hooks/PatchScriptingAssembliesJsonHook.cs similarity index 61% rename from Editor/3rds/UnityHook/HybridCLRHooks/PatchScriptingAssembliesJsonHook.cs rename to Editor/BuildProcessors/Hooks/PatchScriptingAssembliesJsonHook.cs index c912756..51a3086 100644 --- a/Editor/3rds/UnityHook/HybridCLRHooks/PatchScriptingAssembliesJsonHook.cs +++ b/Editor/BuildProcessors/Hooks/PatchScriptingAssembliesJsonHook.cs @@ -1,16 +1,24 @@ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Reflection; -using UnityEngine; -using UnityEditor; -using System.Runtime.CompilerServices; -using MonoHook; -using HybridCLR.Editor.BuildProcessors; -using System.IO; +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. -namespace HybridCLR.MonoHook +namespace HybridCLR.BuildProcessors.Hooks { #if UNITY_2021_1_OR_NEWER && (UNITY_WEBGL || UNITY_WEIXINMINIGAME) [InitializeOnLoad] @@ -41,7 +49,7 @@ namespace HybridCLR.MonoHook foreach (var tempJsonPath in Directory.GetDirectories(cacheDir, "*", SearchOption.TopDirectoryOnly)) { string dirName = Path.GetFileName(tempJsonPath); - #if UNITY_WEIXINMINIGAME +#if UNITY_WEIXINMINIGAME if (!dirName.Contains("WeixinMiniGame")) { continue; @@ -65,7 +73,7 @@ namespace HybridCLR.MonoHook [MethodImpl(MethodImplOptions.NoOptimization)] private static string BuildMainWindowTitleProxy() { - // 为满足MonoHook要求的最小代码长度而特地加入的无用填充代码, + // Padding added only to satisfy MonoHook minimum code length requirements UnityEngine.Debug.Log(12345.ToString()); return string.Empty; } diff --git a/Editor/3rds/UnityHook/HybridCLRHooks/PatchScriptingAssembliesJsonHook.cs.meta b/Editor/BuildProcessors/Hooks/PatchScriptingAssembliesJsonHook.cs.meta similarity index 100% rename from Editor/3rds/UnityHook/HybridCLRHooks/PatchScriptingAssembliesJsonHook.cs.meta rename to Editor/BuildProcessors/Hooks/PatchScriptingAssembliesJsonHook.cs.meta diff --git a/Editor/BuildProcessors/MsvcStdextWorkaround.cs b/Editor/BuildProcessors/MsvcStdextWorkaround.cs deleted file mode 100644 index f01a4dc..0000000 --- a/Editor/BuildProcessors/MsvcStdextWorkaround.cs +++ /dev/null @@ -1,32 +0,0 @@ -#if UNITY_EDITOR -using System; -using UnityEditor.Build; -using UnityEditor.Build.Reporting; - -namespace HybridCLR.Editor.BuildProcessors -{ - - public class MsvcStdextWorkaround : IPreprocessBuildWithReport - { - const string kWorkaroundFlag = "/D_SILENCE_STDEXT_HASH_DEPRECATION_WARNINGS"; - - public int callbackOrder => 0; - - public void OnPreprocessBuild(BuildReport report) - { - var clEnv = Environment.GetEnvironmentVariable("_CL_"); - - if (string.IsNullOrEmpty(clEnv)) - { - Environment.SetEnvironmentVariable("_CL_", kWorkaroundFlag); - } - else if (!clEnv.Contains(kWorkaroundFlag)) - { - clEnv += " " + kWorkaroundFlag; - Environment.SetEnvironmentVariable("_CL_", clEnv); - } - } - } -} - -#endif // UNITY_EDITOR diff --git a/Editor/BuildProcessors/MsvcStdextWorkaround.cs.meta b/Editor/BuildProcessors/MsvcStdextWorkaround.cs.meta deleted file mode 100644 index ef28c51..0000000 --- a/Editor/BuildProcessors/MsvcStdextWorkaround.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 8bff6cadf0b8db54b87ba51b24d080f6 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/BuildProcessors/PatchScriptingAssemblyList.cs b/Editor/BuildProcessors/PatchScriptingAssemblyList.cs index b376fc5..27f893b 100644 --- a/Editor/BuildProcessors/PatchScriptingAssemblyList.cs +++ b/Editor/BuildProcessors/PatchScriptingAssemblyList.cs @@ -1,22 +1,30 @@ -using HybridCLR.Editor.UnityBinFileReader; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using UnityEditor; +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System.IO; using UnityEditor.Android; using UnityEditor.Build; using UnityEditor.Build.Reporting; -using UnityEditor.UnityLinker; using UnityEngine; -using UnityFS; -#if !UNITY_2023_1_OR_NEWER -using UnityEditor.Il2Cpp; -#endif -namespace HybridCLR.Editor.BuildProcessors +namespace HybridCLR.BuildProcessors { public class PatchScriptingAssemblyList : #if UNITY_ANDROID @@ -25,9 +33,6 @@ namespace HybridCLR.Editor.BuildProcessors UnityEditor.OpenHarmony.IPostGenerateOpenHarmonyProject, #endif IPostprocessBuildWithReport -#if !UNITY_2021_1_OR_NEWER && UNITY_WEBGL - , IIl2CppProcessor -#endif #if UNITY_PS5 , IUnityLinkerProcessor @@ -38,9 +43,9 @@ namespace HybridCLR.Editor.BuildProcessors public void OnPostGenerateGradleAndroidProject(string path) { - // 如果直接打包apk,没有机会在PostprocessBuild中修改ScriptingAssemblies.json。 - // 因此需要在这个时机处理 - // Unity有bug,偶然情况下会传入apk的路径,导致替换失败 + // When building apk directly there is no chance to patch ScriptingAssemblies.json in PostprocessBuild. + // Therefore patch it at this stage + // Unity bug: sometimes an apk path is passed in and replacement fails if (Directory.Exists(path)) { PathScriptingAssembilesFile(path); @@ -62,8 +67,8 @@ namespace HybridCLR.Editor.BuildProcessors public void OnPostprocessBuild(BuildReport report) { - // 如果target为Android,由于已经在OnPostGenerateGradelAndroidProject中处理过, - // 这里不再重复处理 + // For Android targets this was already handled in OnPostGenerateGradleAndroidProject, + // so skip duplicate processing here #if !UNITY_ANDROID && !UNITY_WEBGL && !UNITY_OPENHARMONY PathScriptingAssembilesFile(report.summary.outputPath); #endif @@ -71,7 +76,7 @@ namespace HybridCLR.Editor.BuildProcessors #if UNITY_PS5 /// - /// 打包模式如果是 Package 需要在这个阶段提前处理 .json , PC Hosted 和 GP5 模式不受影响 + /// For Package build mode, patch .json at this stage; PC Hosted and GP5 modes are unaffected /// public string GenerateAdditionalLinkXmlFile(UnityEditor.Build.Reporting.BuildReport report, UnityEditor.UnityLinker.UnityLinkerBuildPipelineData data) @@ -94,26 +99,24 @@ namespace HybridCLR.Editor.BuildProcessors path = Path.GetDirectoryName(path); Debug.Log($"[PatchScriptingAssemblyList] get path parent:{path}"); } -#if UNITY_2020_1_OR_NEWER AddHotFixAssembliesToScriptingAssembliesJson(path); -#else - AddHotFixAssembliesToBinFile(path); -#endif } + private const string scriptingAssembliesJsonFile = "ScriptingAssemblies.json"; + private void AddHotFixAssembliesToScriptingAssembliesJson(string path) { Debug.Log($"[PatchScriptingAssemblyList]. path:{path}"); /* - * ScriptingAssemblies.json 文件中记录了所有的dll名称,此列表在游戏启动时自动加载, - * 不在此列表中的dll在资源反序列化时无法被找到其类型 - * 因此 OnFilterAssemblies 中移除的条目需要再加回来 + * ScriptingAssemblies.json lists all dll names that are loaded automatically at startup; + * dlls missing from this list cannot resolve types during asset deserialization + * therefore entries removed by OnFilterAssemblies must be added back */ - string[] jsonFiles = Directory.GetFiles(path, SettingsUtil.ScriptingAssembliesJsonFile, SearchOption.AllDirectories); + string[] jsonFiles = Directory.GetFiles(path, scriptingAssembliesJsonFile, SearchOption.AllDirectories); if (jsonFiles.Length == 0) { - Debug.LogWarning($"can not find file {SettingsUtil.ScriptingAssembliesJsonFile}"); + Debug.LogWarning($"can not find file {scriptingAssembliesJsonFile}"); return; } @@ -125,65 +128,5 @@ namespace HybridCLR.Editor.BuildProcessors patcher.Save(file); } } - private void AddHotFixAssembliesToBinFile(string path) - { -#if UNITY_STANDALONE_OSX - path = Path.GetDirectoryName(path); -#endif - if (AddHotFixAssembliesToGlobalgamemanagers(path)) - { - return; - } - if (AddHotFixAssembliesTodataunity3d(path)) - { - return; - } - Debug.LogError($"[PatchScriptingAssemblyList] can not find file '{SettingsUtil.GlobalgamemanagersBinFile}' or '{SettingsUtil.Dataunity3dBinFile}' in '{path}'"); - } - - private bool AddHotFixAssembliesToGlobalgamemanagers(string path) - { - string[] binFiles = Directory.GetFiles(path, SettingsUtil.GlobalgamemanagersBinFile, SearchOption.AllDirectories); - - if (binFiles.Length == 0) - { - return false; - } - - foreach (string binPath in binFiles) - { - var binFile = new UnityBinFile(); - binFile.Load(binPath); - binFile.AddScriptingAssemblies(SettingsUtil.HotUpdateAssemblyFilesIncludePreserved); - binFile.Save(binPath); - Debug.Log($"[PatchScriptingAssemblyList] patch {binPath}"); - } - return true; - } - - private bool AddHotFixAssembliesTodataunity3d(string path) - { - string[] binFiles = Directory.GetFiles(path, SettingsUtil.Dataunity3dBinFile, SearchOption.AllDirectories); - - if (binFiles.Length == 0) - { - return false; - } - - foreach (string binPath in binFiles) - { - var patcher = new Dataunity3dPatcher(); - patcher.ApplyPatch(binPath, SettingsUtil.HotUpdateAssemblyFilesIncludePreserved); - Debug.Log($"[PatchScriptingAssemblyList] patch {binPath}"); - } - return true; - } - -#if UNITY_WEBGL && !UNITY_2022_3_OR_NEWER - public void OnBeforeConvertRun(BuildReport report, Il2CppBuildPipelineData data) - { - PathScriptingAssembilesFile($"{SettingsUtil.ProjectDir}/Temp/StagingArea/Data"); - } -#endif } } diff --git a/Editor/BuildProcessors/ScriptingAssembliesJsonPatcher.cs b/Editor/BuildProcessors/ScriptingAssembliesJsonPatcher.cs index a124e34..53b0928 100644 --- a/Editor/BuildProcessors/ScriptingAssembliesJsonPatcher.cs +++ b/Editor/BuildProcessors/ScriptingAssembliesJsonPatcher.cs @@ -1,12 +1,29 @@ +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + using System; using System.Collections.Generic; using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using UnityEngine; -namespace HybridCLR.Editor.BuildProcessors +namespace HybridCLR.BuildProcessors { public class ScriptingAssembliesJsonPatcher { diff --git a/Data~/ModifiedUnityAssemblies/2019.4.40.meta b/Editor/CodeGen.meta similarity index 77% rename from Data~/ModifiedUnityAssemblies/2019.4.40.meta rename to Editor/CodeGen.meta index e7f046c..38ee2fe 100644 --- a/Data~/ModifiedUnityAssemblies/2019.4.40.meta +++ b/Editor/CodeGen.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 1cd43f2247d29084fa2b393c30648e64 +guid: ce487ea0948f9a841a034185c1d536ee folderAsset: yes DefaultImporter: externalObjects: {} diff --git a/Editor/AOT.meta b/Editor/CodeGen/AOT.meta similarity index 100% rename from Editor/AOT.meta rename to Editor/CodeGen/AOT.meta diff --git a/Editor/AOT/AOTAssemblyMetadataStripper.cs b/Editor/CodeGen/AOT/AOTAssemblyMetadataStripper.cs similarity index 62% rename from Editor/AOT/AOTAssemblyMetadataStripper.cs rename to Editor/CodeGen/AOT/AOTAssemblyMetadataStripper.cs index 37c8952..fd966d0 100644 --- a/Editor/AOT/AOTAssemblyMetadataStripper.cs +++ b/Editor/CodeGen/AOT/AOTAssemblyMetadataStripper.cs @@ -1,13 +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 dnlib.DotNet.Writer; -using System; -using System.Collections.Generic; using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace HybridCLR.Editor.AOT +namespace HybridCLR.CodeGen.AOT { public class AOTAssemblyMetadataStripper { @@ -48,7 +63,7 @@ namespace HybridCLR.Editor.AOT { 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} "); + 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); } diff --git a/Editor/AOT/AOTAssemblyMetadataStripper.cs.meta b/Editor/CodeGen/AOT/AOTAssemblyMetadataStripper.cs.meta similarity index 100% rename from Editor/AOT/AOTAssemblyMetadataStripper.cs.meta rename to Editor/CodeGen/AOT/AOTAssemblyMetadataStripper.cs.meta diff --git a/Editor/AOT/GenericReferenceWriter.cs b/Editor/CodeGen/AOT/AOTGenericReferenceWriter.cs similarity index 54% rename from Editor/AOT/GenericReferenceWriter.cs rename to Editor/CodeGen/AOT/AOTGenericReferenceWriter.cs index 1b6021f..38b4943 100644 --- a/Editor/AOT/GenericReferenceWriter.cs +++ b/Editor/CodeGen/AOT/AOTGenericReferenceWriter.cs @@ -1,16 +1,35 @@ -using HybridCLR.Editor.Meta; +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + + +using HybridCLR.CppCodeGen; +using HybridCLR.Meta; using System; using System.Collections.Generic; using System.IO; using System.Linq; -using System.Text; using System.Text.RegularExpressions; -using System.Threading.Tasks; -using UnityEngine; -namespace HybridCLR.Editor.AOT +namespace HybridCLR.CodeGen.AOT { - public class GenericReferenceWriter + public class AOTGenericReferenceWriter { private static readonly Dictionary _typeNameMapping = new Dictionary { @@ -33,13 +52,13 @@ namespace HybridCLR.Editor.AOT private readonly Regex _systemTypePattern; private readonly Regex _genericPattern = new Regex(@"`\d+"); - public GenericReferenceWriter() + public AOTGenericReferenceWriter() { foreach (var e in _typeNameMapping) { _typeSimpleNameMapping.Add(e.Key.FullName, e.Value); } - _systemTypePattern = new Regex(string.Join("|", _typeSimpleNameMapping.Keys.Select (k => $@"\b{Regex.Escape(k)}\b"))); + _systemTypePattern = new Regex(string.Join("|", _typeSimpleNameMapping.Keys.Select(k => $@"\b{Regex.Escape(k)}\b"))); } public string PrettifyTypeSig(string typeSig) @@ -63,47 +82,49 @@ namespace HybridCLR.Editor.AOT string parentDir = Directory.GetParent(outputFile).FullName; Directory.CreateDirectory(parentDir); - List codes = new List(); - codes.Add("using System.Collections.Generic;"); - codes.Add("public class AOTGenericReferences : UnityEngine.MonoBehaviour"); - codes.Add("{"); + var cw = new CodeWriter(); + cw.WriteLine("using System.Collections.Generic;"); + cw.WriteLine("public class AOTGenericReferences : UnityEngine.MonoBehaviour"); + cw.WriteLine("{"); + cw.IncreaseIndent(); - codes.Add(""); - codes.Add("\t// {{ AOT assemblies"); - codes.Add("\tpublic static readonly IReadOnlyList PatchedAOTAssemblyList = new List"); - codes.Add("\t{"); + cw.WriteLine(); + cw.WriteLine("// {{ AOT assemblies"); + cw.WriteLine("public static readonly IReadOnlyList PatchedAOTAssemblyList = new List"); + cw.WriteLine("{"); + cw.IncreaseIndent(); List modules = new HashSet( types.Select(t => t.Type.Module).Concat(methods.Select(m => m.Method.Module))).ToList(); modules.Sort((a, b) => a.Name.CompareTo(b.Name)); foreach (dnlib.DotNet.ModuleDef module in modules) { - codes.Add($"\t\t\"{module.Name}\","); + cw.WriteLine($"\"{module.Name}\","); } - codes.Add("\t};"); - codes.Add("\t// }}"); + cw.DecreaseIndent(); + cw.WriteLine("};"); + cw.WriteLine("// }}"); + cw.WriteLine(); + cw.WriteLine("// {{ constraint implement type"); + cw.WriteLine("// }} "); - codes.Add(""); - codes.Add("\t// {{ constraint implement type"); + cw.WriteLine(); + cw.WriteLine("// {{ AOT generic types"); - codes.Add("\t// }} "); - - codes.Add(""); - codes.Add("\t// {{ AOT generic types"); - List typeNames = types.Select(t => PrettifyTypeSig(t.ToTypeSig().ToString())).ToList(); typeNames.Sort(string.CompareOrdinal); - foreach(var typeName in typeNames) + foreach (var typeName in typeNames) { - codes.Add($"\t// {typeName}"); + cw.WriteLine($"// {typeName}"); } - codes.Add("\t// }}"); + cw.WriteLine("// }}"); + + cw.WriteLine(); + cw.WriteLine("public void RefMethods()"); + cw.WriteLine("{"); + cw.IncreaseIndent(); - codes.Add(""); - codes.Add("\tpublic void RefMethods()"); - codes.Add("\t{"); - List<(string, string, string)> methodTypeAndNames = methods.Select(m => (PrettifyTypeSig(m.Method.DeclaringType.ToString()), PrettifyMethodSig(m.Method.Name), PrettifyMethodSig(m.ToMethodSpec().ToString()))) .ToList(); @@ -122,18 +143,17 @@ namespace HybridCLR.Editor.AOT } return String.Compare(a.Item3, b.Item3, StringComparison.Ordinal); }); - foreach(var method in methodTypeAndNames) + foreach (var method in methodTypeAndNames) { - codes.Add($"\t\t// {PrettifyMethodSig(method.Item3)}"); + cw.WriteLine($"// {PrettifyMethodSig(method.Item3)}"); } - codes.Add("\t}"); + cw.DecreaseIndent(); + cw.WriteLine("}"); - codes.Add("}"); + cw.DecreaseIndent(); + cw.WriteLine("}"); - - var utf8WithoutBom = new System.Text.UTF8Encoding(false); - File.WriteAllText(outputFile, string.Join("\n", codes), utf8WithoutBom); - Debug.Log($"[GenericReferenceWriter] write {outputFile}"); + cw.Save(outputFile); } } } diff --git a/Editor/AOT/GenericReferenceWriter.cs.meta b/Editor/CodeGen/AOT/AOTGenericReferenceWriter.cs.meta similarity index 100% rename from Editor/AOT/GenericReferenceWriter.cs.meta rename to Editor/CodeGen/AOT/AOTGenericReferenceWriter.cs.meta diff --git a/Editor/AOT/Analyzer.cs b/Editor/CodeGen/AOT/AOTReferenceAnalyzer.cs similarity index 85% rename from Editor/AOT/Analyzer.cs rename to Editor/CodeGen/AOT/AOTReferenceAnalyzer.cs index dcd2a87..313f234 100644 --- a/Editor/AOT/Analyzer.cs +++ b/Editor/CodeGen/AOT/AOTReferenceAnalyzer.cs @@ -1,16 +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 dnlib.DotNet; -using HybridCLR.Editor.Meta; -using System; +using HybridCLR.Meta; using System.Collections.Generic; using System.Linq; -using System.Text; -using System.Threading.Tasks; using UnityEngine; -namespace HybridCLR.Editor.AOT +namespace HybridCLR.CodeGen.AOT { - public class Analyzer + public class AOTReferenceAnalyzer { public class Options { @@ -47,7 +64,7 @@ namespace HybridCLR.Editor.AOT public List AotGenericMethods { get; } = new List(); - public Analyzer(Options options) + public AOTReferenceAnalyzer(Options options) { _assemblyCollector = options.Collector; _maxInterationCount = options.MaxIterationCount; @@ -86,7 +103,7 @@ namespace HybridCLR.Editor.AOT private void OnNewMethod(MethodDef methodDef, List klassGenericInst, List methodGenericInst, GenericMethod method) { - if(method == null) + if (method == null) { return; } @@ -150,8 +167,8 @@ namespace HybridCLR.Editor.AOT private void Prepare() { - // 将所有非泛型函数全部加入函数列表,同时立马walk这些method。 - // 后续迭代中将只遍历MethodSpec + // Add all non-generic methods to the list and walk them immediately. + // Later iterations only walk MethodSpec entries foreach (var ass in _assemblyCollector.GetLoadedModulesOfRootAssemblies()) { foreach (TypeDef typeDef in ass.GetTypes()) diff --git a/Editor/AOT/Analyzer.cs.meta b/Editor/CodeGen/AOT/AOTReferenceAnalyzer.cs.meta similarity index 100% rename from Editor/AOT/Analyzer.cs.meta rename to Editor/CodeGen/AOT/AOTReferenceAnalyzer.cs.meta diff --git a/Editor/AOT/ConstraintContext.cs b/Editor/CodeGen/AOT/ConstraintContext.cs similarity index 60% rename from Editor/AOT/ConstraintContext.cs rename to Editor/CodeGen/AOT/ConstraintContext.cs index 4a9cd3c..294399c 100644 --- a/Editor/AOT/ConstraintContext.cs +++ b/Editor/CodeGen/AOT/ConstraintContext.cs @@ -1,12 +1,29 @@ -using dnlib.DotNet; -using HybridCLR.Editor.Meta; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. -namespace HybridCLR.Editor.AOT +using dnlib.DotNet; +using HybridCLR.Meta; +using HybridCLR.Utils; +using System.Collections.Generic; + +namespace HybridCLR.CodeGen.AOT { public class ConstraintContext @@ -43,7 +60,7 @@ namespace HybridCLR.Editor.AOT } private int ComputHash() - { + { int hash = 0; if (BaseType != null) { diff --git a/Editor/AOT/ConstraintContext.cs.meta b/Editor/CodeGen/AOT/ConstraintContext.cs.meta similarity index 100% rename from Editor/AOT/ConstraintContext.cs.meta rename to Editor/CodeGen/AOT/ConstraintContext.cs.meta diff --git a/Editor/CodeGen/CodeWriter.cs b/Editor/CodeGen/CodeWriter.cs new file mode 100644 index 0000000..030db51 --- /dev/null +++ b/Editor/CodeGen/CodeWriter.cs @@ -0,0 +1,94 @@ +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Collections.Generic; +using System.Text; + +namespace HybridCLR.CppCodeGen +{ + public class CodeWriter + { + private readonly List _lines = new List(); + + 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}"); + } + } +} diff --git a/Editor/3rds/7zip/Common/CommandLineParser.cs.meta b/Editor/CodeGen/CodeWriter.cs.meta similarity index 83% rename from Editor/3rds/7zip/Common/CommandLineParser.cs.meta rename to Editor/CodeGen/CodeWriter.cs.meta index a35c292..01800b2 100644 --- a/Editor/3rds/7zip/Common/CommandLineParser.cs.meta +++ b/Editor/CodeGen/CodeWriter.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: dc0b3921c07ef224cb3656391f4317c3 +guid: e721876312c6e1b4997df2e900f1d754 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Editor/Il2CppDef.meta b/Editor/CodeGen/Il2CppDef.meta similarity index 100% rename from Editor/Il2CppDef.meta rename to Editor/CodeGen/Il2CppDef.meta diff --git a/Editor/CodeGen/Il2CppDef/Il2CppDefGenerator.cs b/Editor/CodeGen/Il2CppDef/Il2CppDefGenerator.cs new file mode 100644 index 0000000..cd137ef --- /dev/null +++ b/Editor/CodeGen/Il2CppDef/Il2CppDefGenerator.cs @@ -0,0 +1,99 @@ +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using HybridCLR.CppCodeGen; +using System.Collections.Generic; +using System.IO; +using System.Text.RegularExpressions; +using UnityEngine; + +namespace HybridCLR.CodeGen.Il2CppDef +{ + public class Il2CppDefGenerator + { + public class Options + { + public List 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}"); + } + } +} diff --git a/Editor/Il2CppDef/Il2CppDefGenerator.cs.meta b/Editor/CodeGen/Il2CppDef/Il2CppDefGenerator.cs.meta similarity index 100% rename from Editor/Il2CppDef/Il2CppDefGenerator.cs.meta rename to Editor/CodeGen/Il2CppDef/Il2CppDefGenerator.cs.meta diff --git a/Editor/Link.meta b/Editor/CodeGen/Link.meta similarity index 100% rename from Editor/Link.meta rename to Editor/CodeGen/Link.meta diff --git a/Editor/CodeGen/Link/LinkAnalyzer.cs b/Editor/CodeGen/Link/LinkAnalyzer.cs new file mode 100644 index 0000000..f2ffa9d --- /dev/null +++ b/Editor/CodeGen/Link/LinkAnalyzer.cs @@ -0,0 +1,222 @@ +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using dnlib.DotNet; +using HybridCLR.Mod; +using System; +using System.Collections.Generic; +using UnityEngine; +using IAssemblyResolver = HybridCLR.Mod.IAssemblyResolver; + +namespace HybridCLR.CodeGen.Link +{ + public class LinkAnalyzer + { + private readonly IAssemblyResolver _resolver; + + public LinkAnalyzer(IAssemblyResolver resolver) + { + _resolver = resolver; + } + + public List CollectRefs(List rootAssemblies, LinkPreserveLevel preserveLevel) + { + var assCollector = new AssemblyCache(_resolver); + var rootAssemblyNames = new HashSet(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(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 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 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; + } + } +} diff --git a/Editor/Link/Analyzer.cs.meta b/Editor/CodeGen/Link/LinkAnalyzer.cs.meta similarity index 100% rename from Editor/Link/Analyzer.cs.meta rename to Editor/CodeGen/Link/LinkAnalyzer.cs.meta diff --git a/Editor/CodeGen/Link/LinkPreserveLevel.cs b/Editor/CodeGen/Link/LinkPreserveLevel.cs new file mode 100644 index 0000000..505931c --- /dev/null +++ b/Editor/CodeGen/Link/LinkPreserveLevel.cs @@ -0,0 +1,40 @@ +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +namespace HybridCLR.CodeGen.Link +{ + /// + /// Preserve level used when generating link.xml from hot update assembly references. + /// + public enum LinkPreserveLevel + { + /// + /// Preserve the entire declaring type of each referenced type. + /// Safer against future member usage, but may increase build size. + /// + PreserveAllOfDeclaringType = 0, + + /// + /// Preserve only the exact members referenced by hot update code + /// (fields, methods, properties, events). + /// + PreserveExactMember = 1, + } +} diff --git a/Editor/CodeGen/Link/LinkPreserveLevel.cs.meta b/Editor/CodeGen/Link/LinkPreserveLevel.cs.meta new file mode 100644 index 0000000..abef396 --- /dev/null +++ b/Editor/CodeGen/Link/LinkPreserveLevel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6c7a2b75b4c05e13ab1128274336e1d5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/CodeGen/Link/LinkTypePreserveInfo.cs b/Editor/CodeGen/Link/LinkTypePreserveInfo.cs new file mode 100644 index 0000000..b18f196 --- /dev/null +++ b/Editor/CodeGen/Link/LinkTypePreserveInfo.cs @@ -0,0 +1,43 @@ +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System.Collections.Generic; + +namespace HybridCLR.CodeGen.Link +{ + public class LinkTypePreserveInfo + { + public string AssemblyName { get; set; } + + public string TypeFullName { get; set; } + + public bool PreserveAll { get; set; } + + public SortedSet Fields { get; } = new SortedSet(System.StringComparer.Ordinal); + + public SortedSet Methods { get; } = new SortedSet(System.StringComparer.Ordinal); + + public SortedSet Properties { get; } = new SortedSet(System.StringComparer.Ordinal); + + public SortedSet Events { get; } = new SortedSet(System.StringComparer.Ordinal); + + public bool HasExactMembers => Fields.Count > 0 || Methods.Count > 0 || Properties.Count > 0 || Events.Count > 0; + } +} diff --git a/Editor/CodeGen/Link/LinkTypePreserveInfo.cs.meta b/Editor/CodeGen/Link/LinkTypePreserveInfo.cs.meta new file mode 100644 index 0000000..1bf32f2 --- /dev/null +++ b/Editor/CodeGen/Link/LinkTypePreserveInfo.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 03cdedb09fc930d2f1d79689f124f68c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/CodeGen/Link/LinkXmlWriter.cs b/Editor/CodeGen/Link/LinkXmlWriter.cs new file mode 100644 index 0000000..c505fc4 --- /dev/null +++ b/Editor/CodeGen/Link/LinkXmlWriter.cs @@ -0,0 +1,109 @@ +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using HybridCLR.CppCodeGen; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; + +namespace HybridCLR.CodeGen.Link +{ + public class LinkXmlWriter + { + public void Write(string outputLinkXmlFile, List preserveTypes) + { + string parentDir = Directory.GetParent(outputLinkXmlFile).FullName; + Directory.CreateDirectory(parentDir); + + var cw = new CodeWriter(2); + cw.WriteLine(""); + cw.WriteLine(""); + 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($""); + cw.IncreaseIndent(); + + List 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(""); + } + + cw.DecreaseIndent(); + cw.WriteLine(""); + cw.Save(outputLinkXmlFile); + } + + private static void WriteType(CodeWriter cw, LinkTypePreserveInfo typeInfo) + { + if (typeInfo.PreserveAll) + { + cw.WriteLine($""); + return; + } + + if (!typeInfo.HasExactMembers) + { + cw.WriteLine($""); + return; + } + + cw.WriteLine($""); + cw.IncreaseIndent(); + foreach (var field in typeInfo.Fields) + { + cw.WriteLine($""); + } + foreach (var method in typeInfo.Methods) + { + cw.WriteLine($""); + } + foreach (var property in typeInfo.Properties) + { + cw.WriteLine($""); + } + foreach (var evt in typeInfo.Events) + { + cw.WriteLine($""); + } + cw.DecreaseIndent(); + cw.WriteLine(""); + } + } +} diff --git a/Editor/Link/LinkXmlWriter.cs.meta b/Editor/CodeGen/Link/LinkXmlWriter.cs.meta similarity index 100% rename from Editor/Link/LinkXmlWriter.cs.meta rename to Editor/CodeGen/Link/LinkXmlWriter.cs.meta diff --git a/Editor/MethodBridge.meta b/Editor/CodeGen/MethodBridge.meta similarity index 100% rename from Editor/MethodBridge.meta rename to Editor/CodeGen/MethodBridge.meta diff --git a/Editor/CodeGen/MethodBridge/CallNativeMethodSignatureInfo.cs b/Editor/CodeGen/MethodBridge/CallNativeMethodSignatureInfo.cs new file mode 100644 index 0000000..7e4efd1 --- /dev/null +++ b/Editor/CodeGen/MethodBridge/CallNativeMethodSignatureInfo.cs @@ -0,0 +1,31 @@ +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using dnlib.DotNet; + +namespace HybridCLR.CodeGen.MethodBridge +{ + public class CallNativeMethodSignatureInfo + { + public MethodSig MethodSig { get; set; } + + public CallingConvention? Callvention { get; set; } + } +} diff --git a/Editor/MethodBridge/CallNativeMethodSignatureInfo.cs.meta b/Editor/CodeGen/MethodBridge/CallNativeMethodSignatureInfo.cs.meta similarity index 100% rename from Editor/MethodBridge/CallNativeMethodSignatureInfo.cs.meta rename to Editor/CodeGen/MethodBridge/CallNativeMethodSignatureInfo.cs.meta diff --git a/Editor/MethodBridge/CalliAnalyzer.cs b/Editor/CodeGen/MethodBridge/CalliAnalyzer.cs similarity index 62% rename from Editor/MethodBridge/CalliAnalyzer.cs rename to Editor/CodeGen/MethodBridge/CalliAnalyzer.cs index 14611ac..3fdc23e 100644 --- a/Editor/MethodBridge/CalliAnalyzer.cs +++ b/Editor/CodeGen/MethodBridge/CalliAnalyzer.cs @@ -1,13 +1,29 @@ +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + using dnlib.DotNet; -using HybridCLR.Editor.Meta; -using System; +using HybridCLR.Mod; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using UnityEngine; -namespace HybridCLR.Editor.MethodBridge +namespace HybridCLR.CodeGen.MethodBridge { public class CalliAnalyzer diff --git a/Editor/MethodBridge/CalliAnalyzer.cs.meta b/Editor/CodeGen/MethodBridge/CalliAnalyzer.cs.meta similarity index 100% rename from Editor/MethodBridge/CalliAnalyzer.cs.meta rename to Editor/CodeGen/MethodBridge/CalliAnalyzer.cs.meta diff --git a/Editor/MethodBridge/Generator.cs b/Editor/CodeGen/MethodBridge/Generator.cs similarity index 70% rename from Editor/MethodBridge/Generator.cs rename to Editor/CodeGen/MethodBridge/Generator.cs index 954ad8c..bed76e4 100644 --- a/Editor/MethodBridge/Generator.cs +++ b/Editor/CodeGen/MethodBridge/Generator.cs @@ -1,30 +1,44 @@ +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + using dnlib.DotNet; -using HybridCLR.Editor.ABI; -using HybridCLR.Editor.Meta; -using HybridCLR.Editor.Template; +using HybridCLR.CppCodeGen; +using HybridCLR.Meta; +using HybridCLR.Utils; using System; using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; using System.IO; using System.Linq; -using System.Reflection; +using System.Runtime.InteropServices; using System.Text; -using System.Threading.Tasks; using UnityEditor; using UnityEngine; -using TypeInfo = HybridCLR.Editor.ABI.TypeInfo; using CallingConvention = System.Runtime.InteropServices.CallingConvention; -using TypeAttributes = dnlib.DotNet.TypeAttributes; -using System.Runtime.InteropServices; +using TypeInfo = HybridCLR.Meta.TypeInfo; -namespace HybridCLR.Editor.MethodBridge +namespace HybridCLR.CodeGen.MethodBridge { public class Generator { public class Options { - public string TemplateCode { get; set; } - public string OutputFile { get; set; } public IReadOnlyCollection GenericMethods { get; set; } @@ -62,8 +76,6 @@ namespace HybridCLR.Editor.MethodBridge private readonly List _originalCalliMethodSignatures; - private readonly string _templateCode; - private readonly string _outputFile; private readonly bool _development; @@ -88,7 +100,6 @@ namespace HybridCLR.Editor.MethodBridge _originalReversePInvokeMethods = options.ReversePInvokeMethods; _originalCalliMethodSignatures = options.CalliMethodSignatures.ToList(); - _templateCode = options.TemplateCode; _outputFile = options.OutputFile; _typeCreator = new TypeCreator(); _development = options.Development; @@ -332,61 +343,61 @@ namespace HybridCLR.Editor.MethodBridge } switch (typeSig.ElementType) { - case ElementType.Void: return false; - case ElementType.Boolean: - case ElementType.I1: - case ElementType.U1: - case ElementType.I2: - case ElementType.Char: - case ElementType.U2: - case ElementType.I4: - case ElementType.U4: - case ElementType.I8: - case ElementType.U8: - case ElementType.R4: - case ElementType.R8: - case ElementType.I: - case ElementType.U: - case ElementType.Ptr: - case ElementType.ByRef: - case ElementType.FnPtr: - case ElementType.TypedByRef: return true; - case ElementType.String: - case ElementType.Class: - case ElementType.Array: - case ElementType.SZArray: - case ElementType.Object: - case ElementType.Module: - case ElementType.Var: - case ElementType.MVar: return false; - case ElementType.ValueType: + case ElementType.Void: return false; + case ElementType.Boolean: + case ElementType.I1: + case ElementType.U1: + case ElementType.I2: + case ElementType.Char: + case ElementType.U2: + case ElementType.I4: + case ElementType.U4: + case ElementType.I8: + case ElementType.U8: + case ElementType.R4: + case ElementType.R8: + case ElementType.I: + case ElementType.U: + case ElementType.Ptr: + case ElementType.ByRef: + case ElementType.FnPtr: + case ElementType.TypedByRef: return true; + case ElementType.String: + case ElementType.Class: + case ElementType.Array: + case ElementType.SZArray: + case ElementType.Object: + case ElementType.Module: + case ElementType.Var: + case ElementType.MVar: return false; + case ElementType.ValueType: + { + TypeDef typeDef = typeSig.ToTypeDefOrRef().ResolveTypeDef(); + if (typeDef == null) { - TypeDef typeDef = typeSig.ToTypeDefOrRef().ResolveTypeDef(); - if (typeDef == null) - { - throw new Exception($"type:{typeSig} definition could not be found. Please try `HybridCLR/Genergate/LinkXml`, then Build once to generate the AOT dll, and then regenerate the bridge function"); - } - if (typeDef.IsEnum) - { - return true; - } - return CalculateAnalyzeTypeInfoBasic(GetSharedTypeInfo(typeSig)).blittable; + throw new Exception($"type:{typeSig} definition could not be found. Please try `HybridCLR/Genergate/LinkXml`, then Build once to generate the AOT dll, and then regenerate the bridge function"); } - case ElementType.GenericInst: + if (typeDef.IsEnum) { - GenericInstSig gis = (GenericInstSig)typeSig; - if (!gis.GenericType.IsValueType) - { - return false; - } - TypeDef typeDef = gis.GenericType.ToTypeDefOrRef().ResolveTypeDef(); - if (typeDef.IsEnum) - { - return true; - } - return CalculateAnalyzeTypeInfoBasic(GetSharedTypeInfo(typeSig)).blittable; + return true; } - default: throw new NotSupportedException($"{typeSig.ElementType}"); + return CalculateAnalyzeTypeInfoBasic(GetSharedTypeInfo(typeSig)).blittable; + } + case ElementType.GenericInst: + { + GenericInstSig gis = (GenericInstSig)typeSig; + if (!gis.GenericType.IsValueType) + { + return false; + } + TypeDef typeDef = gis.GenericType.ToTypeDefOrRef().ResolveTypeDef(); + if (typeDef.IsEnum) + { + return true; + } + return CalculateAnalyzeTypeInfoBasic(GetSharedTypeInfo(typeSig)).blittable; + } + default: throw new NotSupportedException($"{typeSig.ElementType}"); } } @@ -415,7 +426,7 @@ namespace HybridCLR.Editor.MethodBridge TypeSig fieldType = ctx != null ? MetaUtil.Inflate(field.FieldType, ctx) : field.FieldType; blittable &= IsBlittable(fieldType); TypeInfo sharedFieldTypeInfo = GetSharedTypeInfo(fieldType); - TypeInfo isoType = ToIsomorphicType(sharedFieldTypeInfo); + TypeInfo isoType = ToIsomorphicType(sharedFieldTypeInfo); fields.Add(new AnalyzeFieldInfo { field = field, type = isoType }); } //analyzeTypeInfo.blittable = blittable; @@ -643,7 +654,7 @@ namespace HybridCLR.Editor.MethodBridge sharedMethod.Init(); sharedMethod = ToIsomorphicMethod(sharedMethod); - CallingConvention callingConv = (CallingConvention)((int)((method.Callvention ?? method.MethodSig.CallingConvention) & dnlib.DotNet.CallingConvention.Mask) + 1); + CallingConvention callingConv = (CallingConvention)((int)((method.Callvention ?? method.MethodSig.CallingConvention) & dnlib.DotNet.CallingConvention.Mask) + 1); string signature = MakeCalliSignature(sharedMethod, callingConv); if (!methodsBySig.TryGetValue(signature, out var arm)) @@ -681,14 +692,11 @@ namespace HybridCLR.Editor.MethodBridge private void GenerateCode() { - var frr = new FileRegionReplace(_templateCode); + var cw = new CodeWriter(); - List lines = new List(20_0000) - { - "\n", - $"// DEVELOPMENT={(_development ? 1 : 0)}", - "\n" - }; + cw.WriteLine(); + cw.WriteLine($"// DEVELOPMENT={(_development ? 1 : 0)}"); + cw.WriteLine(); var classInfos = new List(); var classTypeSet = new Dictionary(); @@ -697,69 +705,65 @@ namespace HybridCLR.Editor.MethodBridge GenerateClassInfo(type, classTypeSet, classInfos); } - GenerateStructDefines(classInfos, lines); + GenerateStructDefines(classInfos, cw); // use structTypes0 to generate signature - GenerateStructureSignatureStub(_structTypes0, lines); + GenerateStructureSignatureStub(_structTypes0, cw); foreach (var method in _managed2NativeMethodList) { - GenerateManaged2NativeMethod(method, lines); + GenerateManaged2NativeMethod(method, cw); } - GenerateManaged2NativeStub(_managed2NativeMethodList, lines); + GenerateManaged2NativeStub(_managed2NativeMethodList, cw); foreach (var method in _native2ManagedMethodList) { - GenerateNative2ManagedMethod(method, lines); + GenerateNative2ManagedMethod(method, cw); } - GenerateNative2ManagedStub(_native2ManagedMethodList, lines); + GenerateNative2ManagedStub(_native2ManagedMethodList, cw); foreach (var method in _adjustThunkMethodList) { - GenerateAdjustThunkMethod(method, lines); + GenerateAdjustThunkMethod(method, cw); } - GenerateAdjustThunkStub(_adjustThunkMethodList, lines); + GenerateAdjustThunkStub(_adjustThunkMethodList, cw); - GenerateReversePInvokeWrappers(_reversePInvokeMethods, lines); + GenerateReversePInvokeWrappers(_reversePInvokeMethods, cw); foreach (var method in _callidMethods) { - GenerateManaged2NativeFunctionPointerMethod(method, lines); + GenerateManaged2NativeFunctionPointerMethod(method, cw); } - GenerateManaged2NativeFunctionPointerMethodStub(_callidMethods, lines); - - - frr.Replace("CODE", string.Join("\n", lines)); + GenerateManaged2NativeFunctionPointerMethodStub(_callidMethods, cw); Directory.CreateDirectory(Path.GetDirectoryName(_outputFile)); - - frr.Commit(_outputFile); + cw.Save(_outputFile); } private static string GetIl2cppCallConventionName(CallingConvention conv) { switch (conv) { - case 0: - case CallingConvention.Winapi: - return "DEFAULT_CALL"; - case CallingConvention.Cdecl: - return "CDECL"; - case CallingConvention.StdCall: - return "STDCALL"; - case CallingConvention.ThisCall: - return "THISCALL"; - case CallingConvention.FastCall: - return "FASTCALL"; - default: - throw new NotSupportedException($"Unsupported CallingConvention {conv}"); + case 0: + case CallingConvention.Winapi: + return "DEFAULT_CALL"; + case CallingConvention.Cdecl: + return "CDECL"; + case CallingConvention.StdCall: + return "STDCALL"; + case CallingConvention.ThisCall: + return "THISCALL"; + case CallingConvention.FastCall: + return "FASTCALL"; + default: + throw new NotSupportedException($"Unsupported CallingConvention {conv}"); } } - private void GenerateReversePInvokeWrappers(List methods, List lines) + private void GenerateReversePInvokeWrappers(List methods, CodeWriter cw) { int methodIndex = 0; var stubCodes = new List(); @@ -773,30 +777,32 @@ namespace HybridCLR.Editor.MethodBridge string methodTypeDef = $"typedef {method.ReturnInfo.Type.GetTypeName()} (*Callback)({paramTypeListWithMethodInfoStr})"; for (int i = 0; i < methodInfo.Count; i++, methodIndex++) { - lines.Add($@" -{method.ReturnInfo.Type.GetTypeName()} {il2cppCallConventionName} __ReversePInvokeMethod_{methodIndex}({paramDeclaringListWithoutMethodInfoStr}) -{{ - il2cpp::vm::ScopedThreadAttacher _vmThreadHelper; - const MethodInfo* method = InterpreterModule::GetMethodInfoByReversePInvokeWrapperIndex({methodIndex}); - {methodTypeDef}; - {(method.ReturnInfo.IsVoid ? "" : "return ")}((Callback)(method->methodPointerCallByInterp))({paramNameListWithoutMethodInfoStr}); -}} - "); - stubCodes.Add($"\t{{\"{methodInfo.Signature}\", (Il2CppMethodPointer)__ReversePInvokeMethod_{methodIndex}}},"); + cw.WriteLine(); + cw.WriteLine($"{method.ReturnInfo.Type.GetTypeName()} {il2cppCallConventionName} __ReversePInvokeMethod_{methodIndex}({paramDeclaringListWithoutMethodInfoStr})"); + cw.WriteLine("{"); + cw.IncreaseIndent(); + cw.WriteLine("il2cpp::vm::ScopedThreadAttacher _vmThreadHelper;"); + cw.WriteLine($"const MethodInfo* method = InterpreterModule::GetMethodInfoByReversePInvokeWrapperIndex({methodIndex});"); + cw.WriteLine($"{methodTypeDef};"); + cw.WriteLine($"{(method.ReturnInfo.IsVoid ? "" : "return ")}((Callback)(method->methodPointerCallByInterp))({paramNameListWithoutMethodInfoStr});"); + cw.DecreaseIndent(); + cw.WriteLine("}"); + stubCodes.Add($"{{\"{methodInfo.Signature}\", (Il2CppMethodPointer)__ReversePInvokeMethod_{methodIndex}}},"); } Debug.Log($"[ReversePInvokeWrap.Generator] method:{method.MethodDef} wrapperCount:{methodInfo.Count}"); } - lines.Add(@" -const ReversePInvokeMethodData hybridclr::interpreter::g_reversePInvokeMethodStub[] -{ -"); - lines.AddRange(stubCodes); - - lines.Add(@" - {nullptr, nullptr}, -}; -"); + cw.WriteLine(); + cw.WriteLine("const ReversePInvokeMethodData hybridclr::interpreter::g_reversePInvokeMethodStub[]"); + cw.WriteLine("{"); + cw.IncreaseIndent(); + foreach (var stub in stubCodes) + { + cw.WriteLine(stub); + } + cw.WriteLine("{nullptr, nullptr},"); + cw.DecreaseIndent(); + cw.WriteLine("};"); } public void Generate() @@ -811,7 +817,7 @@ const ReversePInvokeMethodData hybridclr::interpreter::g_reversePInvokeMethodStu { foreach (var method in methods) { - foreach(var paramInfo in method.ParamInfos) + foreach (var paramInfo in method.ParamInfos) { if (paramInfo.Type.IsStruct) { @@ -821,7 +827,7 @@ const ReversePInvokeMethodData hybridclr::interpreter::g_reversePInvokeMethodStu throw new Exception($"[CollectStructDefs] method:{method.MethodDef} type:{paramInfo.Type.Klass} contains generic parameter"); } } - + } if (method.ReturnInfo.Type.IsStruct) { @@ -832,7 +838,7 @@ const ReversePInvokeMethodData hybridclr::interpreter::g_reversePInvokeMethodStu } } } - + } private void CollectStructDefs(List methods, HashSet structTypes) @@ -940,21 +946,23 @@ const ReversePInvokeMethodData hybridclr::interpreter::g_reversePInvokeMethodStu classInfos.Add(classInfo); } - private void GenerateStructDefines(List classInfos, List lines) + private void GenerateStructDefines(List classInfos, CodeWriter cw) { foreach (var ci in classInfos) { - lines.Add($"// {ci.type.Klass}"); + cw.WriteLine($"// {ci.type.Klass}"); uint packingSize = ci.packingSize; uint classSize = ci.classSize; - + if (ci.layout == LayoutKind.Explicit) { - lines.Add($"struct {ci.type.GetTypeName()} {{"); - lines.Add("\tunion {"); + cw.WriteLine($"struct {ci.type.GetTypeName()} {{"); + cw.IncreaseIndent(); + cw.WriteLine("union {"); + cw.IncreaseIndent(); if (classSize > 0) { - lines.Add($"\tstruct {{ char __fieldSize_offsetPadding[{classSize}];}};"); + cw.WriteLine($"struct {{ char __fieldSize_offsetPadding[{classSize}];}};"); } int index = 0; foreach (var field in ci.fields) @@ -962,51 +970,57 @@ const ReversePInvokeMethodData hybridclr::interpreter::g_reversePInvokeMethodStu uint offset = field.field.FieldOffset.Value; string fieldName = $"__{index}"; string commentFieldName = $"{field.field.Name}"; - lines.Add("\t#pragma pack(push, 1)"); - lines.Add($"\tstruct {{ {(offset > 0 ? $"char {fieldName}_offsetPadding[{offset}]; " : "")}{field.type.GetTypeName()} {fieldName};}}; // {commentFieldName}"); - lines.Add($"\t#pragma pack(pop)"); + cw.WriteLine("#pragma pack(push, 1)"); + cw.WriteLine($"struct {{ {(offset > 0 ? $"char {fieldName}_offsetPadding[{offset}]; " : "")}{field.type.GetTypeName()} {fieldName};}}; // {commentFieldName}"); + cw.WriteLine("#pragma pack(pop)"); if (packingSize > 0) { - lines.Add($"\t#pragma pack(push, {packingSize})"); + cw.WriteLine($"#pragma pack(push, {packingSize})"); } - lines.Add($"\tstruct {{ {(offset > 0 ? $"char {fieldName}_offsetPadding_forAlignmentOnly[{offset}]; " : "")}{field.type.GetTypeName()} {fieldName}_forAlignmentOnly;}}; // {commentFieldName}"); + cw.WriteLine($"struct {{ {(offset > 0 ? $"char {fieldName}_offsetPadding_forAlignmentOnly[{offset}]; " : "")}{field.type.GetTypeName()} {fieldName}_forAlignmentOnly;}}; // {commentFieldName}"); if (packingSize > 0) { - lines.Add($"\t#pragma pack(pop)"); + cw.WriteLine("#pragma pack(pop)"); } ++index; } - lines.Add("\t};"); - lines.Add("};"); + cw.DecreaseIndent(); + cw.WriteLine("};"); + cw.DecreaseIndent(); + cw.WriteLine("};"); } else { if (packingSize != 0) { - lines.Add($"#pragma pack(push, {packingSize})"); + cw.WriteLine($"#pragma pack(push, {packingSize})"); } - lines.Add($"{(classSize > 0 ? "union" : "struct")} {ci.type.GetTypeName()} {{"); + cw.WriteLine($"{(classSize > 0 ? "union" : "struct")} {ci.type.GetTypeName()} {{"); + cw.IncreaseIndent(); if (classSize > 0) { - lines.Add($"\tstruct {{ char __fieldSize_offsetPadding[{classSize}];}};"); - lines.Add("\tstruct {"); + cw.WriteLine($"struct {{ char __fieldSize_offsetPadding[{classSize}];}};"); + cw.WriteLine("struct {"); + cw.IncreaseIndent(); } int index = 0; foreach (var field in ci.fields) { string fieldName = $"__{index}"; string commentFieldName = $"{field.field.Name}"; - lines.Add($"\t{field.type.GetTypeName()} {fieldName}; // {commentFieldName}"); + cw.WriteLine($"{field.type.GetTypeName()} {fieldName}; // {commentFieldName}"); ++index; } if (classSize > 0) { - lines.Add("\t};"); + cw.DecreaseIndent(); + cw.WriteLine("};"); } - lines.Add("};"); + cw.DecreaseIndent(); + cw.WriteLine("};"); if (packingSize != 0) { - lines.Add($"#pragma pack(pop)"); + cw.WriteLine("#pragma pack(pop)"); } } } @@ -1019,63 +1033,63 @@ const ReversePInvokeMethodData hybridclr::interpreter::g_reversePInvokeMethodStu type = type.RemovePinnedAndModifiers(); switch (type.ElementType) { - case ElementType.Void: return "v"; - case ElementType.Boolean: return "u1"; - case ElementType.I1: return "i1"; - case ElementType.U1: return "u1"; - case ElementType.I2: return "i2"; - case ElementType.Char: - case ElementType.U2: return "u2"; - case ElementType.I4: return "i4"; - case ElementType.U4: return "u4"; - case ElementType.I8: return "i8"; - case ElementType.U8: return "u8"; - case ElementType.R4: return "r4"; - case ElementType.R8: return "r8"; - case ElementType.I: return "i"; - case ElementType.U: - case ElementType.String: - case ElementType.Ptr: - case ElementType.ByRef: - case ElementType.Class: - case ElementType.Array: - case ElementType.SZArray: - case ElementType.FnPtr: - case ElementType.Object: - return SigOfObj; - case ElementType.Module: - case ElementType.Var: - case ElementType.MVar: - throw new NotSupportedException($"ToFullName type:{type}"); - case ElementType.TypedByRef: return TypeInfo.strTypedByRef; - case ElementType.ValueType: + case ElementType.Void: return "v"; + case ElementType.Boolean: return "u1"; + case ElementType.I1: return "i1"; + case ElementType.U1: return "u1"; + case ElementType.I2: return "i2"; + case ElementType.Char: + case ElementType.U2: return "u2"; + case ElementType.I4: return "i4"; + case ElementType.U4: return "u4"; + case ElementType.I8: return "i8"; + case ElementType.U8: return "u8"; + case ElementType.R4: return "r4"; + case ElementType.R8: return "r8"; + case ElementType.I: return "i"; + case ElementType.U: + case ElementType.String: + case ElementType.Ptr: + case ElementType.ByRef: + case ElementType.Class: + case ElementType.Array: + case ElementType.SZArray: + case ElementType.FnPtr: + case ElementType.Object: + return SigOfObj; + case ElementType.Module: + case ElementType.Var: + case ElementType.MVar: + throw new NotSupportedException($"ToFullName type:{type}"); + case ElementType.TypedByRef: return TypeInfo.strTypedByRef; + case ElementType.ValueType: + { + TypeDef typeDef = type.ToTypeDefOrRef().ResolveTypeDef(); + if (typeDef == null) { - TypeDef typeDef = type.ToTypeDefOrRef().ResolveTypeDef(); - if (typeDef == null) - { - throw new Exception($"type:{type} definition could not be found. Please try `HybridCLR/Genergate/LinkXml`, then Build once to generate the AOT dll, and then regenerate the bridge function"); - } - if (typeDef.IsEnum) - { - return ToFullName(typeDef.GetEnumUnderlyingType()); - } - return ToValueTypeFullName((ClassOrValueTypeSig)type); + throw new Exception($"type:{type} definition could not be found. Please try `HybridCLR/Genergate/LinkXml`, then Build once to generate the AOT dll, and then regenerate the bridge function"); } - case ElementType.GenericInst: - { - GenericInstSig gis = (GenericInstSig)type; - if (!gis.GenericType.IsValueType) - { - return SigOfObj; - } - TypeDef typeDef = gis.GenericType.ToTypeDefOrRef().ResolveTypeDef(); - if (typeDef.IsEnum) - { - return ToFullName(typeDef.GetEnumUnderlyingType()); - } - return $"{ToValueTypeFullName(gis.GenericType)}<{string.Join(",", gis.GenericArguments.Select(a => ToFullName(a)))}>"; - } - default: throw new NotSupportedException($"{type.ElementType}"); + if (typeDef.IsEnum) + { + return ToFullName(typeDef.GetEnumUnderlyingType()); + } + return ToValueTypeFullName((ClassOrValueTypeSig)type); + } + case ElementType.GenericInst: + { + GenericInstSig gis = (GenericInstSig)type; + if (!gis.GenericType.IsValueType) + { + return SigOfObj; + } + TypeDef typeDef = gis.GenericType.ToTypeDefOrRef().ResolveTypeDef(); + if (typeDef.IsEnum) + { + return ToFullName(typeDef.GetEnumUnderlyingType()); + } + return $"{ToValueTypeFullName(gis.GenericType)}<{string.Join(",", gis.GenericArguments.Select(a => ToFullName(a)))}>"; + } + default: throw new NotSupportedException($"{type.ElementType}"); } } @@ -1109,64 +1123,69 @@ const ReversePInvokeMethodData hybridclr::interpreter::g_reversePInvokeMethodStu return $"{Path.GetFileNameWithoutExtension(typeDef.Module.Name)}:{typeDef.FullName}"; } - private void GenerateStructureSignatureStub(List types, List lines) + private void GenerateStructureSignatureStub(List types, CodeWriter cw) { - lines.Add("const FullName2Signature hybridclr::interpreter::g_fullName2SignatureStub[] = {"); + cw.WriteLine("const FullName2Signature hybridclr::interpreter::g_fullName2SignatureStub[] = {"); + cw.IncreaseIndent(); foreach (var type in types) { TypeInfo isoType = ToIsomorphicType(type); - lines.Add($"\t{{\"{ToFullName(type.Klass)}\", \"{isoType.CreateSigName()}\"}},"); + cw.WriteLine($"{{\"{ToFullName(type.Klass)}\", \"{isoType.CreateSigName()}\"}},"); } - lines.Add("\t{ nullptr, nullptr},"); - lines.Add("};"); + cw.WriteLine("{ nullptr, nullptr},"); + cw.DecreaseIndent(); + cw.WriteLine("};"); } - private void GenerateManaged2NativeStub(List methods, List lines) + private void GenerateManaged2NativeStub(List methods, CodeWriter cw) { - lines.Add($@" -const Managed2NativeMethodInfo hybridclr::interpreter::g_managed2nativeStub[] = -{{ -"); + cw.WriteLine(); + cw.WriteLine("const Managed2NativeMethodInfo hybridclr::interpreter::g_managed2nativeStub[] = "); + cw.WriteLine("{"); + cw.IncreaseIndent(); foreach (var method in methods) { - lines.Add($"\t{{\"{method.CreateInvokeSigName()}\", __M2N_{method.CreateInvokeSigName()}}},"); + cw.WriteLine($"{{\"{method.CreateInvokeSigName()}\", __M2N_{method.CreateInvokeSigName()}}},"); } - lines.Add($"\t{{nullptr, nullptr}},"); - lines.Add("};"); + cw.WriteLine("{nullptr, nullptr},"); + cw.DecreaseIndent(); + cw.WriteLine("};"); } - private void GenerateNative2ManagedStub(List methods, List lines) + private void GenerateNative2ManagedStub(List methods, CodeWriter cw) { - lines.Add($@" -const Native2ManagedMethodInfo hybridclr::interpreter::g_native2managedStub[] = -{{ -"); + cw.WriteLine(); + cw.WriteLine("const Native2ManagedMethodInfo hybridclr::interpreter::g_native2managedStub[] = "); + cw.WriteLine("{"); + cw.IncreaseIndent(); foreach (var method in methods) { - lines.Add($"\t{{\"{method.CreateInvokeSigName()}\", (Il2CppMethodPointer)__N2M_{method.CreateInvokeSigName()}}},"); + cw.WriteLine($"{{\"{method.CreateInvokeSigName()}\", (Il2CppMethodPointer)__N2M_{method.CreateInvokeSigName()}}},"); } - lines.Add($"\t{{nullptr, nullptr}},"); - lines.Add("};"); + cw.WriteLine("{nullptr, nullptr},"); + cw.DecreaseIndent(); + cw.WriteLine("};"); } - private void GenerateAdjustThunkStub(List methods, List lines) + private void GenerateAdjustThunkStub(List methods, CodeWriter cw) { - lines.Add($@" -const NativeAdjustThunkMethodInfo hybridclr::interpreter::g_adjustThunkStub[] = -{{ -"); + cw.WriteLine(); + cw.WriteLine("const NativeAdjustThunkMethodInfo hybridclr::interpreter::g_adjustThunkStub[] = "); + cw.WriteLine("{"); + cw.IncreaseIndent(); foreach (var method in methods) { - lines.Add($"\t{{\"{method.CreateInvokeSigName()}\", (Il2CppMethodPointer)__N2M_AdjustorThunk_{method.CreateCallSigName()}}},"); + cw.WriteLine($"{{\"{method.CreateInvokeSigName()}\", (Il2CppMethodPointer)__N2M_AdjustorThunk_{method.CreateCallSigName()}}},"); } - lines.Add($"\t{{nullptr, nullptr}},"); - lines.Add("};"); + cw.WriteLine("{nullptr, nullptr},"); + cw.DecreaseIndent(); + cw.WriteLine("};"); } private string GetManaged2NativePassParam(TypeInfo type, string varName) @@ -1179,37 +1198,35 @@ const NativeAdjustThunkMethodInfo hybridclr::interpreter::g_adjustThunkStub[] = return type.NeedExpandValue() ? $"(uint64_t)({varName})" : $"N2MAsUint64ValueOrAddress<{type.GetTypeName()}>({varName})"; } - private void GenerateManaged2NativeMethod(MethodDesc method, List lines) + private void GenerateManaged2NativeMethod(MethodDesc method, CodeWriter cw) { string paramListStr = string.Join(", ", method.ParamInfos.Select(p => $"{p.Type.GetTypeName()} __arg{p.Index}").Concat(new string[] { "const MethodInfo* method" })); string paramNameListStr = string.Join(", ", method.ParamInfos.Select(p => GetManaged2NativePassParam(p.Type, $"localVarBase+argVarIndexs[{p.Index}]")).Concat(new string[] { "method" })); - lines.Add($@" -static void __M2N_{method.CreateCallSigName()}(const MethodInfo* method, uint16_t* argVarIndexs, StackObject* localVarBase, void* ret) -{{ - typedef {method.ReturnInfo.Type.GetTypeName()} (*NativeMethod)({paramListStr}); - {(!method.ReturnInfo.IsVoid ? $"*({method.ReturnInfo.Type.GetTypeName()}*)ret = " : "")}((NativeMethod)(method->methodPointerCallByInterp))({paramNameListStr}); -}} -"); + cw.WriteLine(); + cw.WriteLine($"static void __M2N_{method.CreateCallSigName()}(const MethodInfo* method, uint16_t* argVarIndexs, StackObject* localVarBase, void* ret)"); + cw.WriteLine("{"); + cw.IncreaseIndent(); + cw.WriteLine($"typedef {method.ReturnInfo.Type.GetTypeName()} (*NativeMethod)({paramListStr});"); + cw.WriteLine($"{(!method.ReturnInfo.IsVoid ? $"*({method.ReturnInfo.Type.GetTypeName()}*)ret = " : "")}((NativeMethod)(method->methodPointerCallByInterp))({paramNameListStr});"); + cw.DecreaseIndent(); + cw.WriteLine("}"); } - private string GenerateArgumentSizeAndOffset(List paramInfos) + private void WriteArgumentSizeAndOffset(List paramInfos, CodeWriter cw) { - StringBuilder s = new StringBuilder(); int index = 0; foreach (var param in paramInfos) { - s.AppendLine($"\tconstexpr int __ARG_OFFSET_{index}__ = {(index > 0 ? $"__ARG_OFFSET_{index - 1}__ + __ARG_SIZE_{index-1}__" : "0")};"); - s.AppendLine($"\tconstexpr int __ARG_SIZE_{index}__ = (sizeof(__arg{index}) + 7)/8;"); + cw.WriteLine($"constexpr int __ARG_OFFSET_{index}__ = {(index > 0 ? $"__ARG_OFFSET_{index - 1}__ + __ARG_SIZE_{index - 1}__" : "0")};"); + cw.WriteLine($"constexpr int __ARG_SIZE_{index}__ = (sizeof(__arg{index}) + 7)/8;"); index++; } - s.AppendLine($"\tconstexpr int __TOTAL_ARG_SIZE__ = {(paramInfos.Count > 0 ? $"__ARG_OFFSET_{index-1}__ + __ARG_SIZE_{index-1}__" : "1")};"); - return s.ToString(); + cw.WriteLine($"constexpr int __TOTAL_ARG_SIZE__ = {(paramInfos.Count > 0 ? $"__ARG_OFFSET_{index - 1}__ + __ARG_SIZE_{index - 1}__" : "1")};"); } - private string GenerateCopyArgumentToInterpreterStack(List paramInfos) + private void WriteCopyArgumentToInterpreterStack(List paramInfos, CodeWriter cw) { - StringBuilder s = new StringBuilder(); int index = 0; foreach (var param in paramInfos) { @@ -1217,77 +1234,88 @@ static void __M2N_{method.CreateCallSigName()}(const MethodInfo* method, uint16_ { if (param.Type.NeedExpandValue()) { - s.AppendLine($"\targs[__ARG_OFFSET_{index}__].u64 = __arg{index};"); + cw.WriteLine($"args[__ARG_OFFSET_{index}__].u64 = __arg{index};"); } else { - s.AppendLine($"\t*({param.Type.GetTypeName()}*)(args + __ARG_OFFSET_{index}__) = __arg{index};"); + cw.WriteLine($"*({param.Type.GetTypeName()}*)(args + __ARG_OFFSET_{index}__) = __arg{index};"); } } else { - s.AppendLine($"\t*({param.Type.GetTypeName()}*)(args + __ARG_OFFSET_{index}__) = __arg{index};"); + cw.WriteLine($"*({param.Type.GetTypeName()}*)(args + __ARG_OFFSET_{index}__) = __arg{index};"); } index++; } - return s.ToString(); } - private void GenerateNative2ManagedMethod0(MethodDesc method, bool adjustorThunk, List lines) + private void GenerateNative2ManagedMethod0(MethodDesc method, bool adjustorThunk, CodeWriter cw) { string paramListStr = string.Join(", ", method.ParamInfos.Select(p => $"{p.Type.GetTypeName()} __arg{p.Index}").Concat(new string[] { "const MethodInfo* method" })); - lines.Add($@" -static {method.ReturnInfo.Type.GetTypeName()} __N2M_{(adjustorThunk ? "AdjustorThunk_" : "")}{method.CreateCallSigName()}({paramListStr}) -{{ - {(adjustorThunk ? "__arg0 += sizeof(Il2CppObject);" : "")} -{GenerateArgumentSizeAndOffset(method.ParamInfos)} - StackObject args[__TOTAL_ARG_SIZE__]; -{GenerateCopyArgumentToInterpreterStack(method.ParamInfos)} - {(method.ReturnInfo.IsVoid ? "Interpreter::Execute(method, args, nullptr);" : $"{method.ReturnInfo.Type.GetTypeName()} ret; Interpreter::Execute(method, args, &ret); return ret;")} -}} -"); + cw.WriteLine(); + cw.WriteLine($"static {method.ReturnInfo.Type.GetTypeName()} __N2M_{(adjustorThunk ? "AdjustorThunk_" : "")}{method.CreateCallSigName()}({paramListStr})"); + cw.WriteLine("{"); + cw.IncreaseIndent(); + if (adjustorThunk) + { + cw.WriteLine("__arg0 += sizeof(Il2CppObject);"); + } + WriteArgumentSizeAndOffset(method.ParamInfos, cw); + cw.WriteLine(); + cw.WriteLine("StackObject args[__TOTAL_ARG_SIZE__];"); + WriteCopyArgumentToInterpreterStack(method.ParamInfos, cw); + cw.WriteLine(); + if (method.ReturnInfo.IsVoid) + { + cw.WriteLine("Interpreter::Execute(method, args, nullptr);"); + } + else + { + cw.WriteLine($"{method.ReturnInfo.Type.GetTypeName()} ret; Interpreter::Execute(method, args, &ret); return ret;"); + } + cw.DecreaseIndent(); + cw.WriteLine("}"); } - private void GenerateNative2ManagedMethod(MethodDesc method, List lines) + private void GenerateNative2ManagedMethod(MethodDesc method, CodeWriter cw) { - GenerateNative2ManagedMethod0(method, false, lines); + GenerateNative2ManagedMethod0(method, false, cw); } - private void GenerateAdjustThunkMethod(MethodDesc method, List lines) + private void GenerateAdjustThunkMethod(MethodDesc method, CodeWriter cw) { - GenerateNative2ManagedMethod0(method, true, lines); + GenerateNative2ManagedMethod0(method, true, cw); } - private void GenerateManaged2NativeFunctionPointerMethod(CalliMethodInfo methodInfo, List lines) + private void GenerateManaged2NativeFunctionPointerMethod(CalliMethodInfo methodInfo, CodeWriter cw) { MethodDesc method = methodInfo.Method; string paramListStr = string.Join(", ", method.ParamInfos.Select(p => $"{p.Type.GetTypeName()} __arg{p.Index}")); string paramNameListStr = string.Join(", ", method.ParamInfos.Select(p => GetManaged2NativePassParam(p.Type, $"localVarBase+argVarIndexs[{p.Index}]"))); string il2cppCallConventionName = GetIl2cppCallConventionName(methodInfo.Callvention); - lines.Add($@" -static void __M2NF_{methodInfo.Signature}(Il2CppMethodPointer methodPointer, uint16_t* argVarIndexs, StackObject* localVarBase, void* ret) -{{ - typedef {method.ReturnInfo.Type.GetTypeName()} ({il2cppCallConventionName} *NativeMethod)({paramListStr}); - {(!method.ReturnInfo.IsVoid ? $"*({method.ReturnInfo.Type.GetTypeName()}*)ret = " : "")}((NativeMethod)(methodPointer))({paramNameListStr}); -}} -"); + cw.WriteLine(); + cw.WriteLine($"static void __M2NF_{methodInfo.Signature}(Il2CppMethodPointer methodPointer, uint16_t* argVarIndexs, StackObject* localVarBase, void* ret)"); + cw.WriteLine("{"); + cw.IncreaseIndent(); + cw.WriteLine($"typedef {method.ReturnInfo.Type.GetTypeName()} ({il2cppCallConventionName} *NativeMethod)({paramListStr});"); + cw.WriteLine($"{(!method.ReturnInfo.IsVoid ? $"*({method.ReturnInfo.Type.GetTypeName()}*)ret = " : "")}((NativeMethod)(methodPointer))({paramNameListStr});"); + cw.DecreaseIndent(); + cw.WriteLine("}"); } - private void GenerateManaged2NativeFunctionPointerMethodStub(List calliMethodSignatures, List lines) + private void GenerateManaged2NativeFunctionPointerMethodStub(List calliMethodSignatures, CodeWriter cw) { - lines.Add(@" -const Managed2NativeFunctionPointerCallData hybridclr::interpreter::g_managed2NativeFunctionPointerCallStub[] -{ -"); + cw.WriteLine(); + cw.WriteLine("const Managed2NativeFunctionPointerCallData hybridclr::interpreter::g_managed2NativeFunctionPointerCallStub[]"); + cw.WriteLine("{"); + cw.IncreaseIndent(); foreach (var method in calliMethodSignatures) { - lines.Add($"\t{{\"{method.Signature}\", __M2NF_{method.Signature}}},"); + cw.WriteLine($"{{\"{method.Signature}\", __M2NF_{method.Signature}}},"); } - - lines.Add(@" - {nullptr, nullptr}, -}; -"); + cw.WriteLine("{nullptr, nullptr},"); + cw.DecreaseIndent(); + cw.WriteLine("};"); } } } diff --git a/Editor/MethodBridge/Generator.cs.meta b/Editor/CodeGen/MethodBridge/Generator.cs.meta similarity index 100% rename from Editor/MethodBridge/Generator.cs.meta rename to Editor/CodeGen/MethodBridge/Generator.cs.meta diff --git a/Editor/MethodBridge/Analyzer.cs b/Editor/CodeGen/MethodBridge/MethodBridgeAnalyzer.cs similarity index 83% rename from Editor/MethodBridge/Analyzer.cs rename to Editor/CodeGen/MethodBridge/MethodBridgeAnalyzer.cs index dd0fd66..17b9ec5 100644 --- a/Editor/MethodBridge/Analyzer.cs +++ b/Editor/CodeGen/MethodBridge/MethodBridgeAnalyzer.cs @@ -1,17 +1,36 @@ +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + using dnlib.DotNet; -using HybridCLR.Editor.ABI; -using HybridCLR.Editor.Meta; -using System; +using HybridCLR.Meta; + +using HybridCLR.Utils; using System.Collections.Generic; using System.Linq; -using System.Text; using System.Threading.Tasks; using UnityEngine; -namespace HybridCLR.Editor.MethodBridge +namespace HybridCLR.CodeGen.MethodBridge { - public class Analyzer + public class MethodBridgeAnalyzer { public class Options { @@ -42,7 +61,7 @@ namespace HybridCLR.Editor.MethodBridge private readonly MethodReferenceAnalyzer _methodReferenceAnalyzer; - public Analyzer(Options options) + public MethodBridgeAnalyzer(Options options) { _maxInterationCount = options.MaxIterationCount; _assemblyCollector = options.Collector; @@ -55,7 +74,7 @@ namespace HybridCLR.Editor.MethodBridge { return; } - lock(_lock) + lock (_lock) { gc = StandardizeClass(gc); if (_genericTypes.Add(gc)) @@ -84,7 +103,7 @@ namespace HybridCLR.Editor.MethodBridge private void OnNewMethod(MethodDef methodDef, List klassGenericInst, List methodGenericInst, GenericMethod method) { - lock(_lock) + lock (_lock) { method = StandardizeMethod(method); if (_genericMethods.Add(method)) @@ -112,7 +131,7 @@ namespace HybridCLR.Editor.MethodBridge { var gm = StandardizeMethod(new GenericMethod(method, gc.KlassInst, null)); //Debug.Log($"add method:{gm.Method} {gm.KlassInst}"); - + if (_genericMethods.Add(gm)) { if (method.HasBody && method.Body.Instructions != null) @@ -134,7 +153,7 @@ namespace HybridCLR.Editor.MethodBridge } foreach (var method in typeDef.Methods) { - // 对于带泛型的参数,统一泛型共享为object + // Share generic parameters as object var gm = StandardizeMethod(new GenericMethod(method, null, null)); _genericMethods.Add(gm); } @@ -142,8 +161,8 @@ namespace HybridCLR.Editor.MethodBridge private void Prepare() { - // 将所有非泛型函数全部加入函数列表,同时立马walk这些method。 - // 后续迭代中将只遍历MethodSpec + // Add all non-generic methods to the list and walk them immediately. + // Later iterations only walk MethodSpec entries foreach (var ass in _assemblyCollector.GetLoadedModules()) { foreach (TypeDef typeDef in ass.GetTypes()) diff --git a/Editor/MethodBridge/Analyzer.cs.meta b/Editor/CodeGen/MethodBridge/MethodBridgeAnalyzer.cs.meta similarity index 100% rename from Editor/MethodBridge/Analyzer.cs.meta rename to Editor/CodeGen/MethodBridge/MethodBridgeAnalyzer.cs.meta diff --git a/Editor/MethodBridge/MonoPInvokeCallbackAnalyzer.cs b/Editor/CodeGen/MethodBridge/MonoPInvokeCallbackAnalyzer.cs similarity index 69% rename from Editor/MethodBridge/MonoPInvokeCallbackAnalyzer.cs rename to Editor/CodeGen/MethodBridge/MonoPInvokeCallbackAnalyzer.cs index 917c2a1..ea49b38 100644 --- a/Editor/MethodBridge/MonoPInvokeCallbackAnalyzer.cs +++ b/Editor/CodeGen/MethodBridge/MonoPInvokeCallbackAnalyzer.cs @@ -1,15 +1,31 @@ +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + using dnlib.DotNet; -using HybridCLR.Editor.ABI; -using HybridCLR.Editor.Meta; -using System; +using HybridCLR.Mod; +using HybridCLR.Utils; using System.Collections.Generic; using System.Linq; -using System.Text; -using System.Threading.Tasks; -using CallingConvention = System.Runtime.InteropServices.CallingConvention; using UnityEngine; -namespace HybridCLR.Editor.MethodBridge +namespace HybridCLR.CodeGen.MethodBridge { public class RawMonoPInvokeCallbackMethodInfo { diff --git a/Editor/MethodBridge/MonoPInvokeCallbackAnalyzer.cs.meta b/Editor/CodeGen/MethodBridge/MonoPInvokeCallbackAnalyzer.cs.meta similarity index 100% rename from Editor/MethodBridge/MonoPInvokeCallbackAnalyzer.cs.meta rename to Editor/CodeGen/MethodBridge/MonoPInvokeCallbackAnalyzer.cs.meta diff --git a/Editor/Commands/AOTReferenceGeneratorCommand.cs b/Editor/Commands/AOTReferenceGeneratorCommand.cs index b4dfb41..82e829b 100644 --- a/Editor/Commands/AOTReferenceGeneratorCommand.cs +++ b/Editor/Commands/AOTReferenceGeneratorCommand.cs @@ -1,17 +1,36 @@ -using HybridCLR.Editor.AOT; -using HybridCLR.Editor.Meta; +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using HybridCLR.CodeGen.AOT; +using HybridCLR.Meta; + +using HybridCLR.Utils; using System; using System.Collections.Generic; using System.IO; using System.Linq; -using System.Text; -using System.Threading.Tasks; using UnityEditor; using UnityEngine; -namespace HybridCLR.Editor.Commands +namespace HybridCLR.Commands { - using Analyzer = HybridCLR.Editor.AOT.Analyzer; public static class AOTReferenceGeneratorCommand { @@ -24,7 +43,7 @@ namespace HybridCLR.Editor.Commands } /// - /// 计算热更代码中的泛型引用 + /// Calculate generic references in hot update code /// /// public static void GenerateAOTGenericReference(BuildTarget target) @@ -33,7 +52,7 @@ namespace HybridCLR.Editor.Commands List hotUpdateDllNames = SettingsUtil.HotUpdateAssemblyNamesExcludePreserved; AssemblyReferenceDeepCollector collector = new AssemblyReferenceDeepCollector(MetaUtil.CreateHotUpdateAndAOTAssemblyResolver(target, hotUpdateDllNames), hotUpdateDllNames); - var analyzer = new Analyzer(new Analyzer.Options + var analyzer = new AOTReferenceAnalyzer(new AOTReferenceAnalyzer.Options { MaxIterationCount = Math.Min(20, gs.maxGenericReferenceIteration), Collector = collector, @@ -41,21 +60,13 @@ namespace HybridCLR.Editor.Commands analyzer.Run(); - var writer = new GenericReferenceWriter(); + var writer = new AOTGenericReferenceWriter(); writer.Write(analyzer.AotGenericTypes.ToList(), analyzer.AotGenericMethods.ToList(), $"{Application.dataPath}/{gs.outputAOTGenericReferenceFile}"); AssetDatabase.Refresh(); } - - - //[MenuItem("HybridCLR/Generate/AOTGenericReference2", priority = 103)] - //public static void GeneratedAOTGenericReferenceExcludeExists() - //{ - // GeneratedAOTGenericReferenceExcludeExists(EditorUserBuildSettings.activeBuildTarget); - //} - /// - /// 计算热更新代码中的泛型引用,但排除AOT已经存在的泛型引用 + /// Calculate generic references in hot update code, but exclude existing generic references in AOT /// /// /// @@ -66,7 +77,7 @@ namespace HybridCLR.Editor.Commands List hotUpdateDllNames = SettingsUtil.HotUpdateAssemblyNamesExcludePreserved; AssemblyReferenceDeepCollector hotUpdateCollector = new AssemblyReferenceDeepCollector(MetaUtil.CreateHotUpdateAndAOTAssemblyResolver(target, hotUpdateDllNames), hotUpdateDllNames); - var hotUpdateAnalyzer = new Analyzer(new Analyzer.Options + var hotUpdateAnalyzer = new AOTReferenceAnalyzer(new AOTReferenceAnalyzer.Options { MaxIterationCount = Math.Min(10, gs.maxGenericReferenceIteration), Collector = hotUpdateCollector, @@ -84,7 +95,7 @@ namespace HybridCLR.Editor.Commands throw new Exception($"no aot assembly found. please run `HybridCLR/Generate/All` or `HybridCLR/Generate/AotDlls` to generate aot dlls before runing `HybridCLR/Generate/AOTGenericReference`"); } AssemblyReferenceDeepCollector aotCollector = new AssemblyReferenceDeepCollector(MetaUtil.CreateAOTAssemblyResolver(target), aotAssemblyNames); - var aotAnalyzer = new Analyzer(new Analyzer.Options + var aotAnalyzer = new AOTReferenceAnalyzer(new AOTReferenceAnalyzer.Options { MaxIterationCount = Math.Min(10, gs.maxGenericReferenceIteration), Collector = aotCollector, @@ -94,7 +105,7 @@ namespace HybridCLR.Editor.Commands aotAnalyzer.Run(); var (resultTypes, resultMethods) = ExcludeExistAOTGenericTypeAndMethodss(hotUpdateAnalyzer.AotGenericTypes.ToList(), hotUpdateAnalyzer.AotGenericMethods.ToList(), aotAnalyzer.AotGenericTypes.ToList(), aotAnalyzer.AotGenericMethods.ToList()); - var writer = new GenericReferenceWriter(); + var writer = new AOTGenericReferenceWriter(); writer.Write(resultTypes, resultMethods, $"{Application.dataPath}/{gs.outputAOTGenericReferenceFile}"); AssetDatabase.Refresh(); } diff --git a/Editor/Commands/CompileDllCommand.cs b/Editor/Commands/CompileDllCommand.cs index 583368e..c1a78aa 100644 --- a/Editor/Commands/CompileDllCommand.cs +++ b/Editor/Commands/CompileDllCommand.cs @@ -1,14 +1,29 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System.IO; using UnityEditor; using UnityEditor.Build.Player; using UnityEngine; -namespace HybridCLR.Editor.Commands +namespace HybridCLR.Commands { public class CompileDllCommand { diff --git a/Editor/Commands/Il2CppDefGeneratorCommand.cs b/Editor/Commands/Il2CppDefGeneratorCommand.cs index 44890ee..ab15e26 100644 --- a/Editor/Commands/Il2CppDefGeneratorCommand.cs +++ b/Editor/Commands/Il2CppDefGeneratorCommand.cs @@ -1,13 +1,28 @@ -using HybridCLR.Editor.Link; -using HybridCLR.Editor.Settings; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using HybridCLR.CodeGen.Il2CppDef; using UnityEditor; using UnityEngine; -namespace HybridCLR.Editor.Commands +namespace HybridCLR.Commands { public static class Il2CppDefGeneratorCommand @@ -16,17 +31,15 @@ namespace HybridCLR.Editor.Commands [MenuItem("HybridCLR/Generate/Il2CppDef", priority = 104)] public static void GenerateIl2CppDef() { - var options = new Il2CppDef.Il2CppDefGenerator.Options() + var options = new Il2CppDefGenerator.Options() { UnityVersion = Application.unityVersion, HotUpdateAssemblies = SettingsUtil.HotUpdateAssemblyNamesIncludePreserved, - UnityVersionTemplateFile = $"{SettingsUtil.TemplatePathInPackage}/UnityVersion.h.tpl", - UnityVersionOutputFile = $"{SettingsUtil.LocalIl2CppDir}/libil2cpp/hybridclr/generated/UnityVersion.h", - AssemblyManifestTemplateFile = $"{SettingsUtil.TemplatePathInPackage}/AssemblyManifest.cpp.tpl", - AssemblyManifestOutputFile = $"{SettingsUtil.LocalIl2CppDir}/libil2cpp/hybridclr/generated/AssemblyManifest.cpp", + UnityVersionOutputFile = $"{SettingsUtil.GeneratedCppDir}/UnityVersion.inc", + AssemblyManifestOutputFile = $"{SettingsUtil.GeneratedCppDir}/AssemblyManifest.inc", }; - var g = new Il2CppDef.Il2CppDefGenerator(options); + var g = new Il2CppDefGenerator(options); g.Generate(); } } diff --git a/Editor/Commands/LinkGeneratorCommand.cs b/Editor/Commands/LinkGeneratorCommand.cs index c545ff5..bb1587b 100644 --- a/Editor/Commands/LinkGeneratorCommand.cs +++ b/Editor/Commands/LinkGeneratorCommand.cs @@ -1,15 +1,32 @@ -using HybridCLR.Editor.Link; -using HybridCLR.Editor.Meta; -using System; +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + + +using HybridCLR.CodeGen.Link; +using HybridCLR.Utils; using System.Collections.Generic; -using System.Reflection; using UnityEditor; using UnityEngine; -namespace HybridCLR.Editor.Commands +namespace HybridCLR.Commands { - using Analyzer = HybridCLR.Editor.Link.Analyzer; - public static class LinkGeneratorCommand { @@ -27,12 +44,12 @@ namespace HybridCLR.Editor.Commands List hotfixAssemblies = SettingsUtil.HotUpdateAssemblyNamesExcludePreserved; - var analyzer = new Analyzer(MetaUtil.CreateHotUpdateAndAOTAssemblyResolver(target, hotfixAssemblies)); - var refTypes = analyzer.CollectRefs(hotfixAssemblies); + var analyzer = new LinkAnalyzer(MetaUtil.CreateHotUpdateAndAOTAssemblyResolver(target, hotfixAssemblies)); + var preserveTypes = analyzer.CollectRefs(hotfixAssemblies, ls.linkPreserveLevel); - Debug.Log($"[LinkGeneratorCommand] hotfix assembly count:{hotfixAssemblies.Count}, ref type count:{refTypes.Count} output:{Application.dataPath}/{ls.outputLinkFile}"); + Debug.Log($"[LinkGeneratorCommand] hotfix assembly count:{hotfixAssemblies.Count}, preserve level:{ls.linkPreserveLevel}, type count:{preserveTypes.Count} output:{Application.dataPath}/{ls.outputLinkFile}"); var linkXmlWriter = new LinkXmlWriter(); - linkXmlWriter.Write($"{Application.dataPath}/{ls.outputLinkFile}", refTypes); + linkXmlWriter.Write($"{Application.dataPath}/{ls.outputLinkFile}", preserveTypes); AssetDatabase.Refresh(); } } diff --git a/Editor/Commands/MethodBridgeGeneratorCommand.cs b/Editor/Commands/MethodBridgeGeneratorCommand.cs index 0ebdce0..e15cdc4 100644 --- a/Editor/Commands/MethodBridgeGeneratorCommand.cs +++ b/Editor/Commands/MethodBridgeGeneratorCommand.cs @@ -1,41 +1,42 @@ -using HybridCLR.Editor; -using HybridCLR.Editor.ABI; -using HybridCLR.Editor.Meta; -using HybridCLR.Editor.MethodBridge; +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using HybridCLR.Meta; +using HybridCLR.CodeGen.MethodBridge; +using HybridCLR.Mod; +using HybridCLR.Utils; using System; using System.Collections.Generic; using System.IO; using System.Linq; -using System.Reflection; -using System.Text; -using System.Threading.Tasks; using UnityEditor; -using UnityEditor.Build; using UnityEngine; -namespace HybridCLR.Editor.Commands +namespace HybridCLR.Commands { - using Analyzer = HybridCLR.Editor.MethodBridge.Analyzer; public class MethodBridgeGeneratorCommand { - - public static void CleanIl2CppBuildCache() + public static void GenerateMethodBridgeCppFile(IReadOnlyCollection genericMethods, List reversePInvokeMethods, IReadOnlyCollection calliMethodSignatures, string outputFile) { - string il2cppBuildCachePath = SettingsUtil.Il2CppBuildCacheDir; - if (!Directory.Exists(il2cppBuildCachePath)) - { - return; - } - Debug.Log($"clean il2cpp build cache:{il2cppBuildCachePath}"); - Directory.Delete(il2cppBuildCachePath, true); - } - - private static void GenerateMethodBridgeCppFile(IReadOnlyCollection genericMethods, List reversePInvokeMethods, IReadOnlyCollection calliMethodSignatures, string tempFile, string outputFile) - { - string templateCode = File.ReadAllText(tempFile, Encoding.UTF8); var g = new Generator(new Generator.Options() { - TemplateCode = templateCode, OutputFile = outputFile, GenericMethods = genericMethods, ReversePInvokeMethods = reversePInvokeMethods, @@ -66,7 +67,7 @@ namespace HybridCLR.Editor.Commands } AssemblyReferenceDeepCollector collector = new AssemblyReferenceDeepCollector(MetaUtil.CreateAOTAssemblyResolver(target), aotAssemblyNames); - var methodBridgeAnalyzer = new Analyzer(new Analyzer.Options + var methodBridgeAnalyzer = new MethodBridgeAnalyzer(new MethodBridgeAnalyzer.Options { MaxIterationCount = Math.Min(20, SettingsUtil.HybridCLRSettings.maxMethodBridgeGenericIteration), Collector = collector, @@ -82,17 +83,11 @@ namespace HybridCLR.Editor.Commands var calliAnalyzer = new CalliAnalyzer(cache, hotUpdateDlls); calliAnalyzer.Run(); - var pinvokeAnalyzer = new PInvokeAnalyzer(cache, hotUpdateDlls); - pinvokeAnalyzer.Run(); - var callPInvokeMethodSignatures = pinvokeAnalyzer.PInvokeMethodSignatures; - string templateFile = $"{SettingsUtil.TemplatePathInPackage}/MethodBridge.cpp.tpl"; - string outputFile = $"{SettingsUtil.GeneratedCppDir}/MethodBridge.cpp"; + string outputFile = $"{SettingsUtil.GeneratedCppDir}/MethodBridge.inc"; - var callNativeMethodSignatures = calliAnalyzer.CalliMethodSignatures.Concat(pinvokeAnalyzer.PInvokeMethodSignatures).ToList(); - GenerateMethodBridgeCppFile(methodBridgeAnalyzer.GenericMethods, reversePInvokeAnalyzer.ReversePInvokeMethods, callNativeMethodSignatures, templateFile, outputFile); - - CleanIl2CppBuildCache(); + var callNativeMethodSignatures = calliAnalyzer.CalliMethodSignatures.ToList(); + GenerateMethodBridgeCppFile(methodBridgeAnalyzer.GenericMethods, reversePInvokeAnalyzer.ReversePInvokeMethods, callNativeMethodSignatures, outputFile); } } } diff --git a/Editor/Commands/PrebuildCommand.cs b/Editor/Commands/PrebuildCommand.cs index 3278802..fb85a75 100644 --- a/Editor/Commands/PrebuildCommand.cs +++ b/Editor/Commands/PrebuildCommand.cs @@ -1,17 +1,32 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using UnityEditor; +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using UnityEditor; using UnityEditor.Build; -namespace HybridCLR.Editor.Commands +namespace HybridCLR.Commands { public static class PrebuildCommand { /// - /// 按照必要的顺序,执行所有生成操作,适合打包前操作 + /// Execute all generation operations in the necessary order, suitable for pre-build operations /// [MenuItem("HybridCLR/Generate/All", priority = 200)] public static void GenerateAll() @@ -25,13 +40,13 @@ namespace HybridCLR.Editor.Commands CompileDllCommand.CompileDll(target, EditorUserBuildSettings.development); Il2CppDefGeneratorCommand.GenerateIl2CppDef(); - // 这几个生成依赖HotUpdateDlls + // These generation depend on HotUpdateDlls LinkGeneratorCommand.GenerateLinkXml(target); - // 生成裁剪后的aot dll + // Generate stripped aot dll StripAOTDllCommand.GenerateStripedAOTDlls(target); - // 桥接函数生成依赖于AOT dll,必须保证已经build过,生成AOT dll + // Method bridge generation depends on AOT dll, must be built before generating AOT dll MethodBridgeGeneratorCommand.GenerateMethodBridgeAndReversePInvokeWrapper(target); AOTReferenceGeneratorCommand.GenerateAOTGenericReference(target); } diff --git a/Editor/Commands/StripAOTDllCommand.cs b/Editor/Commands/StripAOTDllCommand.cs index 7e7230e..c7ee38e 100644 --- a/Editor/Commands/StripAOTDllCommand.cs +++ b/Editor/Commands/StripAOTDllCommand.cs @@ -1,20 +1,35 @@ -using HybridCLR.Editor.BuildProcessors; -using HybridCLR.Editor.Installer; +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using HybridCLR.BuildProcessors; +using HybridCLR.Utils; using System; -using System.Collections.Generic; -using System.IO; using System.Linq; -using System.Reflection; -using System.Text; -using System.Threading.Tasks; using UnityEditor; using UnityEngine; -namespace HybridCLR.Editor.Commands +namespace HybridCLR.Commands { public static class StripAOTDllCommand { - [MenuItem("HybridCLR/Generate/AOTDlls", priority = 105)] + [MenuItem("HybridCLR/Generate/StrippedAotDlls", priority = 105)] public static void GenerateStripedAOTDlls() { GenerateStripedAOTDlls(EditorUserBuildSettings.activeBuildTarget); @@ -53,22 +68,22 @@ namespace HybridCLR.Editor.Commands 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}/{PlayerSettings.productName}.exe"; + case BuildTarget.StandaloneOSX: return buildDir; + case BuildTarget.iOS: return buildDir; + case BuildTarget.Android: return buildDir; + case BuildTarget.StandaloneLinux64: return $"{buildDir}/{PlayerSettings.productName}"; + default: return buildDir; } } public static void GenerateStripedAOTDlls(BuildTarget target) { - string outputPath = $"{SettingsUtil.HybridCLRDataDir}/StrippedAOTDllsTempProj/{target}"; - BashUtil.RemoveDir(outputPath); + string outputPath = $"Temp/HybridCLR/StrippedAOTDllsTempProj/{target}"; + DirectoryUtil.RemoveDir(outputPath); var buildOptions = GetBuildPlayerOptions(target); @@ -94,36 +109,36 @@ namespace HybridCLR.Editor.Commands switch (target) { - case BuildTarget.StandaloneWindows: - case BuildTarget.StandaloneWindows64: - { - #if UNITY_EDITOR_WIN - UnityEditor.WindowsStandalone.UserBuildSettings.createSolution = true; - #endif - break; - } - case BuildTarget.StandaloneOSX: - { - #if UNITY_EDITOR_OSX + case BuildTarget.StandaloneWindows: + case BuildTarget.StandaloneWindows64: + { +#if UNITY_EDITOR_WIN + UnityEditor.WindowsStandalone.UserBuildSettings.createSolution = true; +#endif + break; + } + case BuildTarget.StandaloneOSX: + { +#if UNITY_EDITOR_OSX UnityEditor.OSXStandalone.UserBuildSettings.createXcodeProject = true; - #endif - break; - } - #if TUANJIE_2022_3_OR_NEWER +#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 +#endif + case BuildTarget.Android: + { + EditorUserBuildSettings.exportAsGoogleAndroidProject = true; + break; + } +#if TUANJIE_2022_3_OR_NEWER case BuildTarget.OpenHarmony: { EditorUserBuildSettings.exportAsOpenHarmonyProject = true; break; } - #endif +#endif } Debug.Log($"GenerateStripedAOTDlls build option:{buildOptions}"); @@ -157,29 +172,29 @@ namespace HybridCLR.Editor.Commands switch (target) { - case BuildTarget.StandaloneWindows: - case BuildTarget.StandaloneWindows64: - { + case BuildTarget.StandaloneWindows: + case BuildTarget.StandaloneWindows64: + { #if UNITY_EDITOR_WIN - UnityEditor.WindowsStandalone.UserBuildSettings.createSolution = oldCreateSolution; + UnityEditor.WindowsStandalone.UserBuildSettings.createSolution = oldCreateSolution; #endif - break; - } - case BuildTarget.StandaloneOSX: - { + break; + } + case BuildTarget.StandaloneOSX: + { #if UNITY_EDITOR_OSX UnityEditor.OSXStandalone.UserBuildSettings.createXcodeProject = oldCreateSolution; #endif - break; - } + break; + } #if TUANJIE_2022_3_OR_NEWER case BuildTarget.HMIAndroid: #endif - case BuildTarget.Android: - { - EditorUserBuildSettings.exportAsGoogleAndroidProject = oldExportAndroidProj; - break; - } + case BuildTarget.Android: + { + EditorUserBuildSettings.exportAsGoogleAndroidProject = oldExportAndroidProj; + break; + } #if TUANJIE_2022_3_OR_NEWER case BuildTarget.OpenHarmony: { diff --git a/Editor/HashUtil.cs b/Editor/HashUtil.cs deleted file mode 100644 index 38e83e3..0000000 --- a/Editor/HashUtil.cs +++ /dev/null @@ -1,28 +0,0 @@ -using dnlib.DotNet; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace HybridCLR.Editor -{ - public static class HashUtil - { - public static int CombineHash(int hash1, int hash2) - { - return hash1 * 1566083941 + hash2; - } - - public static int ComputHash(List sigs) - { - int hash = 135781321; - TypeEqualityComparer tc = TypeEqualityComparer.Instance; - foreach (var sig in sigs) - { - hash = hash * 1566083941 + tc.GetHashCode(sig); - } - return hash; - } - } -} diff --git a/Editor/HotUpdate/MissingMetadataChecker.cs b/Editor/HotUpdate/MissingMetadataChecker.cs index 2459b48..63f47f2 100644 --- a/Editor/HotUpdate/MissingMetadataChecker.cs +++ b/Editor/HotUpdate/MissingMetadataChecker.cs @@ -1,13 +1,29 @@ +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + using dnlib.DotNet; -using HybridCLR.Editor.Meta; -using System; +using HybridCLR.Mod; using System.Collections.Generic; using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace HybridCLR.Editor.HotUpdate +namespace HybridCLR.HotUpdate { public class MissingMetadataChecker { diff --git a/Editor/HybridCLR.Editor.asmdef b/Editor/HybridCLR.Editor.asmdef index 4612a6d..27a6287 100644 --- a/Editor/HybridCLR.Editor.asmdef +++ b/Editor/HybridCLR.Editor.asmdef @@ -1,6 +1,6 @@ { "name": "HybridCLR.Editor", - "rootNamespace": "", + "rootNamespace": "HybridCLR", "references": [ "HybridCLR.Runtime" ], diff --git a/Editor/Il2CppDef/Il2CppDefGenerator.cs b/Editor/Il2CppDef/Il2CppDefGenerator.cs deleted file mode 100644 index 0632750..0000000 --- a/Editor/Il2CppDef/Il2CppDefGenerator.cs +++ /dev/null @@ -1,107 +0,0 @@ -using HybridCLR.Editor.ABI; -using HybridCLR.Editor.Template; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Text.RegularExpressions; -using System.Threading.Tasks; -using UnityEngine; - -namespace HybridCLR.Editor.Il2CppDef -{ - public class Il2CppDefGenerator - { - public class Options - { - public List HotUpdateAssemblies { get; set; } - - public string UnityVersionTemplateFile { get; set; } - - public string UnityVersionOutputFile { get; set; } - - public string AssemblyManifestTemplateFile { 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() - { - GenerateIl2CppConfig(); - GeneratePlaceHolderAssemblies(); - } - - private void GenerateIl2CppConfig() - { - var frr = new FileRegionReplace(File.ReadAllText(_options.UnityVersionTemplateFile)); - - List lines = new List(); - - var match = s_unityVersionPat.Matches(_options.UnityVersion)[0]; - int majorVer = int.Parse(match.Groups[1].Value); - int minorVer1 = int.Parse(match.Groups[2].Value); - int minorVer2 = int.Parse(match.Groups[3].Value); - - lines.Add($"#define HYBRIDCLR_UNITY_VERSION {majorVer}{minorVer1.ToString("D2")}{minorVer2.ToString("D2")}"); - lines.Add($"#define HYBRIDCLR_UNITY_{majorVer} 1"); - for (int ver = 2019; ver <= 2023; ver++) - { - if (majorVer >= ver) - { - lines.Add($"#define HYBRIDCLR_UNITY_{ver}_OR_NEW 1"); - } - } - for (int ver = 6000; ver <= 6100; ver++) - { - if (majorVer >= ver) - { - lines.Add($"#define HYBRIDCLR_UNITY_{ver}_OR_NEW 1"); - } - } - -#if TUANJIE_1_1_OR_NEWER - var tuanjieMatch = Regex.Matches(Application.tuanjieVersion, @"(\d+)\.(\d+)\.(\d+)"); - int tuanjieMajorVer = int.Parse(tuanjieMatch[0].Groups[1].Value); - int tuanjieMinorVer1 = int.Parse(tuanjieMatch[0].Groups[2].Value); - int tuanjieMinorVer2 = int.Parse(tuanjieMatch[0].Groups[3].Value); - lines.Add($"#define HYBRIDCLR_TUANJIE_VERSION {tuanjieMajorVer}{tuanjieMinorVer1.ToString("D2")}{tuanjieMinorVer2.ToString("D2")}"); -#elif TUANJIE_2022_3_OR_NEWER - lines.Add($"#define HYBRIDCLR_TUANJIE_VERSION 10000"); -#endif - - frr.Replace("UNITY_VERSION", string.Join("\n", lines)); - - frr.Commit(_options.UnityVersionOutputFile); - Debug.Log($"[HybridCLR.Editor.Il2CppDef.Generator] output:{_options.UnityVersionOutputFile}"); - } - - private void GeneratePlaceHolderAssemblies() - { - var frr = new FileRegionReplace(File.ReadAllText(_options.AssemblyManifestTemplateFile)); - - List lines = new List(); - - foreach (var ass in _options.HotUpdateAssemblies) - { - lines.Add($"\t\t\"{ass}\","); - } - - frr.Replace("PLACE_HOLDER", string.Join("\n", lines)); - - frr.Commit(_options.AssemblyManifestOutputFile); - Debug.Log($"[HybridCLR.Editor.Il2CppDef.Generator] output:{_options.AssemblyManifestOutputFile}"); - } - } -} diff --git a/Editor/Installer/BashUtil.cs b/Editor/Installer/BashUtil.cs deleted file mode 100644 index 1685469..0000000 --- a/Editor/Installer/BashUtil.cs +++ /dev/null @@ -1,124 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; - -namespace HybridCLR.Editor.Installer -{ - public static class BashUtil - { - public static int RunCommand(string workingDir, string program, string[] args, bool log = true) - { - using (Process p = new Process()) - { - p.StartInfo.WorkingDirectory = workingDir; - p.StartInfo.FileName = program; - p.StartInfo.UseShellExecute = false; - p.StartInfo.CreateNoWindow = true; - string argsStr = string.Join(" ", args.Select(arg => "\"" + arg + "\"")); - p.StartInfo.Arguments = argsStr; - if (log) - { - UnityEngine.Debug.Log($"[BashUtil] run => {program} {argsStr}"); - } - p.Start(); - p.WaitForExit(); - return p.ExitCode; - } - } - - - public static (int ExitCode, string StdOut, string StdErr) RunCommand2(string workingDir, string program, string[] args, bool log = true) - { - using (Process p = new Process()) - { - p.StartInfo.WorkingDirectory = workingDir; - p.StartInfo.FileName = program; - p.StartInfo.UseShellExecute = false; - p.StartInfo.CreateNoWindow = true; - p.StartInfo.RedirectStandardOutput = true; - p.StartInfo.RedirectStandardError = true; - string argsStr = string.Join(" ", args); - p.StartInfo.Arguments = argsStr; - if (log) - { - UnityEngine.Debug.Log($"[BashUtil] run => {program} {argsStr}"); - } - p.Start(); - p.WaitForExit(); - - string stdOut = p.StandardOutput.ReadToEnd(); - string stdErr = p.StandardError.ReadToEnd(); - return (p.ExitCode, stdOut, stdErr); - } - } - - - public static void RemoveDir(string dir, bool log = false) - { - if (log) - { - UnityEngine.Debug.Log($"[BashUtil] RemoveDir dir:{dir}"); - } - - int maxTryCount = 5; - for (int i = 0; i < maxTryCount; ++i) - { - try - { - if (!Directory.Exists(dir)) - { - return; - } - foreach (var file in Directory.GetFiles(dir)) - { - File.SetAttributes(file, FileAttributes.Normal); - File.Delete(file); - } - foreach (var subDir in Directory.GetDirectories(dir)) - { - RemoveDir(subDir); - } - Directory.Delete(dir, true); - break; - } - catch (Exception e) - { - UnityEngine.Debug.LogError($"[BashUtil] RemoveDir:{dir} with exception:{e}. try count:{i}"); - Thread.Sleep(100); - } - } - } - - public static void RecreateDir(string dir) - { - if(Directory.Exists(dir)) - { - RemoveDir(dir, true); - } - Directory.CreateDirectory(dir); - } - public static void CopyDir(string src, string dst, bool log = false) - { - if (log) - { - UnityEngine.Debug.Log($"[BashUtil] CopyDir {src} => {dst}"); - } - if (Directory.Exists(dst)) - { - RemoveDir(dst); - } - else - { - string parentDir = Path.GetDirectoryName(Path.GetFullPath(dst)); - Directory.CreateDirectory(parentDir); - } - - UnityEditor.FileUtil.CopyFileOrDirectory(src, dst); - } - } -} diff --git a/Editor/Installer/InstallerController.cs b/Editor/Installer/InstallerController.cs index 361940e..9850260 100644 --- a/Editor/Installer/InstallerController.cs +++ b/Editor/Installer/InstallerController.cs @@ -1,19 +1,38 @@ +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + #if UNITY_6000_3_OR_NEWER && UNITY_EDITOR_OSX #define NEW_IL2CPP_PATH #endif +using HybridCLR.Settings; +using HybridCLR.Utils; using System; using System.Collections.Generic; using System.IO; +using System.Linq; using System.Text; using UnityEditor; using UnityEngine; using Debug = UnityEngine.Debug; -using System.Text.RegularExpressions; -using System.Linq; -using HybridCLR.Editor.Settings; -using System.Runtime.InteropServices; -namespace HybridCLR.Editor.Installer +namespace HybridCLR.Installer { public class InstallerController @@ -22,9 +41,10 @@ namespace HybridCLR.Editor.Installer private const string il2cpp_plus_repo_path = "il2cpp_plus_repo"; + public int MajorVersion => _curVersion.major; + private readonly UnityVersion _curVersion; - private readonly HybridclrVersionManifest _versionManifest; private readonly HybridclrVersionInfo _curDefaultVersion; public string PackageVersion { get; private set; } @@ -33,9 +53,10 @@ namespace HybridCLR.Editor.Installer public InstallerController() { - _curVersion = ParseUnityVersion(Application.unityVersion); - _versionManifest = GetHybridCLRVersionManifest(); - _curDefaultVersion = FindMatchedVersion(_versionManifest.versions, _curVersion); + _curVersion = UnityVersion.ParseUnityVersion(Application.unityVersion); + HybridclrVersionManifest versionManifest = GetHybridCLRVersionManifest(); + + _curDefaultVersion = FindMatchedVersion(versionManifest.versions, _curVersion); PackageVersion = LoadPackageInfo().version; InstalledLibil2cppVersion = ReadLocalVersion(); } @@ -52,6 +73,32 @@ namespace HybridCLR.Editor.Installer return JsonUtility.FromJson(File.ReadAllText(packageJson, Encoding.UTF8)); } + private HybridclrVersionInfo FindMatchedVersion(List versions, UnityVersion curVer) + { + HybridclrVersionInfo bestMatch = null; + foreach (var v in versions) + { + string[] versionWithEngineParts = v.unity_version.Split('-'); + bool isTuanjieVersion = versionWithEngineParts.Length >= 2 && versionWithEngineParts[1] == "tuanjie"; + if (curVer.isTuanjieEngine != isTuanjieVersion) + { + continue; + } + + string[] versionParts = versionWithEngineParts[0].Split('.'); + if (int.Parse(versionParts[0]) == curVer.major && (versionParts.Length < 2 || int.Parse(versionParts[1]) == curVer.minor1)) + { + bestMatch = v; + } + } + if (bestMatch == null) + { + string compatibleVersions = string.Join(", ", versions.Select(v => v.unity_version)); + throw new NotSupportedException($"No compatible version found for Unity {curVer.major}.{curVer.minor1}.{curVer.minor2}, please use compatible version of Unity: {compatibleVersions}"); + } + UnityEngine.Debug.Log($"bestMatch: {bestMatch.unity_version} {bestMatch.il2cpp_plus.tag} {bestMatch.hybridclr.tag} "); + return bestMatch; + } [Serializable] class PackageInfo @@ -64,7 +111,7 @@ namespace HybridCLR.Editor.Installer [Serializable] class VersionDesc { - public string branch; + public string tag; //public string hash; } @@ -85,110 +132,10 @@ namespace HybridCLR.Editor.Installer public List versions; } - private class UnityVersion - { - public int major; - public int minor1; - public int minor2; - public bool isTuanjieEngine; - public override string ToString() - { - return $"{major}.{minor1}.{minor2}"; - } - } + public string HybridclrLocalVersion => _curDefaultVersion?.hybridclr?.tag; - private static readonly Regex s_unityVersionPat = new Regex(@"(\d+)\.(\d+)\.(\d+)"); - - private UnityVersion ParseUnityVersion(string versionStr) - { - var matches = s_unityVersionPat.Matches(versionStr); - if (matches.Count == 0) - { - return null; - } - Match match = matches[matches.Count - 1]; - int major = int.Parse(match.Groups[1].Value); - int minor1 = int.Parse(match.Groups[2].Value); - int minor2 = int.Parse(match.Groups[3].Value); - bool isTuanjieEngine = versionStr.Contains("t"); - return new UnityVersion { major = major, minor1 = minor1, minor2 = minor2, isTuanjieEngine = isTuanjieEngine }; - } - - public string GetCurrentUnityVersionMinCompatibleVersionStr() - { - return GetMinCompatibleVersion(_curVersion.major, _curVersion.minor1); - } - - private HybridclrVersionInfo FindMatchedVersion(List versions, UnityVersion curVer) - { - HybridclrVersionInfo bestMatch = null; - foreach (var v in versions) - { - string[] versionWithEngineParts = v.unity_version.Split('-'); - if ((curVer.isTuanjieEngine && versionWithEngineParts.Length == 1) || (!curVer.isTuanjieEngine && versionWithEngineParts.Length == 2)) - { - continue; - } - - string[] versionParts = versionWithEngineParts[0].Split('.'); - if (int.Parse(versionParts[0]) == curVer.major && (versionParts.Length == 1 || int.Parse(versionParts[1]) <= curVer.minor1)) - { - bestMatch = v; - } - } - if (bestMatch == null) - { - throw new NotSupportedException($"No compatible version found for Unity {curVer.major}.{curVer.minor1}.{curVer.minor2}"); - } - return bestMatch; - } - - private string GetMinCompatibleVersion(int majorVersion, int minorVersion) - { - switch(majorVersion) - { - case 2019: return "2019.4.0"; - case 2020: return "2020.3.0"; - case 2021: return "2021.3.0"; - case 2022: return "2022.3.0"; - case 2023: return "2023.2.0"; - default: - { - if (majorVersion < 2019) - { - throw new NotSupportedException($"Unsupported major version: {majorVersion}"); - } - return $"{majorVersion}.0.0"; - } - } - } - - public enum CompatibleType - { - Compatible, - MaybeIncompatible, - Incompatible, - } - - public CompatibleType GetCompatibleType() - { - if (_curDefaultVersion == null) - { - return CompatibleType.Incompatible; - } - UnityVersion version = _curVersion; - if ((version.major == 2019 && version.minor1 < 4) - || (version.major >= 2020 && version.major <= 2022 && version.minor1 < 3)) - { - return CompatibleType.MaybeIncompatible; - } - return CompatibleType.Compatible; - } - - public string HybridclrLocalVersion => _curDefaultVersion?.hybridclr?.branch; - - public string Il2cppPlusLocalVersion => _curDefaultVersion?.il2cpp_plus?.branch; + public string Il2cppPlusLocalVersion => _curDefaultVersion?.il2cpp_plus?.tag; public string ApplicationIl2cppPath { @@ -208,7 +155,7 @@ namespace HybridCLR.Editor.Installer return $"{EditorApplication.applicationContentsPath}/../../PlaybackEngines/{platformDirName}/il2cpp"; #else return $"{EditorApplication.applicationContentsPath}/il2cpp"; - #endif +#endif } } @@ -226,6 +173,7 @@ namespace HybridCLR.Editor.Installer public void WriteLocalVersion() { InstalledLibil2cppVersion = PackageVersion; + Directory.CreateDirectory(Path.GetDirectoryName(LocalVersionFile)); File.WriteAllText(LocalVersionFile, PackageVersion, Encoding.UTF8); Debug.Log($"Write installed version:'{PackageVersion}' to {LocalVersionFile}"); } @@ -240,28 +188,10 @@ namespace HybridCLR.Editor.Installer return Directory.Exists($"{SettingsUtil.LocalIl2CppDir}/libil2cpp/hybridclr"); } - private string GetUnityIl2CppDllInstallLocation() - { -#if UNITY_EDITOR_WIN - return $"{SettingsUtil.LocalIl2CppDir}/build/deploy/net471/Unity.IL2CPP.dll"; -#else - return $"{SettingsUtil.LocalIl2CppDir}/build/deploy/il2cppcore/Unity.IL2CPP.dll"; -#endif - } - - private string GetUnityIl2CppDllModifiedPath(string curVersionStr) - { -#if UNITY_EDITOR_WIN - return $"{SettingsUtil.ProjectDir}/{SettingsUtil.HybridCLRDataPathInPackage}/ModifiedUnityAssemblies/{curVersionStr}/Unity.IL2CPP-Win.dll"; -#else - return $"{SettingsUtil.ProjectDir}/{SettingsUtil.HybridCLRDataPathInPackage}/ModifiedUnityAssemblies/{curVersionStr}/Unity.IL2CPP-Mac.dll"; -#endif - } - void CloneBranch(string workDir, string repoUrl, string branch, string repoDir) { - BashUtil.RemoveDir(repoDir); - BashUtil.RunCommand(workDir, "git", new string[] {"clone", "-b", branch, "--depth", "1", repoUrl, repoDir}); + DirectoryUtil.RemoveDir(repoDir); + BashUtil.RunCommand(workDir, "git", new string[] { "clone", "-b", branch, "--depth", "1", repoUrl, repoDir }); } private string PrepareLibil2cppWithHybridclrFromGitRepo() @@ -271,9 +201,9 @@ namespace HybridCLR.Editor.Installer //BashUtil.RecreateDir(workDir); // clone hybridclr - string hybridclrRepoURL = HybridCLRSettings.Instance.hybridclrRepoURL; + string hybridclrRepoURL = HybridCLRSettings.instance.hybridclrRepoURL; string hybridclrRepoDir = $"{workDir}/{hybridclr_repo_path}"; - CloneBranch(workDir, hybridclrRepoURL, _curDefaultVersion.hybridclr.branch, hybridclrRepoDir); + CloneBranch(workDir, hybridclrRepoURL, _curDefaultVersion.hybridclr.tag, hybridclrRepoDir); if (!Directory.Exists(hybridclrRepoDir)) { @@ -281,9 +211,9 @@ namespace HybridCLR.Editor.Installer } // clone il2cpp_plus - string il2cppPlusRepoURL = HybridCLRSettings.Instance.il2cppPlusRepoURL; + string il2cppPlusRepoURL = HybridCLRSettings.instance.il2cppPlusRepoURL; string il2cppPlusRepoDir = $"{workDir}/{il2cpp_plus_repo_path}"; - CloneBranch(workDir, il2cppPlusRepoURL, _curDefaultVersion.il2cpp_plus.branch, il2cppPlusRepoDir); + CloneBranch(workDir, il2cppPlusRepoURL, _curDefaultVersion.il2cpp_plus.tag, il2cppPlusRepoDir); if (!Directory.Exists(il2cppPlusRepoDir)) { @@ -296,61 +226,41 @@ namespace HybridCLR.Editor.Installer public void InstallFromLocal(string libil2cppWithHybridclrSourceDir) { - RunInitLocalIl2CppData(ApplicationIl2cppPath, libil2cppWithHybridclrSourceDir, _curVersion); + RunInitLocalIl2CppData(ApplicationIl2cppPath, libil2cppWithHybridclrSourceDir); } - private void RunInitLocalIl2CppData(string editorIl2cppPath, string libil2cppWithHybridclrSourceDir, UnityVersion version) + private void RunInitLocalIl2CppData(string editorIl2cppPath, string libil2cppWithHybridclrSourceDir) { - if (GetCompatibleType() == CompatibleType.Incompatible) - { - Debug.LogError($"Incompatible with current version, minimum compatible version: {GetCurrentUnityVersionMinCompatibleVersionStr()}"); - return; - } string workDir = SettingsUtil.HybridCLRDataDir; Directory.CreateDirectory(workDir); // create LocalIl2Cpp string localUnityDataDir = SettingsUtil.LocalUnityDataDir; - BashUtil.RecreateDir(localUnityDataDir); + DirectoryUtil.RecreateDir(localUnityDataDir); #if !NEW_IL2CPP_PATH // copy MonoBleedingEdge - BashUtil.CopyDir($"{Directory.GetParent(editorIl2cppPath)}/MonoBleedingEdge", $"{localUnityDataDir}/MonoBleedingEdge", true); + DirectoryUtil.CopyDir($"{Directory.GetParent(editorIl2cppPath)}/MonoBleedingEdge", $"{localUnityDataDir}/MonoBleedingEdge", true); #endif // copy il2cpp - BashUtil.CopyDir(editorIl2cppPath, SettingsUtil.LocalIl2CppDir, true); + DirectoryUtil.CopyDir(editorIl2cppPath, SettingsUtil.LocalIl2CppDir, true); #if NEW_IL2CPP_PATH string buildDir = $"{SettingsUtil.LocalIl2CppDir}/build"; if (RuntimeInformation.ProcessArchitecture == Architecture.Arm || RuntimeInformation.ProcessArchitecture == Architecture.Arm64) { - BashUtil.CopyDir($"{buildDir}/deploy_arm64", $"{buildDir}/deploy", false); + DirectoryUtil.CopyDir($"{buildDir}/deploy_arm64", $"{buildDir}/deploy", false); } else { - BashUtil.CopyDir($"{buildDir}/deploy_x86_64", $"{buildDir}/deploy", false); + DirectoryUtil.CopyDir($"{buildDir}/deploy_x86_64", $"{buildDir}/deploy", false); } #endif // replace libil2cpp string dstLibil2cppDir = $"{SettingsUtil.LocalIl2CppDir}/libil2cpp"; - BashUtil.CopyDir($"{libil2cppWithHybridclrSourceDir}", dstLibil2cppDir, true); + DirectoryUtil.CopyDir($"{libil2cppWithHybridclrSourceDir}", dstLibil2cppDir, true); // clean Il2cppBuildCache - BashUtil.RemoveDir($"{SettingsUtil.ProjectDir}/Library/Il2cppBuildCache", true); - if (version.major == 2019) - { - string curVersionStr = version.ToString(); - string srcIl2CppDll = GetUnityIl2CppDllModifiedPath(curVersionStr); - if (File.Exists(srcIl2CppDll)) - { - string dstIl2CppDll = GetUnityIl2CppDllInstallLocation(); - File.Copy(srcIl2CppDll, dstIl2CppDll, true); - Debug.Log($"copy {srcIl2CppDll} => {dstIl2CppDll}"); - } - else - { - throw new Exception($"the modified Unity.IL2CPP.dll of {curVersionStr} isn't found. please install hybridclr in 2019.4.40 first, then switch to your unity version"); - } - } + DirectoryUtil.RemoveDir($"{SettingsUtil.ProjectDir}/Library/Il2cppBuildCache", true); if (HasInstalledHybridCLR()) { WriteLocalVersion(); diff --git a/Editor/Installer/InstallerWindow.cs b/Editor/Installer/InstallerWindow.cs index 1869f89..dd9617b 100644 --- a/Editor/Installer/InstallerWindow.cs +++ b/Editor/Installer/InstallerWindow.cs @@ -1,11 +1,29 @@ -using System; +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + using System.IO; -using System.Reflection; using UnityEditor; using UnityEngine; -namespace HybridCLR.Editor.Installer +namespace HybridCLR.Installer { public class InstallerWindow : EditorWindow { @@ -51,39 +69,28 @@ namespace HybridCLR.Editor.Installer GUILayout.Space(10f); - InstallerController.CompatibleType compatibleType = _controller.GetCompatibleType(); - if (compatibleType != InstallerController.CompatibleType.Incompatible) + + + EditorGUILayout.BeginHorizontal(); + _installFromDir = EditorGUILayout.Toggle("Copy libil2cpp from local", _installFromDir, GUILayout.MinWidth(100)); + EditorGUI.BeginDisabledGroup(!_installFromDir); + EditorGUILayout.TextField(_installLibil2cppWithHybridclrSourceDir, GUILayout.Width(400)); + if (GUILayout.Button("Choose", GUILayout.Width(100))) { - if (compatibleType == InstallerController.CompatibleType.MaybeIncompatible) - { - EditorGUILayout.HelpBox($"Maybe incompatible with current version, recommend minimum compatible version:{_controller.GetCurrentUnityVersionMinCompatibleVersionStr()}", MessageType.Warning); - } - - EditorGUILayout.BeginHorizontal(); - _installFromDir = EditorGUILayout.Toggle("Copy libil2cpp from local", _installFromDir, GUILayout.MinWidth(100)); - EditorGUI.BeginDisabledGroup(!_installFromDir); - EditorGUILayout.TextField(_installLibil2cppWithHybridclrSourceDir, GUILayout.Width(400)); - if (GUILayout.Button("Choose", GUILayout.Width(100))) - { - _installLibil2cppWithHybridclrSourceDir = EditorUtility.OpenFolderPanel("Select libil2cpp", Application.dataPath, "libil2cpp"); - } - EditorGUI.EndDisabledGroup(); - EditorGUILayout.EndHorizontal(); - - GUILayout.Space(20f); - - EditorGUILayout.BeginHorizontal(); - if (GUILayout.Button("Install", GUILayout.Width(100))) - { - InstallLocalHybridCLR(); - GUIUtility.ExitGUI(); - } - EditorGUILayout.EndHorizontal(); + _installLibil2cppWithHybridclrSourceDir = EditorUtility.OpenFolderPanel("Select libil2cpp", Application.dataPath, "libil2cpp"); } - else + EditorGUI.EndDisabledGroup(); + EditorGUILayout.EndHorizontal(); + + GUILayout.Space(20f); + + EditorGUILayout.BeginHorizontal(); + if (GUILayout.Button("Install", GUILayout.Width(100))) { - EditorGUILayout.HelpBox($"Incompatible with current version, minimum compatible version:{_controller.GetCurrentUnityVersionMinCompatibleVersionStr()}", MessageType.Error); + InstallLocalHybridCLR(); + GUIUtility.ExitGUI(); } + EditorGUILayout.EndHorizontal(); EditorGUILayout.EndVertical(); } diff --git a/Editor/Installer/UnityCompatibleUtil.cs b/Editor/Installer/UnityCompatibleUtil.cs new file mode 100644 index 0000000..7651b99 --- /dev/null +++ b/Editor/Installer/UnityCompatibleUtil.cs @@ -0,0 +1,31 @@ +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#if UNITY_6000_3_OR_NEWER && UNITY_EDITOR_OSX +#define NEW_IL2CPP_PATH +#endif +namespace HybridCLR.Installer +{ + public class UnityCompatibleUtil + { + + + } +} diff --git a/Editor/3rds/7zip/Common/InBuffer.cs.meta b/Editor/Installer/UnityCompatibleUtil.cs.meta similarity index 83% rename from Editor/3rds/7zip/Common/InBuffer.cs.meta rename to Editor/Installer/UnityCompatibleUtil.cs.meta index 843e5cf..7dbb8a0 100644 --- a/Editor/3rds/7zip/Common/InBuffer.cs.meta +++ b/Editor/Installer/UnityCompatibleUtil.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 6ea025f5b275726479ba55e956574898 +guid: 9eaeda6b4aeb5be449ba1ebeb98014df MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Editor/Installer/UnityVersion.cs b/Editor/Installer/UnityVersion.cs new file mode 100644 index 0000000..c85d512 --- /dev/null +++ b/Editor/Installer/UnityVersion.cs @@ -0,0 +1,58 @@ +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#if UNITY_6000_3_OR_NEWER && UNITY_EDITOR_OSX +#define NEW_IL2CPP_PATH +#endif +using System.Text.RegularExpressions; + +namespace HybridCLR.Installer +{ + public class UnityVersion + { + public int major; + public int minor1; + public int minor2; + public bool isTuanjieEngine; + + public override string ToString() + { + return $"{major}.{minor1}.{minor2}"; + } + + + private static readonly Regex s_unityVersionPat = new Regex(@"(\d+)\.(\d+)\.(\d+)"); + + public static UnityVersion ParseUnityVersion(string versionStr) + { + var matches = s_unityVersionPat.Matches(versionStr); + if (matches.Count == 0) + { + return null; + } + Match match = matches[matches.Count - 1]; + int major = int.Parse(match.Groups[1].Value); + int minor1 = int.Parse(match.Groups[2].Value); + int minor2 = int.Parse(match.Groups[3].Value); + bool isTuanjieEngine = versionStr.Contains("t"); + return new UnityVersion { major = major, minor1 = minor1, minor2 = minor2, isTuanjieEngine = isTuanjieEngine }; + } + } +} diff --git a/Editor/3rds/7zip/Common/OutBuffer.cs.meta b/Editor/Installer/UnityVersion.cs.meta similarity index 83% rename from Editor/3rds/7zip/Common/OutBuffer.cs.meta rename to Editor/Installer/UnityVersion.cs.meta index 38af8c8..e2dc90b 100644 --- a/Editor/3rds/7zip/Common/OutBuffer.cs.meta +++ b/Editor/Installer/UnityVersion.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 5d61847c152e7384ab15aea89a942f54 +guid: 7b474b2f44b3d804dace7aa7357ce144 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Editor/Link/Analyzer.cs b/Editor/Link/Analyzer.cs deleted file mode 100644 index ffbb93d..0000000 --- a/Editor/Link/Analyzer.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Text; -using System.Threading.Tasks; -using dnlib.DotNet; -using HybridCLR.Editor.Meta; -using UnityEditor; -using UnityEngine; -using IAssemblyResolver = HybridCLR.Editor.Meta.IAssemblyResolver; - -namespace HybridCLR.Editor.Link -{ - public class Analyzer - { - private readonly IAssemblyResolver _resolver; - - public Analyzer(IAssemblyResolver resolver) - { - _resolver = resolver; - } - - public HashSet CollectRefs(List rootAssemblies) - { - var assCollector = new AssemblyCache(_resolver); - var rootAssemblyNames = new HashSet(rootAssemblies); - - var typeRefs = new HashSet(TypeEqualityComparer.Instance); - foreach (var rootAss in rootAssemblies) - { - var dnAss = assCollector.LoadModule(rootAss, false); - foreach (var type in dnAss.GetTypeRefs()) - { - if (type.DefinitionAssembly == null) - { - Debug.LogWarning($"assembly:{dnAss.Name} TypeRef {type.FullName} has no DefinitionAssembly"); - continue; - } - if (!rootAssemblyNames.Contains(type.DefinitionAssembly.Name.ToString())) - { - typeRefs.Add(type); - } - } - } - return typeRefs; - } - } -} diff --git a/Editor/Link/LinkXmlWriter.cs b/Editor/Link/LinkXmlWriter.cs deleted file mode 100644 index d72d0f7..0000000 --- a/Editor/Link/LinkXmlWriter.cs +++ /dev/null @@ -1,53 +0,0 @@ -using dnlib.DotNet; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; - -namespace HybridCLR.Editor.Link -{ - public class LinkXmlWriter - { - public void Write(string outputLinkXmlFile, HashSet refTypes) - { - string parentDir = Directory.GetParent(outputLinkXmlFile).FullName; - Directory.CreateDirectory(parentDir); - var writer = System.Xml.XmlWriter.Create(outputLinkXmlFile, - new System.Xml.XmlWriterSettings { Encoding = Encoding.UTF8, Indent = true}); - - writer.WriteStartDocument(); - writer.WriteStartElement("linker"); - - var typesByAssembly = refTypes.GroupBy(t => t.DefinitionAssembly.Name.String).ToList(); - typesByAssembly.Sort((a, b) => String.Compare(a.Key, b.Key, StringComparison.Ordinal)); - - foreach(var assembly in typesByAssembly) - { - writer.WriteStartElement("assembly"); - writer.WriteAttributeString("fullname", assembly.Key); - List assTypeNames = assembly.Select(t => t.FullName).ToList(); - assTypeNames.Sort(string.CompareOrdinal); - foreach(var typeName in assTypeNames) - { -#if UNITY_2023_1_OR_NEWER - if (typeName == "UnityEngine.Debug") - { - continue; - } -#endif - writer.WriteStartElement("type"); - writer.WriteAttributeString("fullname", typeName); - writer.WriteAttributeString("preserve", "all"); - writer.WriteEndElement(); - } - writer.WriteEndElement(); - } - writer.WriteEndElement(); - writer.WriteEndDocument(); - writer.Close(); - } - } -} diff --git a/Editor/MenuProvider.cs b/Editor/MenuProvider.cs new file mode 100644 index 0000000..260cc5c --- /dev/null +++ b/Editor/MenuProvider.cs @@ -0,0 +1,60 @@ +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using HybridCLR.Installer; +using UnityEditor; +using UnityEngine; + +namespace HybridCLR +{ + public static class MenuProvider + { + public const string WebsiteUrl = "https://www.hybridclr.cn"; + + [MenuItem("HybridCLR/About", priority = 0)] + public static void OpenAbout() => Application.OpenURL($"{WebsiteUrl}/docs/intro"); + + [MenuItem("HybridCLR/Installer...", priority = 60)] + private static void Open() + { + InstallerWindow window = EditorWindow.GetWindow("HybridCLR Installer", true); + window.minSize = new Vector2(800f, 500f); + } + + [MenuItem("HybridCLR/Settings...", priority = 61)] + public static void OpenSettings() => SettingsService.OpenProjectSettings("Project/HybridCLR Settings"); + + [MenuItem("HybridCLR/Documents/Quick Start")] + public static void OpenQuickStart() => Application.OpenURL($"{WebsiteUrl}/docs/beginner/quickstart"); + + [MenuItem("HybridCLR/Documents/Performance")] + public static void OpenPerformance() => Application.OpenURL($"{WebsiteUrl}/docs/basic/performance"); + + [MenuItem("HybridCLR/Documents/FAQ")] + public static void OpenFAQ() => Application.OpenURL($"{WebsiteUrl}/docs/help/faq"); + + [MenuItem("HybridCLR/Documents/Common Errors")] + public static void OpenCommonErrors() => Application.OpenURL($"{WebsiteUrl}/docs/help/commonerrors"); + + [MenuItem("HybridCLR/Documents/Bug Report")] + public static void OpenBugReport() => Application.OpenURL($"{WebsiteUrl}/docs/help/issue"); + } + +} \ No newline at end of file diff --git a/Editor/Settings/MenuProvider.cs.meta b/Editor/MenuProvider.cs.meta similarity index 100% rename from Editor/Settings/MenuProvider.cs.meta rename to Editor/MenuProvider.cs.meta diff --git a/Editor/Meta/AssemblyCache.cs b/Editor/Meta/AssemblyCache.cs deleted file mode 100644 index 7fed930..0000000 --- a/Editor/Meta/AssemblyCache.cs +++ /dev/null @@ -1,20 +0,0 @@ -using dnlib.DotNet; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Text; -using System.Threading.Tasks; -using UnityEngine; - -namespace HybridCLR.Editor.Meta -{ - public class AssemblyCache : AssemblyCacheBase - { - - public AssemblyCache(IAssemblyResolver assemblyResolver) : base(assemblyResolver) - { - - } - } -} diff --git a/Editor/Meta/AssemblyReferenceDeepCollector.cs b/Editor/Meta/AssemblyReferenceDeepCollector.cs index 44c1c71..1fc8c2b 100644 --- a/Editor/Meta/AssemblyReferenceDeepCollector.cs +++ b/Editor/Meta/AssemblyReferenceDeepCollector.cs @@ -1,13 +1,30 @@ +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + using dnlib.DotNet; -using System; +using HybridCLR.Mod; using System.Collections.Generic; using System.Linq; -using System.Reflection; -using System.Text; -using System.Threading.Tasks; -using UnityEngine; +using IAssemblyResolver = HybridCLR.Mod.IAssemblyResolver; -namespace HybridCLR.Editor.Meta +namespace HybridCLR.Meta { public class AssemblyReferenceDeepCollector : AssemblyCacheBase { diff --git a/Editor/Meta/AssemblyResolverBase.cs b/Editor/Meta/AssemblyResolverBase.cs deleted file mode 100644 index 973619a..0000000 --- a/Editor/Meta/AssemblyResolverBase.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace HybridCLR.Editor.Meta -{ - public abstract class AssemblyResolverBase : IAssemblyResolver - { - public string ResolveAssembly(string assemblyName, bool throwExIfNotFind) - { - if (TryResolveAssembly(assemblyName, out string assemblyPath)) - { - return assemblyPath; - } - if (throwExIfNotFind) - { - if (SettingsUtil.HotUpdateAssemblyNamesIncludePreserved.Contains(assemblyName)) - { - throw new Exception($"resolve Hot update dll:{assemblyName} failed! Please make sure that this hot update dll exists or the search path is configured in the external hot update path."); - } - else - { - throw new Exception($"resolve AOT dll:{assemblyName} failed! Please make sure that the AOT project has referenced the dll and generated the trimmed AOT dll correctly."); - } - } - return null; - } - - protected abstract bool TryResolveAssembly(string assemblyName, out string assemblyPath); - } -} diff --git a/Editor/Meta/AssemblySorter.cs b/Editor/Meta/AssemblySorter.cs deleted file mode 100644 index 3784b37..0000000 --- a/Editor/Meta/AssemblySorter.cs +++ /dev/null @@ -1,105 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace HybridCLR.Editor.Meta -{ - - public class AssemblySorter - { - class Node - { - public string Name; - public List Dependencies = new List(); - - public Node(string name) - { - Name = name; - } - } - - class TopologicalSorter - { - - public static List Sort(List nodes) - { - List sorted = new List(); - HashSet visited = new HashSet(); - HashSet tempMarks = new HashSet(); - - foreach (var node in nodes) - { - if (!visited.Contains(node)) - { - Visit(node, visited, tempMarks, sorted); - } - } - return sorted; - } - - private static void Visit(Node node, HashSet visited, HashSet tempMarks, List sorted) - { - if (tempMarks.Contains(node)) - { - throw new Exception("Detected cyclic dependency!"); - } - - if (!visited.Contains(node)) - { - tempMarks.Add(node); - foreach (var dependency in node.Dependencies) - { - Visit(dependency, visited, tempMarks, sorted); - } - tempMarks.Remove(node); - visited.Add(node); - sorted.Add(node); - } - } - } - - private static List SortAssemblyByReferenceOrder(IEnumerable assemblies, Dictionary> refs) - { - var nodes = new List(); - var nodeMap = new Dictionary(); - foreach (var assembly in assemblies) - { - var node = new Node(assembly); - nodes.Add(node); - nodeMap.Add(assembly, node); - } - foreach (var assembly in assemblies) - { - var node = nodeMap[assembly]; - foreach (var refAssembly in refs[assembly]) - { - node.Dependencies.Add(nodeMap[refAssembly]); - } - } - var sortedNodes = TopologicalSorter.Sort(nodes); - return sortedNodes.Select(node => node.Name).ToList(); - } - - public static List SortAssemblyByReferenceOrder(IEnumerable assemblies, IAssemblyResolver assemblyResolver) - { - var assCache = new AssemblyCache(assemblyResolver); - var assRefAssemblies = new Dictionary>(); - foreach (var assName in assemblies) - { - var refAssemblies = new HashSet(); - var mod = assCache.LoadModule(assName, false); - foreach (var refAss in mod.GetAssemblyRefs()) - { - if (assemblies.Contains(refAss.Name.ToString())) - { - refAssemblies.Add(refAss.Name.ToString()); - } - } - assRefAssemblies.Add(assName, refAssemblies); - } - return SortAssemblyByReferenceOrder(assemblies, assRefAssemblies); - } - } -} diff --git a/Editor/Meta/AssemblySorter.cs.meta b/Editor/Meta/AssemblySorter.cs.meta deleted file mode 100644 index 6fce7f9..0000000 --- a/Editor/Meta/AssemblySorter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: b9b8eb45398fa344daa8c6e9b9fbf291 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/Meta/CombinedAssemblyResolver.cs b/Editor/Meta/CombinedAssemblyResolver.cs deleted file mode 100644 index 31a0c51..0000000 --- a/Editor/Meta/CombinedAssemblyResolver.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace HybridCLR.Editor.Meta -{ - public class CombinedAssemblyResolver : AssemblyResolverBase - { - private readonly IAssemblyResolver[] _resolvers; - - public CombinedAssemblyResolver(params IAssemblyResolver[] resolvers) - { - _resolvers = resolvers; - } - - protected override bool TryResolveAssembly(string assemblyName, out string assemblyPath) - { - foreach(var resolver in _resolvers) - { - var assembly = resolver.ResolveAssembly(assemblyName, false); - if (assembly != null) - { - assemblyPath = assembly; - return true; - } - } - assemblyPath = null; - return false; - } - } -} diff --git a/Editor/Meta/GenericArgumentContext.cs b/Editor/Meta/GenericArgumentContext.cs index d200399..c2c6d12 100644 --- a/Editor/Meta/GenericArgumentContext.cs +++ b/Editor/Meta/GenericArgumentContext.cs @@ -1,11 +1,29 @@ +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + using dnlib.DotNet; using System; using System.Collections.Generic; using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace HybridCLR.Editor.Meta +namespace HybridCLR.Meta { public class GenericArgumentContext @@ -21,84 +39,84 @@ namespace HybridCLR.Editor.Meta public TypeSig Resolve(TypeSig typeSig) { - if (!typeSig.ContainsGenericParameter) + if (!typeSig.ContainsGenericParameter) { - return typeSig; + return typeSig; } typeSig = typeSig.RemovePinnedAndModifiers(); - switch (typeSig.ElementType) - { - case ElementType.Ptr: return new PtrSig(Resolve(typeSig.Next)); - case ElementType.ByRef: return new ByRefSig(Resolve(typeSig.Next)); + switch (typeSig.ElementType) + { + case ElementType.Ptr: return new PtrSig(Resolve(typeSig.Next)); + case ElementType.ByRef: return new ByRefSig(Resolve(typeSig.Next)); - case ElementType.SZArray: return new SZArraySig(Resolve(typeSig.Next)); - case ElementType.Array: - { - var ara = (ArraySig)typeSig; - return new ArraySig(Resolve(typeSig.Next), ara.Rank, ara.Sizes, ara.LowerBounds); - } + case ElementType.SZArray: return new SZArraySig(Resolve(typeSig.Next)); + case ElementType.Array: + { + var ara = (ArraySig)typeSig; + return new ArraySig(Resolve(typeSig.Next), ara.Rank, ara.Sizes, ara.LowerBounds); + } - case ElementType.Var: + case ElementType.Var: + { + GenericVar genericVar = (GenericVar)typeSig; + var newSig = Resolve(typeArgsStack, genericVar.Number); + if (newSig == null) { - GenericVar genericVar = (GenericVar)typeSig; - var newSig = Resolve(typeArgsStack, genericVar.Number); - if (newSig == null) - { - throw new Exception(); - } - return newSig; + throw new Exception(); } + return newSig; + } - case ElementType.MVar: + case ElementType.MVar: + { + GenericMVar genericVar = (GenericMVar)typeSig; + var newSig = Resolve(methodArgsStack, genericVar.Number); + if (newSig == null) { - GenericMVar genericVar = (GenericMVar)typeSig; - var newSig = Resolve(methodArgsStack, genericVar.Number); - if (newSig == null) - { - throw new Exception(); - } - return newSig; - } - case ElementType.GenericInst: - { - var gia = (GenericInstSig)typeSig; - return new GenericInstSig(gia.GenericType, gia.GenericArguments.Select(ga => Resolve(ga)).ToList()); + throw new Exception(); } + return newSig; + } + case ElementType.GenericInst: + { + var gia = (GenericInstSig)typeSig; + return new GenericInstSig(gia.GenericType, gia.GenericArguments.Select(ga => Resolve(ga)).ToList()); + } - case ElementType.FnPtr: + case ElementType.FnPtr: + { + var fptr = (FnPtrSig)typeSig; + var cs = fptr.Signature; + CallingConventionSig ccs; + switch (cs) { - var fptr = (FnPtrSig)typeSig; - var cs = fptr.Signature; - CallingConventionSig ccs; - switch (cs) - { - case MethodSig ms: - { - ccs = new MethodSig(ms.GetCallingConvention(), ms.GenParamCount, Resolve(ms.RetType), ms.Params.Select(p => Resolve(p)).ToList()); - break; - } - case PropertySig ps: - { - ccs = new PropertySig(ps.HasThis, Resolve(ps.RetType)); - break; - } - case GenericInstMethodSig gims: - { - ccs = new GenericInstMethodSig(gims.GenericArguments.Select(ga => Resolve(ga)).ToArray()); - break; - } - default: throw new NotSupportedException(cs.ToString()); - } - return new FnPtrSig(ccs); + case MethodSig ms: + { + ccs = new MethodSig(ms.GetCallingConvention(), ms.GenParamCount, Resolve(ms.RetType), ms.Params.Select(p => Resolve(p)).ToList()); + break; } + case PropertySig ps: + { + ccs = new PropertySig(ps.HasThis, Resolve(ps.RetType)); + break; + } + case GenericInstMethodSig gims: + { + ccs = new GenericInstMethodSig(gims.GenericArguments.Select(ga => Resolve(ga)).ToArray()); + break; + } + default: throw new NotSupportedException(cs.ToString()); + } + return new FnPtrSig(ccs); + } - case ElementType.ValueArray: - { - var vas = (ValueArraySig)typeSig; - return new ValueArraySig(Resolve(vas.Next), vas.Size); - } - default: return typeSig; - } + case ElementType.ValueArray: + { + var vas = (ValueArraySig)typeSig; + return new ValueArraySig(Resolve(vas.Next), vas.Size); + } + default: return typeSig; + } } private TypeSig Resolve(List args, uint number) diff --git a/Editor/Meta/GenericClass.cs b/Editor/Meta/GenericClass.cs index 0479f6f..ee703ec 100644 --- a/Editor/Meta/GenericClass.cs +++ b/Editor/Meta/GenericClass.cs @@ -1,9 +1,30 @@ +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + using dnlib.DotNet; +using HybridCLR.Utils; using System.Collections.Generic; using System.Linq; using UnityEngine; -namespace HybridCLR.Editor.Meta +namespace HybridCLR.Meta { public class GenericClass { diff --git a/Editor/Meta/GenericMethod.cs b/Editor/Meta/GenericMethod.cs index 243aecb..e1e7e97 100644 --- a/Editor/Meta/GenericMethod.cs +++ b/Editor/Meta/GenericMethod.cs @@ -1,10 +1,30 @@ +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + using dnlib.DotNet; +using HybridCLR.Utils; using System; using System.Collections.Generic; using System.Linq; -using UnityEngine; -namespace HybridCLR.Editor.Meta +namespace HybridCLR.Meta { public class GenericMethod { @@ -64,7 +84,7 @@ namespace HybridCLR.Editor.Meta public MethodSpec ToMethodSpec() { - IMethodDefOrRef mt = KlassInst != null ? + IMethodDefOrRef mt = KlassInst != null ? (IMethodDefOrRef)new MemberRefUser(this.Method.Module, Method.Name, Method.MethodSig, new TypeSpecUser(new GenericInstSig(this.Method.DeclaringType.ToTypeSig().ToClassOrValueTypeSig(), this.KlassInst))) : this.Method; return new MethodSpecUser(mt, new GenericInstMethodSig(MethodInst)); diff --git a/Editor/Meta/IAssemblyResolver.cs b/Editor/Meta/IAssemblyResolver.cs deleted file mode 100644 index 25a6d42..0000000 --- a/Editor/Meta/IAssemblyResolver.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace HybridCLR.Editor.Meta -{ - public interface IAssemblyResolver - { - string ResolveAssembly(string assemblyName, bool throwExIfNotFind); - } -} diff --git a/Editor/Meta/MetaUtil.cs b/Editor/Meta/MetaUtil.cs deleted file mode 100644 index 2302540..0000000 --- a/Editor/Meta/MetaUtil.cs +++ /dev/null @@ -1,217 +0,0 @@ -using dnlib.DotNet; -using HybridCLR.Editor.Meta; -using HybridCLR.Editor.Settings; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using UnityEditor; - -namespace HybridCLR.Editor.Meta -{ - public static class MetaUtil - { - - public static bool EqualsTypeSig(TypeSig a, TypeSig b) - { - if (a == b) - { - return true; - } - if (a != null && b != null) - { - return TypeEqualityComparer.Instance.Equals(a, b); - } - return false; - } - - public static bool EqualsTypeSigArray(List a, List b) - { - if (a == b) - { - return true; - } - if (a != null && b != null) - { - if (a.Count != b.Count) - { - return false; - } - for (int i = 0; i < a.Count; i++) - { - if (!TypeEqualityComparer.Instance.Equals(a[i], b[i])) - { - return false; - } - } - return true; - } - return false; - } - - public static TypeSig Inflate(TypeSig sig, GenericArgumentContext ctx) - { - if (!sig.ContainsGenericParameter) - { - return sig; - } - return ctx.Resolve(sig); - } - - public static TypeSig ToShareTypeSig(ICorLibTypes corTypes, TypeSig typeSig) - { - var a = typeSig.RemovePinnedAndModifiers(); - switch (a.ElementType) - { - case ElementType.Void: return corTypes.Void; - case ElementType.Boolean: return corTypes.Byte; - case ElementType.Char: return corTypes.UInt16; - case ElementType.I1: return corTypes.SByte; - case ElementType.U1:return corTypes.Byte; - case ElementType.I2: return corTypes.Int16; - case ElementType.U2: return corTypes.UInt16; - case ElementType.I4: return corTypes.Int32; - case ElementType.U4: return corTypes.UInt32; - case ElementType.I8: return corTypes.Int64; - case ElementType.U8: return corTypes.UInt64; - case ElementType.R4: return corTypes.Single; - case ElementType.R8: return corTypes.Double; - case ElementType.String: return corTypes.Object; - case ElementType.TypedByRef: return corTypes.TypedReference; - case ElementType.I: return corTypes.IntPtr; - case ElementType.U: return corTypes.UIntPtr; - case ElementType.Object: return corTypes.Object; - case ElementType.Sentinel: return typeSig; - case ElementType.Ptr: return corTypes.UIntPtr; - case ElementType.ByRef: return corTypes.UIntPtr; - case ElementType.SZArray: return corTypes.Object; - case ElementType.Array: return corTypes.Object; - case ElementType.ValueType: - { - TypeDef typeDef = a.ToTypeDefOrRef().ResolveTypeDef(); - if (typeDef == null) - { - throw new Exception($"type:{a} definition could not be found"); - } - if (typeDef.IsEnum) - { - return ToShareTypeSig(corTypes, typeDef.GetEnumUnderlyingType()); - } - return typeSig; - } - case ElementType.Var: - case ElementType.MVar: - case ElementType.Class: return corTypes.Object; - case ElementType.GenericInst: - { - var gia = (GenericInstSig)a; - TypeDef typeDef = gia.GenericType.ToTypeDefOrRef().ResolveTypeDef(); - if (typeDef == null) - { - throw new Exception($"type:{a} definition could not be found"); - } - if (typeDef.IsEnum) - { - return ToShareTypeSig(corTypes, typeDef.GetEnumUnderlyingType()); - } - if (!typeDef.IsValueType) - { - return corTypes.Object; - } - return new GenericInstSig(gia.GenericType, gia.GenericArguments.Select(ga => ToShareTypeSig(corTypes, ga)).ToList()); - } - case ElementType.FnPtr: return corTypes.UIntPtr; - case ElementType.ValueArray: return typeSig; - case ElementType.Module: return typeSig; - default: - throw new NotSupportedException(typeSig.ToString()); - } - } - - public static List ToShareTypeSigs(ICorLibTypes corTypes, IList typeSigs) - { - if (typeSigs == null) - { - return null; - } - return typeSigs.Select(s => ToShareTypeSig(corTypes, s)).ToList(); - } - - public static IAssemblyResolver CreateHotUpdateAssemblyResolver(BuildTarget target, List hotUpdateDlls) - { - var externalDirs = HybridCLRSettings.Instance.externalHotUpdateAssembliyDirs; - var defaultHotUpdateOutputDir = SettingsUtil.GetHotUpdateDllsOutputDirByTarget(target); - IAssemblyResolver defaultHotUpdateResolver = new FixedSetAssemblyResolver(defaultHotUpdateOutputDir, hotUpdateDlls); - if (externalDirs == null || externalDirs.Length == 0) - { - return defaultHotUpdateResolver; - } - else - { - var resolvers = new List(); - foreach (var dir in externalDirs) - { - resolvers.Add(new FixedSetAssemblyResolver($"{dir}/{target}", hotUpdateDlls)); - resolvers.Add(new FixedSetAssemblyResolver(dir, hotUpdateDlls)); - } - resolvers.Add(defaultHotUpdateResolver); - return new CombinedAssemblyResolver(resolvers.ToArray()); - } - } - - public static IAssemblyResolver CreateAOTAssemblyResolver(BuildTarget target) - { - return new PathAssemblyResolver(SettingsUtil.GetAssembliesPostIl2CppStripDir(target)); - } - - public static IAssemblyResolver CreateHotUpdateAndAOTAssemblyResolver(BuildTarget target, List hotUpdateDlls) - { - return new CombinedAssemblyResolver( - CreateHotUpdateAssemblyResolver(target, hotUpdateDlls), - CreateAOTAssemblyResolver(target) - ); - } - - public static string ResolveNetStandardAssemblyPath(string assemblyName) - { - return $"{SettingsUtil.HybridCLRDataPathInPackage}/NetStandard/{assemblyName}.dll"; - } - - - public static List CreateDefaultGenericParams(ModuleDef module, int genericParamCount) - { - var methodGenericParams = new List(); - for (int i = 0; i < genericParamCount; i++) - { - methodGenericParams.Add(module.CorLibTypes.Object); - } - return methodGenericParams; - } - - public static bool IsSupportedPInvokeTypeSig(TypeSig typeSig) - { - typeSig = typeSig.RemovePinnedAndModifiers(); - if (typeSig.IsByRef) - { - return true; - } - switch (typeSig.ElementType) - { - case ElementType.SZArray: - case ElementType.Array: - //case ElementType.Class: - case ElementType.String: - //case ElementType.Object: - return false; - default: return true; - } - } - - public static bool IsSupportedPInvokeMethodSignature(MethodSig methodSig) - { - return IsSupportedPInvokeTypeSig(methodSig.RetType) && methodSig.Params.All(p => IsSupportedPInvokeTypeSig(p)); - } - } -} diff --git a/Editor/ABI/MethodDesc.cs b/Editor/Meta/MethodDesc.cs similarity index 56% rename from Editor/ABI/MethodDesc.cs rename to Editor/Meta/MethodDesc.cs index 6675f34..136e8b3 100644 --- a/Editor/ABI/MethodDesc.cs +++ b/Editor/Meta/MethodDesc.cs @@ -1,13 +1,29 @@ +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + using 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.Editor.ABI +namespace HybridCLR.Meta { public class MethodDesc : IEquatable { @@ -21,7 +37,7 @@ namespace HybridCLR.Editor.ABI public void Init() { - for(int i = 0; i < ParamInfos.Count; i++) + for (int i = 0; i < ParamInfos.Count; i++) { ParamInfos[i].Index = i; } @@ -31,7 +47,7 @@ namespace HybridCLR.Editor.ABI public void TransfromSigTypes(Func transformer) { ReturnInfo.Type = transformer(ReturnInfo.Type, true); - foreach(var paramType in ParamInfos) + foreach (var paramType in ParamInfos) { paramType.Type = transformer(paramType.Type, false); } @@ -41,7 +57,7 @@ namespace HybridCLR.Editor.ABI { var n = new StringBuilder(); n.Append(ReturnInfo.Type.CreateSigName()); - foreach(var param in ParamInfos) + foreach (var param in ParamInfos) { n.Append(param.Type.CreateSigName()); } diff --git a/Editor/ABI/MethodDesc.cs.meta b/Editor/Meta/MethodDesc.cs.meta similarity index 100% rename from Editor/ABI/MethodDesc.cs.meta rename to Editor/Meta/MethodDesc.cs.meta diff --git a/Editor/Meta/MethodReferenceAnalyzer.cs b/Editor/Meta/MethodReferenceAnalyzer.cs index bb36692..c302271 100644 --- a/Editor/Meta/MethodReferenceAnalyzer.cs +++ b/Editor/Meta/MethodReferenceAnalyzer.cs @@ -1,13 +1,29 @@ +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + using dnlib.DotNet; -using HybridCLR.Editor.ABI; using System; using System.Collections.Concurrent; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace HybridCLR.Editor.Meta +namespace HybridCLR.Meta { public class MethodReferenceAnalyzer { @@ -49,28 +65,28 @@ namespace HybridCLR.Editor.Meta } switch (inst.Operand) { - case IMethod met: + case IMethod met: + { + if (!met.IsMethod) { - if (!met.IsMethod) - { - continue; - } - var resolveMet = GenericMethod.ResolveMethod(met, ctx)?.ToGenericShare(); - if (resolveMet == null) - { - continue; - } - effectInsts.Add(met); - _onNewMethod(method, klassGenericInst, methodGenericInst, resolveMet); - break; + continue; } - case ITokenOperand token: + var resolveMet = GenericMethod.ResolveMethod(met, ctx)?.ToGenericShare(); + if (resolveMet == null) { - //GenericParamContext paramContext = method.HasGenericParameters || method.DeclaringType.HasGenericParameters ? - // new GenericParamContext(method.DeclaringType, method) : default; - //method.Module.ResolveToken(token.MDToken, paramContext); - break; + continue; } + effectInsts.Add(met); + _onNewMethod(method, klassGenericInst, methodGenericInst, resolveMet); + break; + } + case ITokenOperand token: + { + //GenericParamContext paramContext = method.HasGenericParameters || method.DeclaringType.HasGenericParameters ? + // new GenericParamContext(method.DeclaringType, method) : default; + //method.Module.ResolveToken(token.MDToken, paramContext); + break; + } } } _methodEffectInsts.TryAdd(method, effectInsts); diff --git a/Editor/Meta/ParamInfo.cs b/Editor/Meta/ParamInfo.cs new file mode 100644 index 0000000..b6af196 --- /dev/null +++ b/Editor/Meta/ParamInfo.cs @@ -0,0 +1,43 @@ +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +namespace HybridCLR.Meta +{ + + public class ParamInfo + { + public TypeInfo Type { get; set; } + + public int Index { get; set; } + + } + + public class ReturnInfo + { + public TypeInfo Type { get; set; } + + public bool IsVoid => Type.PorType == ParamOrReturnType.VOID; + + public override string ToString() + { + return Type.GetTypeName(); + } + } +} diff --git a/Editor/ABI/ParamInfo.cs.meta b/Editor/Meta/ParamInfo.cs.meta similarity index 100% rename from Editor/ABI/ParamInfo.cs.meta rename to Editor/Meta/ParamInfo.cs.meta diff --git a/Editor/Meta/ParamOrReturnType.cs b/Editor/Meta/ParamOrReturnType.cs new file mode 100644 index 0000000..e3a8294 --- /dev/null +++ b/Editor/Meta/ParamOrReturnType.cs @@ -0,0 +1,41 @@ +// 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.Meta +{ + public enum ParamOrReturnType + { + VOID, + I1, + U1, + I2, + U2, + I4, + U4, + I8, + U8, + R4, + R8, + I, + U, + TYPEDBYREF, + STRUCT, + } +} diff --git a/Editor/ABI/ParamOrReturnType.cs.meta b/Editor/Meta/ParamOrReturnType.cs.meta similarity index 100% rename from Editor/ABI/ParamOrReturnType.cs.meta rename to Editor/Meta/ParamOrReturnType.cs.meta diff --git a/Editor/Meta/PathAssemblyResolver.cs b/Editor/Meta/PathAssemblyResolver.cs deleted file mode 100644 index 1cfc376..0000000 --- a/Editor/Meta/PathAssemblyResolver.cs +++ /dev/null @@ -1,40 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using UnityEngine; - -namespace HybridCLR.Editor.Meta -{ - public class PathAssemblyResolver : AssemblyResolverBase - { - private readonly string[] _searchPaths; - public PathAssemblyResolver(params string[] searchPaths) - { - _searchPaths = searchPaths; - } - - protected override bool TryResolveAssembly(string assemblyName, out string assemblyPath) - { - foreach(var path in _searchPaths) - { - assemblyPath = Path.Combine(path, $"{assemblyName}.dll"); - if (File.Exists(assemblyPath)) - { - Debug.Log($"resolve {assemblyName} at {assemblyPath}"); - return true; - } - assemblyPath = Path.Combine(path, $"{assemblyName}.dll.bytes"); - if (File.Exists(assemblyPath)) - { - Debug.Log($"resolve {assemblyName} at {assemblyPath}"); - return true; - } - } - assemblyPath = null; - return false; - } - } -} diff --git a/Editor/Meta/TypeCreator.cs b/Editor/Meta/TypeCreator.cs new file mode 100644 index 0000000..a963bf5 --- /dev/null +++ b/Editor/Meta/TypeCreator.cs @@ -0,0 +1,117 @@ +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using dnlib.DotNet; +using System; +using System.Collections.Generic; + +namespace HybridCLR.Meta +{ + public class TypeCreator + { + private readonly Dictionary _typeInfoCache = new Dictionary(TypeEqualityComparer.Instance); + + private int _nextStructId = 0; + + public TypeInfo CreateTypeInfo(TypeSig type) + { + type = type.RemovePinnedAndModifiers(); + if (!_typeInfoCache.TryGetValue(type, out var typeInfo)) + { + typeInfo = CreateTypeInfo0(type); + _typeInfoCache.Add(type, typeInfo); + } + return typeInfo; + } + + TypeInfo CreateTypeInfo0(TypeSig type) + { + type = type.RemovePinnedAndModifiers(); + if (type.IsByRef) + { + return TypeInfo.s_u; + } + switch (type.ElementType) + { + case ElementType.Void: return TypeInfo.s_void; + case ElementType.Boolean: return TypeInfo.s_u1; + case ElementType.I1: return TypeInfo.s_i1; + case ElementType.U1: return TypeInfo.s_u1; + case ElementType.I2: return TypeInfo.s_i2; + case ElementType.Char: + case ElementType.U2: return TypeInfo.s_u2; + case ElementType.I4: return TypeInfo.s_i4; + case ElementType.U4: return TypeInfo.s_u4; + case ElementType.I8: return TypeInfo.s_i8; + case ElementType.U8: return TypeInfo.s_u8; + case ElementType.R4: return TypeInfo.s_r4; + case ElementType.R8: return TypeInfo.s_r8; + case ElementType.I: return TypeInfo.s_i; + case ElementType.U: + case ElementType.String: + case ElementType.Ptr: + case ElementType.ByRef: + case ElementType.Class: + case ElementType.Array: + case ElementType.SZArray: + case ElementType.FnPtr: + case ElementType.Object: + case ElementType.Module: + case ElementType.Var: + case ElementType.MVar: + return TypeInfo.s_u; + case ElementType.TypedByRef: return TypeInfo.s_typedByRef; + case ElementType.ValueType: + { + TypeDef typeDef = type.ToTypeDefOrRef().ResolveTypeDef(); + if (typeDef == null) + { + throw new Exception($"type:{type} definition could not be found. Please try `HybridCLR/Genergate/LinkXml`, then Build once to generate the AOT dll, and then regenerate the bridge function"); + } + if (typeDef.IsEnum) + { + return CreateTypeInfo(typeDef.GetEnumUnderlyingType()); + } + return CreateValueType(type); + } + case ElementType.GenericInst: + { + GenericInstSig gis = (GenericInstSig)type; + if (!gis.GenericType.IsValueType) + { + return TypeInfo.s_u; + } + TypeDef typeDef = gis.GenericType.ToTypeDefOrRef().ResolveTypeDef(); + if (typeDef.IsEnum) + { + return CreateTypeInfo(typeDef.GetEnumUnderlyingType()); + } + return CreateValueType(type); + } + default: throw new NotSupportedException($"{type.ElementType}"); + } + } + + protected TypeInfo CreateValueType(TypeSig type) + { + return new TypeInfo(ParamOrReturnType.STRUCT, type, _nextStructId++); + } + } +} diff --git a/Editor/ABI/TypeCreator.cs.meta b/Editor/Meta/TypeCreator.cs.meta similarity index 100% rename from Editor/ABI/TypeCreator.cs.meta rename to Editor/Meta/TypeCreator.cs.meta diff --git a/Editor/Meta/TypeInfo.cs b/Editor/Meta/TypeInfo.cs new file mode 100644 index 0000000..14ee8e4 --- /dev/null +++ b/Editor/Meta/TypeInfo.cs @@ -0,0 +1,134 @@ +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using dnlib.DotNet; +using System; + +namespace HybridCLR.Meta +{ + public class TypeInfo : IEquatable + { + + public static readonly TypeInfo s_void = new TypeInfo(ParamOrReturnType.VOID); + public static readonly TypeInfo s_i1 = new TypeInfo(ParamOrReturnType.I1); + public static readonly TypeInfo s_u1 = new TypeInfo(ParamOrReturnType.U1); + public static readonly TypeInfo s_i2 = new TypeInfo(ParamOrReturnType.I2); + public static readonly TypeInfo s_u2 = new TypeInfo(ParamOrReturnType.U2); + public static readonly TypeInfo s_i4 = new TypeInfo(ParamOrReturnType.I4); + public static readonly TypeInfo s_u4 = new TypeInfo(ParamOrReturnType.U4); + public static readonly TypeInfo s_i8 = new TypeInfo(ParamOrReturnType.I8); + public static readonly TypeInfo s_u8 = new TypeInfo(ParamOrReturnType.U8); + public static readonly TypeInfo s_r4 = new TypeInfo(ParamOrReturnType.R4); + public static readonly TypeInfo s_r8 = new TypeInfo(ParamOrReturnType.R8); + public static readonly TypeInfo s_i = new TypeInfo(ParamOrReturnType.I); + public static readonly TypeInfo s_u = new TypeInfo(ParamOrReturnType.U); + public static readonly TypeInfo s_typedByRef = new TypeInfo(ParamOrReturnType.TYPEDBYREF); + + public const string strTypedByRef = "typedbyref"; + + public TypeInfo(ParamOrReturnType portype, TypeSig klass = null, int typeId = 0) + { + PorType = portype; + Klass = klass; + _typeId = typeId; + } + + public ParamOrReturnType PorType { get; } + + public TypeSig Klass { get; } + + public bool IsStruct => PorType == ParamOrReturnType.STRUCT; + + public bool IsPrimitiveType => PorType <= ParamOrReturnType.U; + + private readonly int _typeId; + + public int TypeId => _typeId; + + public bool Equals(TypeInfo other) + { + return PorType == other.PorType && TypeEqualityComparer.Instance.Equals(Klass, other.Klass); + } + + public override bool Equals(object obj) + { + return Equals((TypeInfo)obj); + } + + public override int GetHashCode() + { + return (int)PorType * 23 + (Klass != null ? TypeEqualityComparer.Instance.GetHashCode(Klass) : 0); + } + + public bool NeedExpandValue() + { + return PorType >= ParamOrReturnType.I1 && PorType <= ParamOrReturnType.U2; + } + + public string CreateSigName() + { + switch (PorType) + { + case ParamOrReturnType.VOID: return "v"; + case ParamOrReturnType.I1: return "i1"; + case ParamOrReturnType.U1: return "u1"; + case ParamOrReturnType.I2: return "i2"; + case ParamOrReturnType.U2: return "u2"; + case ParamOrReturnType.I4: return "i4"; + case ParamOrReturnType.U4: return "u4"; + case ParamOrReturnType.I8: return "i8"; + case ParamOrReturnType.U8: return "u8"; + case ParamOrReturnType.R4: return "r4"; + case ParamOrReturnType.R8: return "r8"; + case ParamOrReturnType.I: return "i"; + case ParamOrReturnType.U: return "u"; + case ParamOrReturnType.TYPEDBYREF: return strTypedByRef; + case ParamOrReturnType.STRUCT: return $"s{_typeId}"; + default: throw new NotSupportedException(PorType.ToString()); + } + ; + } + + public string GetTypeName() + { + switch (PorType) + { + case ParamOrReturnType.VOID: return "void"; + case ParamOrReturnType.I1: return "int8_t"; + case ParamOrReturnType.U1: return "uint8_t"; + case ParamOrReturnType.I2: return "int16_t"; + case ParamOrReturnType.U2: return "uint16_t"; + case ParamOrReturnType.I4: return "int32_t"; + case ParamOrReturnType.U4: return "uint32_t"; + case ParamOrReturnType.I8: return "int64_t"; + case ParamOrReturnType.U8: return "uint64_t"; + case ParamOrReturnType.R4: return "float"; + case ParamOrReturnType.R8: return "double"; + case ParamOrReturnType.I: return "intptr_t"; + case ParamOrReturnType.U: return "uintptr_t"; + case ParamOrReturnType.TYPEDBYREF: return "Il2CppTypedRef"; + case ParamOrReturnType.STRUCT: return $"__struct_{_typeId}__"; + default: throw new NotImplementedException(PorType.ToString()); + } + ; + } + + } +} diff --git a/Editor/ABI/TypeInfo.cs.meta b/Editor/Meta/TypeInfo.cs.meta similarity index 100% rename from Editor/ABI/TypeInfo.cs.meta rename to Editor/Meta/TypeInfo.cs.meta diff --git a/Editor/MethodBridge/CallNativeMethodSignatureInfo.cs b/Editor/MethodBridge/CallNativeMethodSignatureInfo.cs deleted file mode 100644 index 566d9ba..0000000 --- a/Editor/MethodBridge/CallNativeMethodSignatureInfo.cs +++ /dev/null @@ -1,11 +0,0 @@ -using dnlib.DotNet; - -namespace HybridCLR.Editor.MethodBridge -{ - public class CallNativeMethodSignatureInfo - { - public MethodSig MethodSig { get; set; } - - public CallingConvention? Callvention { get; set; } - } -} diff --git a/Editor/MethodBridge/PInvokeAnalyzer.cs b/Editor/MethodBridge/PInvokeAnalyzer.cs deleted file mode 100644 index 51075e4..0000000 --- a/Editor/MethodBridge/PInvokeAnalyzer.cs +++ /dev/null @@ -1,68 +0,0 @@ -using dnlib.DotNet; -using HybridCLR.Editor.Meta; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Runtime.CompilerServices; -using System.Text; -using System.Threading.Tasks; -using UnityEngine; - -namespace HybridCLR.Editor.MethodBridge -{ - - public class PInvokeAnalyzer - { - private readonly List _rootModules = new List(); - - private readonly List _pinvokeMethodSignatures = new List(); - - public List PInvokeMethodSignatures => _pinvokeMethodSignatures; - - public PInvokeAnalyzer(AssemblyCache cache, List assemblyNames) - { - foreach (var assemblyName in assemblyNames) - { - _rootModules.Add(cache.LoadModule(assemblyName)); - } - } - - private CallingConvention GetCallingConvention(MethodDef method) - { - switch (method.ImplMap.CallConv) - { - case PInvokeAttributes.CallConvWinapi: return CallingConvention.Default; - case PInvokeAttributes.CallConvCdecl: return CallingConvention.C; - case PInvokeAttributes.CallConvStdCall: return CallingConvention.StdCall; - case PInvokeAttributes.CallConvThiscall: return CallingConvention.ThisCall; - case PInvokeAttributes.CallConvFastcall: return CallingConvention.FastCall; - default: return CallingConvention.Default; - } - } - - public void Run() - { - foreach (var mod in _rootModules) - { - foreach (TypeDef type in mod.GetTypes()) - { - foreach (MethodDef method in type.Methods) - { - if (method.IsPinvokeImpl) - { - if (!MetaUtil.IsSupportedPInvokeMethodSignature(method.MethodSig)) - { - Debug.LogError($"PInvoke method {method.FullName} has unsupported parameter or return type. Please check the method signature."); - } - _pinvokeMethodSignatures.Add(new CallNativeMethodSignatureInfo - { - MethodSig = method.MethodSig, - Callvention = method.HasImplMap? GetCallingConvention(method) : (CallingConvention?)null, - }); - } - } - } - } - } - } -} diff --git a/Editor/MethodBridge/PInvokeAnalyzer.cs.meta b/Editor/MethodBridge/PInvokeAnalyzer.cs.meta deleted file mode 100644 index 3d2ae8a..0000000 --- a/Editor/MethodBridge/PInvokeAnalyzer.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 9923175c961b78849aeaf99708e294ce -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/3rds/7zip.meta b/Editor/Mod.meta similarity index 77% rename from Editor/3rds/7zip.meta rename to Editor/Mod.meta index 48fedff..a0fecc0 100644 --- a/Editor/3rds/7zip.meta +++ b/Editor/Mod.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 08f44f6e8bfbc2c45afae7bdd2d7f21f +guid: 76ea6539f67705e47a9ff05e82726bd4 folderAsset: yes DefaultImporter: externalObjects: {} diff --git a/Editor/Mod/AssemblyCache.cs b/Editor/Mod/AssemblyCache.cs new file mode 100644 index 0000000..e3db591 --- /dev/null +++ b/Editor/Mod/AssemblyCache.cs @@ -0,0 +1,31 @@ +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +namespace HybridCLR.Mod +{ + public class AssemblyCache : AssemblyCacheBase + { + + public AssemblyCache(IAssemblyResolver assemblyResolver) : base(assemblyResolver) + { + + } + } +} diff --git a/Editor/Meta/AssemblyCache.cs.meta b/Editor/Mod/AssemblyCache.cs.meta similarity index 100% rename from Editor/Meta/AssemblyCache.cs.meta rename to Editor/Mod/AssemblyCache.cs.meta diff --git a/Editor/Meta/AssemblyCacheBase.cs b/Editor/Mod/AssemblyCacheBase.cs similarity index 73% rename from Editor/Meta/AssemblyCacheBase.cs rename to Editor/Mod/AssemblyCacheBase.cs index 04f2d15..fa8dbb1 100644 --- a/Editor/Meta/AssemblyCacheBase.cs +++ b/Editor/Mod/AssemblyCacheBase.cs @@ -1,12 +1,29 @@ +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + using dnlib.DotNet; -using System; +using HybridCLR.Utils; using System.Collections.Generic; using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace HybridCLR.Editor.Meta +namespace HybridCLR.Mod { public abstract class AssemblyCacheBase { diff --git a/Editor/Meta/AssemblyCacheBase.cs.meta b/Editor/Mod/AssemblyCacheBase.cs.meta similarity index 100% rename from Editor/Meta/AssemblyCacheBase.cs.meta rename to Editor/Mod/AssemblyCacheBase.cs.meta diff --git a/Editor/Mod/AssemblyResolverBase.cs b/Editor/Mod/AssemblyResolverBase.cs new file mode 100644 index 0000000..0b1281b --- /dev/null +++ b/Editor/Mod/AssemblyResolverBase.cs @@ -0,0 +1,49 @@ +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; + +namespace HybridCLR.Mod +{ + public abstract class AssemblyResolverBase : IAssemblyResolver + { + public string ResolveAssembly(string assemblyName, bool throwExIfNotFind) + { + if (TryResolveAssembly(assemblyName, out string assemblyPath)) + { + return assemblyPath; + } + if (throwExIfNotFind) + { + if (SettingsUtil.HotUpdateAssemblyNamesIncludePreserved.Contains(assemblyName)) + { + throw new Exception($"resolve Hot update dll:{assemblyName} failed! Please make sure that this hot update dll exists or the search path is configured in the external hot update path."); + } + else + { + throw new Exception($"resolve AOT dll:{assemblyName} failed! Please make sure that the AOT project has referenced the dll and generated the trimmed AOT dll correctly."); + } + } + return null; + } + + protected abstract bool TryResolveAssembly(string assemblyName, out string assemblyPath); + } +} diff --git a/Editor/Meta/AssemblyResolverBase.cs.meta b/Editor/Mod/AssemblyResolverBase.cs.meta similarity index 100% rename from Editor/Meta/AssemblyResolverBase.cs.meta rename to Editor/Mod/AssemblyResolverBase.cs.meta diff --git a/Editor/Mod/CombinedAssemblyResolver.cs b/Editor/Mod/CombinedAssemblyResolver.cs new file mode 100644 index 0000000..def6c72 --- /dev/null +++ b/Editor/Mod/CombinedAssemblyResolver.cs @@ -0,0 +1,47 @@ +// 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.Mod +{ + public class CombinedAssemblyResolver : AssemblyResolverBase + { + private readonly IAssemblyResolver[] _resolvers; + + public CombinedAssemblyResolver(params IAssemblyResolver[] resolvers) + { + _resolvers = resolvers; + } + + protected override bool TryResolveAssembly(string assemblyName, out string assemblyPath) + { + foreach (var resolver in _resolvers) + { + var assembly = resolver.ResolveAssembly(assemblyName, false); + if (assembly != null) + { + assemblyPath = assembly; + return true; + } + } + assemblyPath = null; + return false; + } + } +} diff --git a/Editor/Meta/CombinedAssemblyResolver.cs.meta b/Editor/Mod/CombinedAssemblyResolver.cs.meta similarity index 100% rename from Editor/Meta/CombinedAssemblyResolver.cs.meta rename to Editor/Mod/CombinedAssemblyResolver.cs.meta diff --git a/Editor/Meta/FixedSetAssemblyResolver.cs b/Editor/Mod/FixedSetAssemblyResolver.cs similarity index 51% rename from Editor/Meta/FixedSetAssemblyResolver.cs rename to Editor/Mod/FixedSetAssemblyResolver.cs index 8206553..4f2e626 100644 --- a/Editor/Meta/FixedSetAssemblyResolver.cs +++ b/Editor/Mod/FixedSetAssemblyResolver.cs @@ -1,12 +1,28 @@ -using System; -using System.Collections.Generic; +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System.Collections.Generic; using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using UnityEngine; -namespace HybridCLR.Editor.Meta +namespace HybridCLR.Mod { public class FixedSetAssemblyResolver : AssemblyResolverBase { diff --git a/Editor/Meta/FixedSetAssemblyResolver.cs.meta b/Editor/Mod/FixedSetAssemblyResolver.cs.meta similarity index 100% rename from Editor/Meta/FixedSetAssemblyResolver.cs.meta rename to Editor/Mod/FixedSetAssemblyResolver.cs.meta diff --git a/Editor/Mod/IAssemblyResolver.cs b/Editor/Mod/IAssemblyResolver.cs new file mode 100644 index 0000000..c6a6288 --- /dev/null +++ b/Editor/Mod/IAssemblyResolver.cs @@ -0,0 +1,27 @@ +// 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.Mod +{ + public interface IAssemblyResolver + { + string ResolveAssembly(string assemblyName, bool throwExIfNotFind); + } +} diff --git a/Editor/Meta/IAssemblyResolver.cs.meta b/Editor/Mod/IAssemblyResolver.cs.meta similarity index 100% rename from Editor/Meta/IAssemblyResolver.cs.meta rename to Editor/Mod/IAssemblyResolver.cs.meta diff --git a/Editor/Mod/PathAssemblyResolver.cs b/Editor/Mod/PathAssemblyResolver.cs new file mode 100644 index 0000000..377419a --- /dev/null +++ b/Editor/Mod/PathAssemblyResolver.cs @@ -0,0 +1,55 @@ +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System.IO; +using UnityEngine; + +namespace HybridCLR.Mod +{ + public class PathAssemblyResolver : AssemblyResolverBase + { + private readonly string[] _searchPaths; + public PathAssemblyResolver(params string[] searchPaths) + { + _searchPaths = searchPaths; + } + + protected override bool TryResolveAssembly(string assemblyName, out string assemblyPath) + { + foreach (var path in _searchPaths) + { + assemblyPath = Path.Combine(path, $"{assemblyName}.dll"); + if (File.Exists(assemblyPath)) + { + Debug.Log($"resolve {assemblyName} at {assemblyPath}"); + return true; + } + assemblyPath = Path.Combine(path, $"{assemblyName}.dll.bytes"); + if (File.Exists(assemblyPath)) + { + Debug.Log($"resolve {assemblyName} at {assemblyPath}"); + return true; + } + } + assemblyPath = null; + return false; + } + } +} diff --git a/Editor/Meta/PathAssemblyResolver.cs.meta b/Editor/Mod/PathAssemblyResolver.cs.meta similarity index 100% rename from Editor/Meta/PathAssemblyResolver.cs.meta rename to Editor/Mod/PathAssemblyResolver.cs.meta diff --git a/Editor/Settings/HybridCLRSettingProvider.cs b/Editor/Settings/HybridCLRSettingProvider.cs index 51ecb3b..ec0c60f 100644 --- a/Editor/Settings/HybridCLRSettingProvider.cs +++ b/Editor/Settings/HybridCLRSettingProvider.cs @@ -1,87 +1,55 @@ -using System; -using System.Reflection; +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + using UnityEditor; -using UnityEditor.Presets; -using UnityEngine; using UnityEngine.UIElements; -namespace HybridCLR.Editor.Settings +namespace HybridCLR.Settings { public class HybridCLRSettingsProvider : SettingsProvider { - private SerializedObject _serializedObject; - private SerializedProperty _enable; - private SerializedProperty _useGlobalIl2cpp; - private SerializedProperty _hybridclrRepoURL; - private SerializedProperty _il2cppPlusRepoURL; - private SerializedProperty _hotUpdateAssemblyDefinitions; - private SerializedProperty _hotUpdateAssemblies; - private SerializedProperty _preserveHotUpdateAssemblies; - private SerializedProperty _hotUpdateDllCompileOutputRootDir; - private SerializedProperty _externalHotUpdateAssemblyDirs; - private SerializedProperty _strippedAOTDllOutputRootDir; - private SerializedProperty _patchAOTAssemblies; - private SerializedProperty _outputLinkFile; - private SerializedProperty _outputAOTGenericReferenceFile; - private SerializedProperty _maxGenericReferenceIteration; - private SerializedProperty _maxMethodBridgeGenericIteration; + private static HybridCLRSettingsProvider s_provider; - public HybridCLRSettingsProvider() : base("Project/HybridCLR Settings", SettingsScope.Project) { } + [SettingsProvider] + public static SettingsProvider CreateMyCustomSettingsProvider() + { + if (s_provider == null) + { + s_provider = new HybridCLRSettingsProvider(); + } + + return s_provider; + } + + private SerializedObject _serializedObject; + + public HybridCLRSettingsProvider() : base("Project/HybridCLR Settings", SettingsScope.Project) + { + } public override void OnActivate(string searchContext, VisualElement rootElement) { InitGUI(); - } - - private void InitGUI() - { - var setting = HybridCLRSettings.LoadOrCreate(); - _serializedObject?.Dispose(); - _serializedObject = new SerializedObject(setting); - _enable = _serializedObject.FindProperty("enable"); - _useGlobalIl2cpp = _serializedObject.FindProperty("useGlobalIl2cpp"); - _hybridclrRepoURL = _serializedObject.FindProperty("hybridclrRepoURL"); - _il2cppPlusRepoURL = _serializedObject.FindProperty("il2cppPlusRepoURL"); - _hotUpdateAssemblyDefinitions = _serializedObject.FindProperty("hotUpdateAssemblyDefinitions"); - _hotUpdateAssemblies = _serializedObject.FindProperty("hotUpdateAssemblies"); - _preserveHotUpdateAssemblies = _serializedObject.FindProperty("preserveHotUpdateAssemblies"); - _hotUpdateDllCompileOutputRootDir = _serializedObject.FindProperty("hotUpdateDllCompileOutputRootDir"); - _externalHotUpdateAssemblyDirs = _serializedObject.FindProperty("externalHotUpdateAssembliyDirs"); - _strippedAOTDllOutputRootDir = _serializedObject.FindProperty("strippedAOTDllOutputRootDir"); - _patchAOTAssemblies = _serializedObject.FindProperty("patchAOTAssemblies"); - _outputLinkFile = _serializedObject.FindProperty("outputLinkFile"); - _outputAOTGenericReferenceFile = _serializedObject.FindProperty("outputAOTGenericReferenceFile"); - _maxGenericReferenceIteration = _serializedObject.FindProperty("maxGenericReferenceIteration"); - _maxMethodBridgeGenericIteration = _serializedObject.FindProperty("maxMethodBridgeGenericIteration"); - } - - public override void OnGUI(string searchContext) - { - if (_serializedObject == null || !_serializedObject.targetObject) + using (var so = new SerializedObject(HybridCLRSettings.instance)) { - InitGUI(); - } - _serializedObject.Update(); - EditorGUI.BeginChangeCheck(); - EditorGUILayout.PropertyField(_enable); - EditorGUILayout.PropertyField(_hybridclrRepoURL); - EditorGUILayout.PropertyField(_il2cppPlusRepoURL); - EditorGUILayout.PropertyField(_useGlobalIl2cpp); - EditorGUILayout.PropertyField(_hotUpdateAssemblyDefinitions); - EditorGUILayout.PropertyField(_hotUpdateAssemblies); - EditorGUILayout.PropertyField(_preserveHotUpdateAssemblies); - EditorGUILayout.PropertyField(_hotUpdateDllCompileOutputRootDir); - EditorGUILayout.PropertyField(_externalHotUpdateAssemblyDirs); - EditorGUILayout.PropertyField(_strippedAOTDllOutputRootDir); - EditorGUILayout.PropertyField(_patchAOTAssemblies); - EditorGUILayout.PropertyField(_outputLinkFile); - EditorGUILayout.PropertyField(_outputAOTGenericReferenceFile); - EditorGUILayout.PropertyField(_maxGenericReferenceIteration); - EditorGUILayout.PropertyField(_maxMethodBridgeGenericIteration); - if (EditorGUI.EndChangeCheck()) - { - _serializedObject.ApplyModifiedProperties(); - HybridCLRSettings.Save(); + keywords = GetSearchKeywordsFromSerializedObject(so); } } @@ -91,16 +59,45 @@ namespace HybridCLR.Editor.Settings HybridCLRSettings.Save(); } - static HybridCLRSettingsProvider s_provider; - - [SettingsProvider] - public static SettingsProvider CreateMyCustomSettingsProvider() + private void InitGUI() { - if (s_provider == null) + var setting = HybridCLRSettings.instance; + _serializedObject?.Dispose(); + _serializedObject = new SerializedObject(setting); + } + + public override void OnGUI(string searchContext) + { + if (_serializedObject == null || !_serializedObject.targetObject) { - s_provider = new HybridCLRSettingsProvider(); + InitGUI(); + } + + _serializedObject.Update(); + EditorGUI.BeginChangeCheck(); + + using (var prop = _serializedObject.GetIterator()) + { + if (prop.NextVisible(true)) + { + do + { + if (prop.name == "m_Script") + { + continue; + } + + EditorGUILayout.PropertyField(prop, true); + } + while (prop.NextVisible(false)); + } + } + + if (EditorGUI.EndChangeCheck()) + { + _serializedObject.ApplyModifiedProperties(); + HybridCLRSettings.Save(); } - return s_provider; } } -} \ No newline at end of file +} diff --git a/Editor/Settings/HybridCLRSettings.cs b/Editor/Settings/HybridCLRSettings.cs index f577a95..46cd467 100644 --- a/Editor/Settings/HybridCLRSettings.cs +++ b/Editor/Settings/HybridCLRSettings.cs @@ -1,12 +1,35 @@ -using System.IO; +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using HybridCLR.CodeGen.Link; +using UnityEditor; using UnityEditorInternal; using UnityEngine; -namespace HybridCLR.Editor.Settings +namespace HybridCLR.Settings { - public class HybridCLRSettings : ScriptableObject + [FilePath("ProjectSettings/HybridCLRSettings.asset", FilePathAttribute.Location.ProjectFolder)] + public class HybridCLRSettings : ScriptableSingleton { + [Tooltip("enable HybridCLR")] public bool enable = true; @@ -28,23 +51,17 @@ namespace HybridCLR.Editor.Settings [Tooltip("preserved hot update assembly names(without .dll suffix)")] public string[] preserveHotUpdateAssemblies; - [Tooltip("output directory of compiling hot update assemblies")] - public string hotUpdateDllCompileOutputRootDir = "HybridCLRData/HotUpdateDlls"; - [Tooltip("searching paths of external hot update assemblies")] public string[] externalHotUpdateAssembliyDirs; - [Tooltip("output directory of stripped AOT assemblies")] - public string strippedAOTDllOutputRootDir = "HybridCLRData/AssembliesPostIl2CppStrip"; - - [Tooltip("supplementary metadata assembly names(without .dll suffix)")] - public string[] patchAOTAssemblies; + [Tooltip("preserve level when generating link.xml. PreserveAllOfDeclaringType keeps whole referenced types (safer, larger). PreserveExactMember keeps only referenced fields/methods/properties/events (smaller).")] + public LinkPreserveLevel linkPreserveLevel = LinkPreserveLevel.PreserveAllOfDeclaringType; [Tooltip("output file of automatic generated link.xml by scanning hot update assemblies")] - public string outputLinkFile = "HybridCLRGenerate/link.xml"; + public string outputLinkFile = "HybridCLR/Generate/link.xml"; [Tooltip("output file of automatic generated AOTGenericReferences.cs")] - public string outputAOTGenericReferenceFile = "HybridCLRGenerate/AOTGenericReferences.cs"; + public string outputAOTGenericReferenceFile = "HybridCLR/Generate/AOTGenericReferences.cs"; [Tooltip("max iteration count of searching generic methods in hot update assemblies")] public int maxGenericReferenceIteration = 10; @@ -52,47 +69,14 @@ namespace HybridCLR.Editor.Settings [Tooltip("max iteration count of searching method bridge generic methods in AOT assemblies")] public int maxMethodBridgeGenericIteration = 10; - - - private static HybridCLRSettings s_Instance; - - public static HybridCLRSettings Instance - { - get - { - if (!s_Instance) - { - LoadOrCreate(); - } - return s_Instance; - } - } - - private static string GetFilePath() - { - return "ProjectSettings/HybridCLRSettings.asset"; - } - - public static HybridCLRSettings LoadOrCreate() - { - string filePath = GetFilePath(); - Object[] objs = InternalEditorUtility.LoadSerializedFileAndForget(filePath); - s_Instance = objs.Length > 0 ? (HybridCLRSettings)objs[0] : (s_Instance ?? CreateInstance()); - return s_Instance; - } - public static void Save() { - if (!s_Instance) + if (!instance) { return; } - string filePath = GetFilePath(); - string directoryName = Path.GetDirectoryName(filePath); - Directory.CreateDirectory(directoryName); - var obj = new Object[1] { s_Instance }; - InternalEditorUtility.SaveToSerializedFileAndForget(obj, filePath, true); + instance.Save(true); } } } diff --git a/Editor/Settings/MenuProvider.cs b/Editor/Settings/MenuProvider.cs deleted file mode 100644 index 906b089..0000000 --- a/Editor/Settings/MenuProvider.cs +++ /dev/null @@ -1,39 +0,0 @@ -using HybridCLR.Editor.Installer; -using UnityEditor; -using UnityEngine; - -namespace HybridCLR.Editor.Settings -{ - public static class MenuProvider - { - - [MenuItem("HybridCLR/About", priority = 0)] - public static void OpenAbout() => Application.OpenURL("https://www.hybridclr.cn/docs/intro"); - - [MenuItem("HybridCLR/Installer...", priority = 60)] - private static void Open() - { - InstallerWindow window = EditorWindow.GetWindow("HybridCLR Installer", true); - window.minSize = new Vector2(800f, 500f); - } - - [MenuItem("HybridCLR/Settings...", priority = 61)] - public static void OpenSettings() => SettingsService.OpenProjectSettings("Project/HybridCLR Settings"); - - [MenuItem("HybridCLR/Documents/Quick Start")] - public static void OpenQuickStart() => Application.OpenURL("https://www.hybridclr.cn/docs/beginner/quickstart"); - - [MenuItem("HybridCLR/Documents/Performance")] - public static void OpenPerformance() => Application.OpenURL("https://www.hybridclr.cn/docs/basic/performance"); - - [MenuItem("HybridCLR/Documents/FAQ")] - public static void OpenFAQ() => Application.OpenURL("https://www.hybridclr.cn/docs/help/faq"); - - [MenuItem("HybridCLR/Documents/Common Errors")] - public static void OpenCommonErrors() => Application.OpenURL("https://www.hybridclr.cn/docs/help/commonerrors"); - - [MenuItem("HybridCLR/Documents/Bug Report")] - public static void OpenBugReport() => Application.OpenURL("https://www.hybridclr.cn/docs/help/issue"); - } - -} \ No newline at end of file diff --git a/Editor/Template.meta b/Editor/Template.meta deleted file mode 100644 index f2430d5..0000000 --- a/Editor/Template.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 9af6345cc5ab1ae4a81262ab4b537911 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/Template/FileRegionReplace.cs b/Editor/Template/FileRegionReplace.cs deleted file mode 100644 index 797477b..0000000 --- a/Editor/Template/FileRegionReplace.cs +++ /dev/null @@ -1,74 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace HybridCLR.Editor.Template -{ - public class FileRegionReplace - { - private readonly string _tplCode; - - private readonly Dictionary _regionReplaceContents = new Dictionary(); - - public FileRegionReplace(string tplCode) - { - _tplCode = tplCode; - } - - public void Replace(string regionName, string regionContent) - { - _regionReplaceContents.Add(regionName, regionContent); - } - - public string GenFinalString() - { - string originContent = _tplCode; - - string resultContent = originContent; - - foreach (var c in _regionReplaceContents) - { - resultContent = ReplaceRegion(resultContent, c.Key, c.Value); - } - return resultContent; - } - - public void Commit(string outputFile) - { - string dir = Path.GetDirectoryName(outputFile); - Directory.CreateDirectory(dir); - string resultContent = GenFinalString(); - var utf8WithoutBOM = new System.Text.UTF8Encoding(false); - File.WriteAllText(outputFile, resultContent, utf8WithoutBOM); - } - - public static string ReplaceRegion(string resultText, string region, string replaceContent) - { - int startIndex = resultText.IndexOf("//!!!{{" + region); - if (startIndex == -1) - { - throw new Exception($"region:{region} start not find"); - } - int endIndex = resultText.IndexOf("//!!!}}" + region); - if (endIndex == -1) - { - throw new Exception($"region:{region} end not find"); - } - int replaceStart = resultText.IndexOf('\n', startIndex); - int replaceEnd = resultText.LastIndexOf('\n', endIndex); - if (replaceStart == -1 || replaceEnd == -1) - { - throw new Exception($"region:{region} not find"); - } - if (resultText.Substring(replaceStart, replaceEnd - replaceStart) == replaceContent) - { - return resultText; - } - resultText = resultText.Substring(0, replaceStart) + "\n" + replaceContent + "\n" + resultText.Substring(replaceEnd); - return resultText; - } - } -} diff --git a/Editor/Template/FileRegionReplace.cs.meta b/Editor/Template/FileRegionReplace.cs.meta deleted file mode 100644 index 14a642a..0000000 --- a/Editor/Template/FileRegionReplace.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 15d4563ad83546c42bc65c99be9bd54a -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/3rds/7zip/Common.meta b/Editor/Utils.meta similarity index 77% rename from Editor/3rds/7zip/Common.meta rename to Editor/Utils.meta index 0e4cc9e..e380a5c 100644 --- a/Editor/3rds/7zip/Common.meta +++ b/Editor/Utils.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 5cedddbfa873eb94496b496e2a3ce8aa +guid: c27fe11625b7eee46847a83a9897fdc0 folderAsset: yes DefaultImporter: externalObjects: {} diff --git a/Editor/Utils/BashUtil.cs b/Editor/Utils/BashUtil.cs new file mode 100644 index 0000000..6b6587e --- /dev/null +++ b/Editor/Utils/BashUtil.cs @@ -0,0 +1,74 @@ +// 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.Diagnostics; +using System.Linq; + +namespace HybridCLR.Installer +{ + public static class BashUtil + { + public static int RunCommand(string workingDir, string program, string[] args, bool log = true) + { + using (Process p = new Process()) + { + p.StartInfo.WorkingDirectory = workingDir; + p.StartInfo.FileName = program; + p.StartInfo.UseShellExecute = false; + p.StartInfo.CreateNoWindow = true; + string argsStr = string.Join(" ", args.Select(arg => "\"" + arg + "\"")); + p.StartInfo.Arguments = argsStr; + if (log) + { + UnityEngine.Debug.Log($"[BashUtil] run => {program} {argsStr}"); + } + p.Start(); + p.WaitForExit(); + return p.ExitCode; + } + } + + + public static (int ExitCode, string StdOut, string StdErr) RunCommand2(string workingDir, string program, string[] args, bool log = true) + { + using (Process p = new Process()) + { + p.StartInfo.WorkingDirectory = workingDir; + p.StartInfo.FileName = program; + p.StartInfo.UseShellExecute = false; + p.StartInfo.CreateNoWindow = true; + p.StartInfo.RedirectStandardOutput = true; + p.StartInfo.RedirectStandardError = true; + string argsStr = string.Join(" ", args); + p.StartInfo.Arguments = argsStr; + if (log) + { + UnityEngine.Debug.Log($"[BashUtil] run => {program} {argsStr}"); + } + p.Start(); + p.WaitForExit(); + + string stdOut = p.StandardOutput.ReadToEnd(); + string stdErr = p.StandardError.ReadToEnd(); + return (p.ExitCode, stdOut, stdErr); + } + } + } +} diff --git a/Editor/Installer/BashUtil.cs.meta b/Editor/Utils/BashUtil.cs.meta similarity index 100% rename from Editor/Installer/BashUtil.cs.meta rename to Editor/Utils/BashUtil.cs.meta diff --git a/Editor/Utils/DirectoryUtil.cs b/Editor/Utils/DirectoryUtil.cs new file mode 100644 index 0000000..b353ce2 --- /dev/null +++ b/Editor/Utils/DirectoryUtil.cs @@ -0,0 +1,93 @@ +// 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.IO; +using System.Threading; + +namespace HybridCLR.Utils +{ + public class DirectoryUtil + { + public static void RemoveDir(string dir, bool log = false) + { + if (log) + { + UnityEngine.Debug.Log($"RemoveDir dir:{dir}"); + } + + int maxTryCount = 5; + for (int i = 0; i < maxTryCount; ++i) + { + try + { + if (!Directory.Exists(dir)) + { + return; + } + foreach (var file in Directory.GetFiles(dir)) + { + File.SetAttributes(file, FileAttributes.Normal); + File.Delete(file); + } + foreach (var subDir in Directory.GetDirectories(dir)) + { + RemoveDir(subDir); + } + Directory.Delete(dir, true); + break; + } + catch (Exception e) + { + UnityEngine.Debug.LogError($"RemoveDir:{dir} with exception:{e}. try count:{i}"); + Thread.Sleep(100); + } + } + } + + public static void RecreateDir(string dir) + { + if (Directory.Exists(dir)) + { + RemoveDir(dir, true); + } + Directory.CreateDirectory(dir); + } + + public static void CopyDir(string src, string dst, bool log = false) + { + if (log) + { + UnityEngine.Debug.Log($"[BashUtil] CopyDir {src} => {dst}"); + } + if (Directory.Exists(dst)) + { + RemoveDir(dst); + } + else + { + string parentDir = Path.GetDirectoryName(Path.GetFullPath(dst)); + Directory.CreateDirectory(parentDir); + } + + UnityEditor.FileUtil.CopyFileOrDirectory(src, dst); + } + } +} diff --git a/Editor/3rds/7zip/Common/CRC.cs.meta b/Editor/Utils/DirectoryUtil.cs.meta similarity index 83% rename from Editor/3rds/7zip/Common/CRC.cs.meta rename to Editor/Utils/DirectoryUtil.cs.meta index e366fdf..073301d 100644 --- a/Editor/3rds/7zip/Common/CRC.cs.meta +++ b/Editor/Utils/DirectoryUtil.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: d0bb58ecc915d9d47b8567adaa2d0ca6 +guid: 43a8b86a1416b6f418d1ead448e7ebb9 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Editor/Utils/HashUtil.cs b/Editor/Utils/HashUtil.cs new file mode 100644 index 0000000..148c563 --- /dev/null +++ b/Editor/Utils/HashUtil.cs @@ -0,0 +1,44 @@ +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using dnlib.DotNet; +using System.Collections.Generic; + +namespace HybridCLR +{ + public static class HashUtil + { + public static int CombineHash(int hash1, int hash2) + { + return hash1 * 1566083941 + hash2; + } + + public static int ComputHash(List sigs) + { + int hash = 135781321; + TypeEqualityComparer tc = TypeEqualityComparer.Instance; + foreach (var sig in sigs) + { + hash = hash * 1566083941 + tc.GetHashCode(sig); + } + return hash; + } + } +} diff --git a/Editor/HashUtil.cs.meta b/Editor/Utils/HashUtil.cs.meta similarity index 83% rename from Editor/HashUtil.cs.meta rename to Editor/Utils/HashUtil.cs.meta index 9cdce22..42a10e8 100644 --- a/Editor/HashUtil.cs.meta +++ b/Editor/Utils/HashUtil.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 5d4ae4a5c0bba49469c525887d812717 +guid: 4db1429642a79b24ba0c91b80ff9290c MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Editor/Utils/MetaUtil.cs b/Editor/Utils/MetaUtil.cs new file mode 100644 index 0000000..4859088 --- /dev/null +++ b/Editor/Utils/MetaUtil.cs @@ -0,0 +1,236 @@ +// 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.Mod; +using HybridCLR.Settings; +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEditor; +using IAssemblyResolver = HybridCLR.Mod.IAssemblyResolver; + +namespace HybridCLR.Utils +{ + public static class MetaUtil + { + + public static bool EqualsTypeSig(TypeSig a, TypeSig b) + { + if (a == b) + { + return true; + } + if (a != null && b != null) + { + return TypeEqualityComparer.Instance.Equals(a, b); + } + return false; + } + + public static bool EqualsTypeSigArray(List a, List b) + { + if (a == b) + { + return true; + } + if (a != null && b != null) + { + if (a.Count != b.Count) + { + return false; + } + for (int i = 0; i < a.Count; i++) + { + if (!TypeEqualityComparer.Instance.Equals(a[i], b[i])) + { + return false; + } + } + return true; + } + return false; + } + + public static TypeSig Inflate(TypeSig sig, GenericArgumentContext ctx) + { + if (!sig.ContainsGenericParameter) + { + return sig; + } + return ctx.Resolve(sig); + } + + public static TypeSig ToShareTypeSig(ICorLibTypes corTypes, TypeSig typeSig) + { + var a = typeSig.RemovePinnedAndModifiers(); + switch (a.ElementType) + { + case ElementType.Void: return corTypes.Void; + case ElementType.Boolean: return corTypes.Byte; + case ElementType.Char: return corTypes.UInt16; + case ElementType.I1: return corTypes.SByte; + case ElementType.U1: return corTypes.Byte; + case ElementType.I2: return corTypes.Int16; + case ElementType.U2: return corTypes.UInt16; + case ElementType.I4: return corTypes.Int32; + case ElementType.U4: return corTypes.UInt32; + case ElementType.I8: return corTypes.Int64; + case ElementType.U8: return corTypes.UInt64; + case ElementType.R4: return corTypes.Single; + case ElementType.R8: return corTypes.Double; + case ElementType.String: return corTypes.Object; + case ElementType.TypedByRef: return corTypes.TypedReference; + case ElementType.I: return corTypes.IntPtr; + case ElementType.U: return corTypes.UIntPtr; + case ElementType.Object: return corTypes.Object; + case ElementType.Sentinel: return typeSig; + case ElementType.Ptr: return corTypes.UIntPtr; + case ElementType.ByRef: return corTypes.UIntPtr; + case ElementType.SZArray: return corTypes.Object; + case ElementType.Array: return corTypes.Object; + case ElementType.ValueType: + { + TypeDef typeDef = a.ToTypeDefOrRef().ResolveTypeDef(); + if (typeDef == null) + { + throw new Exception($"type:{a} definition could not be found"); + } + if (typeDef.IsEnum) + { + return ToShareTypeSig(corTypes, typeDef.GetEnumUnderlyingType()); + } + return typeSig; + } + case ElementType.Var: + case ElementType.MVar: + case ElementType.Class: return corTypes.Object; + case ElementType.GenericInst: + { + var gia = (GenericInstSig)a; + TypeDef typeDef = gia.GenericType.ToTypeDefOrRef().ResolveTypeDef(); + if (typeDef == null) + { + throw new Exception($"type:{a} definition could not be found"); + } + if (typeDef.IsEnum) + { + return ToShareTypeSig(corTypes, typeDef.GetEnumUnderlyingType()); + } + if (!typeDef.IsValueType) + { + return corTypes.Object; + } + return new GenericInstSig(gia.GenericType, gia.GenericArguments.Select(ga => ToShareTypeSig(corTypes, ga)).ToList()); + } + case ElementType.FnPtr: return corTypes.UIntPtr; + case ElementType.ValueArray: return typeSig; + case ElementType.Module: return typeSig; + default: + throw new NotSupportedException(typeSig.ToString()); + } + } + + public static List ToShareTypeSigs(ICorLibTypes corTypes, IList typeSigs) + { + if (typeSigs == null) + { + return null; + } + return typeSigs.Select(s => ToShareTypeSig(corTypes, s)).ToList(); + } + + public static IAssemblyResolver CreateHotUpdateAssemblyResolver(BuildTarget target, List hotUpdateDlls) + { + var externalDirs = HybridCLRSettings.instance.externalHotUpdateAssembliyDirs; + var defaultHotUpdateOutputDir = SettingsUtil.GetHotUpdateDllsOutputDirByTarget(target); + IAssemblyResolver defaultHotUpdateResolver = new FixedSetAssemblyResolver(defaultHotUpdateOutputDir, hotUpdateDlls); + if (externalDirs == null || externalDirs.Length == 0) + { + return defaultHotUpdateResolver; + } + else + { + var resolvers = new List(); + foreach (var dir in externalDirs) + { + resolvers.Add(new FixedSetAssemblyResolver($"{dir}/{target}", hotUpdateDlls)); + resolvers.Add(new FixedSetAssemblyResolver(dir, hotUpdateDlls)); + } + resolvers.Add(defaultHotUpdateResolver); + return new CombinedAssemblyResolver(resolvers.ToArray()); + } + } + + public static IAssemblyResolver CreateAOTAssemblyResolver(BuildTarget target) + { + return new PathAssemblyResolver(SettingsUtil.GetAssembliesPostIl2CppStripDir(target)); + } + + public static IAssemblyResolver CreateHotUpdateAndAOTAssemblyResolver(BuildTarget target, List hotUpdateDlls) + { + return new CombinedAssemblyResolver( + CreateHotUpdateAssemblyResolver(target, hotUpdateDlls), + CreateAOTAssemblyResolver(target) + ); + } + + public static string ResolveNetStandardAssemblyPath(string assemblyName) + { + return $"{SettingsUtil.HybridCLRDataPathInPackage}/NetStandard/{assemblyName}.dll"; + } + + + public static List CreateDefaultGenericParams(ModuleDef module, int genericParamCount) + { + var methodGenericParams = new List(); + for (int i = 0; i < genericParamCount; i++) + { + methodGenericParams.Add(module.CorLibTypes.Object); + } + return methodGenericParams; + } + + public static bool IsSupportedPInvokeTypeSig(TypeSig typeSig) + { + typeSig = typeSig.RemovePinnedAndModifiers(); + if (typeSig.IsByRef) + { + return true; + } + switch (typeSig.ElementType) + { + case ElementType.SZArray: + case ElementType.Array: + //case ElementType.Class: + case ElementType.String: + //case ElementType.Object: + return false; + default: return true; + } + } + + public static bool IsSupportedPInvokeMethodSignature(MethodSig methodSig) + { + return IsSupportedPInvokeTypeSig(methodSig.RetType) && methodSig.Params.All(p => IsSupportedPInvokeTypeSig(p)); + } + } +} diff --git a/Editor/Meta/MetaUtil.cs.meta b/Editor/Utils/MetaUtil.cs.meta similarity index 83% rename from Editor/Meta/MetaUtil.cs.meta rename to Editor/Utils/MetaUtil.cs.meta index d9342a4..c8842d4 100644 --- a/Editor/Meta/MetaUtil.cs.meta +++ b/Editor/Utils/MetaUtil.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: f3dbfe2e8b6a92742b18e287c5d281dd +guid: 83d88438e4ad9d94088cdc3cc08e51a1 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Editor/SettingsUtil.cs b/Editor/Utils/SettingsUtil.cs similarity index 63% rename from Editor/SettingsUtil.cs rename to Editor/Utils/SettingsUtil.cs index 0aaa269..4d6a249 100644 --- a/Editor/SettingsUtil.cs +++ b/Editor/Utils/SettingsUtil.cs @@ -1,26 +1,44 @@ -using System; +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using HybridCLR.Settings; +using System; using System.Collections.Generic; using System.IO; using System.Linq; using UnityEditor; using UnityEditorInternal; using UnityEngine; -using HybridCLR.Editor.Settings; -namespace HybridCLR.Editor +namespace HybridCLR { public static class SettingsUtil { - public static bool Enable - { - get => HybridCLRSettings.Instance.enable; - set - { - HybridCLRSettings.Instance.enable = value; - HybridCLRSettings.Save(); - } - } + + + private const string HybridCLRDataPath = "Library/HybridCLR"; + private const string CompiledDllOutputDirName = "HotUpdateDlls"; + private const string StripedAotDllOutputDirName = "AssembliesPostIl2CppStrip"; + + public static string ProjectDir { get; } = Directory.GetParent(Application.dataPath).ToString(); public static string PackageName { get; } = "com.code-philosophy.hybridclr"; @@ -28,15 +46,9 @@ namespace HybridCLR.Editor public static string TemplatePathInPackage => $"{HybridCLRDataPathInPackage}/Templates"; - public static string ProjectDir { get; } = Directory.GetParent(Application.dataPath).ToString(); - public static string ScriptingAssembliesJsonFile { get; } = "ScriptingAssemblies.json"; - public static string HotUpdateDllsRootOutputDir => HybridCLRSettings.Instance.hotUpdateDllCompileOutputRootDir; - - public static string AssembliesPostIl2CppStripDir => HybridCLRSettings.Instance.strippedAOTDllOutputRootDir; - - public static string HybridCLRDataDir => $"{ProjectDir}/HybridCLRData"; + public static string HybridCLRDataDir => $"{ProjectDir}/{HybridCLRDataPath}"; public static string LocalUnityDataDir => $"{HybridCLRDataDir}/LocalIl2CppData-{Application.platform}"; @@ -44,20 +56,24 @@ namespace HybridCLR.Editor public static string GeneratedCppDir => $"{LocalIl2CppDir}/libil2cpp/hybridclr/generated"; - public static string Il2CppBuildCacheDir { get; } = $"{ProjectDir}/Library/Il2cppBuildCache"; - - public static string GlobalgamemanagersBinFile { get; } = "globalgamemanagers"; - - public static string Dataunity3dBinFile { get; } = "data.unity3d"; - public static string GetHotUpdateDllsOutputDirByTarget(BuildTarget target) { - return $"{HotUpdateDllsRootOutputDir}/{target}"; + return $"{HybridCLRDataDir}/{CompiledDllOutputDirName}/{target}"; } public static string GetAssembliesPostIl2CppStripDir(BuildTarget target) { - return $"{AssembliesPostIl2CppStripDir}/{target}"; + return $"{HybridCLRDataDir}/{StripedAotDllOutputDirName}/{target}"; + } + + public static bool Enable + { + get => HybridCLRSettings.instance.enable; + set + { + HybridCLRSettings.instance.enable = value; + HybridCLRSettings.Save(); + } } class AssemblyDefinitionData @@ -69,7 +85,7 @@ namespace HybridCLR.Editor { get { - var gs = HybridCLRSettings.Instance; + var gs = HybridCLRSettings.instance; var hotfixAssNames = (gs.hotUpdateAssemblyDefinitions ?? Array.Empty()).Select(ad => JsonUtility.FromJson(ad.text)); var hotfixAssembles = new List(); @@ -90,7 +106,7 @@ namespace HybridCLR.Editor get { List allAsses = HotUpdateAssemblyNamesExcludePreserved; - string[] preserveAssemblyNames = HybridCLRSettings.Instance.preserveHotUpdateAssemblies; + string[] preserveAssemblyNames = HybridCLRSettings.instance.preserveHotUpdateAssemblies; if (preserveAssemblyNames != null && preserveAssemblyNames.Length > 0) { foreach (var assemblyName in preserveAssemblyNames) @@ -109,8 +125,6 @@ namespace HybridCLR.Editor public static List HotUpdateAssemblyFilesIncludePreserved => HotUpdateAssemblyNamesIncludePreserved.Select(ass => ass + ".dll").ToList(); - public static List AOTAssemblyNames => HybridCLRSettings.Instance.patchAOTAssemblies.ToList(); - - public static HybridCLRSettings HybridCLRSettings => HybridCLRSettings.Instance; + public static HybridCLRSettings HybridCLRSettings => HybridCLRSettings.instance; } } diff --git a/Editor/SettingsUtil.cs.meta b/Editor/Utils/SettingsUtil.cs.meta similarity index 83% rename from Editor/SettingsUtil.cs.meta rename to Editor/Utils/SettingsUtil.cs.meta index 323dcf6..1fe0acb 100644 --- a/Editor/SettingsUtil.cs.meta +++ b/Editor/Utils/SettingsUtil.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 381c08faeafbc004f97504eeba87380d +guid: 6d7f0f5453492484880e4f509d49febb MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Editor/Utils/XcodeProjectFileUtil.cs b/Editor/Utils/XcodeProjectFileUtil.cs new file mode 100644 index 0000000..a76c854 --- /dev/null +++ b/Editor/Utils/XcodeProjectFileUtil.cs @@ -0,0 +1,44 @@ +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System.IO; +using UnityEditor.Build; + +namespace HybridCLR.Utils +{ + + public static class XcodeProjectFileUtil + { + + public static string GetXcodeProjectFile(string pathToBuiltProject) + { + foreach (string dir in Directory.GetDirectories(pathToBuiltProject, "*.xcodeproj", SearchOption.TopDirectoryOnly)) + { + string pbxprojFile = $"{dir}/project.pbxproj"; + if (File.Exists(pbxprojFile)) + { + return pbxprojFile; + } + } + throw new BuildFailedException($"can't find xxxx.xcodeproj/project.pbxproj in {pathToBuiltProject}"); + } + } +} + diff --git a/Editor/BuildProcessors/BuildProcessorUtil.cs.meta b/Editor/Utils/XcodeProjectFileUtil.cs.meta similarity index 100% rename from Editor/BuildProcessors/BuildProcessorUtil.cs.meta rename to Editor/Utils/XcodeProjectFileUtil.cs.meta diff --git a/Plugins/LZ4.dll b/Plugins/LZ4.dll deleted file mode 100644 index f1aeba3..0000000 Binary files a/Plugins/LZ4.dll and /dev/null differ diff --git a/Plugins/LZ4.dll.meta b/Plugins/LZ4.dll.meta deleted file mode 100644 index 527366c..0000000 --- a/Plugins/LZ4.dll.meta +++ /dev/null @@ -1,87 +0,0 @@ -fileFormatVersion: 2 -guid: ca69cf4ffd628394a9dd1ef1c56f7f20 -PluginImporter: - externalObjects: {} - serializedVersion: 2 - iconMap: {} - executionOrder: {} - defineConstraints: [] - isPreloaded: 0 - isOverridable: 1 - isExplicitlyReferenced: 0 - validateReferences: 1 - platformData: - - first: - : Any - second: - enabled: 0 - settings: - Exclude Android: 1 - Exclude Editor: 0 - Exclude Linux64: 1 - Exclude OSXUniversal: 1 - Exclude WebGL: 1 - Exclude Win: 1 - Exclude Win64: 1 - Exclude iOS: 1 - - first: - Android: Android - second: - enabled: 0 - settings: - CPU: ARMv7 - - first: - Any: - second: - enabled: 0 - settings: {} - - first: - Editor: Editor - second: - enabled: 1 - settings: - CPU: AnyCPU - DefaultValueInitialized: true - OS: AnyOS - - first: - Standalone: Linux64 - second: - enabled: 0 - settings: - CPU: None - - first: - Standalone: OSXUniversal - second: - enabled: 0 - settings: - CPU: None - - first: - Standalone: Win - second: - enabled: 0 - settings: - CPU: None - - first: - Standalone: Win64 - second: - enabled: 0 - settings: - CPU: None - - first: - Windows Store Apps: WindowsStoreApps - second: - enabled: 0 - settings: - CPU: AnyCPU - - first: - iPhone: iOS - second: - enabled: 0 - settings: - AddToEmbeddedBinaries: false - CPU: AnyCPU - CompileFlags: - FrameworkDependencies: - userData: - assetBundleName: - assetBundleVariant: diff --git a/README.md b/README.md index 70e4e00..d418b40 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@

-**中文** | [English](./README_EN.md) +[README 中文](./README.md) | [README English](./README_EN.md) [Github](https://github.com/focus-creative-games/hybridclr) | [Gitee](https://gitee.com/focus-creative-games/hybridclr) @@ -25,8 +25,6 @@ HybridCLR扩充了il2cpp运行时代码,使它由纯[AOT](https://en.wikipedia - [快速上手](https://www.hybridclr.cn/docs/beginner/quickstart) - [商业项目案例](https://www.hybridclr.cn/docs/other/businesscase) - [LeanCLR](https://github.com/focus-creative-games/leanclr) -- HybridCLR 原生集成脚本方案: Lua-[ZLua](https://github.com/focus-creative-games/zlua)/Typescript-[ZenTS](https://github.com/focus-creative-games/zen-ts) -- 代码混淆工具 [Obfuz](https://github.com/focus-creative-games/obfuz) ## 特性 @@ -78,7 +76,7 @@ HybridCLR已经被广泛验证是非常高效、稳定的Unity热更新解决方 - 新手1群(3000人):428404198(满) - 新手2群(2000人):680274677(满) - 新手3群(2000人):**920714552(推荐)** -- discord频道: +- discord频道 `https://discord.gg/BATfNfJnm2` - 商业合作邮箱: business#code-philosophy.com - [商业化支持](https://www.hybridclr.cn/docs/business/intro) diff --git a/README_EN.md b/README_EN.md index a869209..e92cc44 100644 --- a/README_EN.md +++ b/README_EN.md @@ -1,3 +1,7 @@ + +- [README Chinese](./README.md) +- [README English](./README_EN.md) + # HybridCLR [![license](http://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/focus-creative-games/hybridclr/blob/main/LICENSE) @@ -7,8 +11,6 @@

-[中文](./README.md) | **English** - HybridCLR is a **feature-complete, zero-cost, high-performance, low-memory** **near-perfect** Unity cross-platform native C# hot update solution. HybridCLR extends the il2cpp runtime code, transforming it from a pure [AOT](https://en.wikipedia.org/wiki/Ahead-of-time_compilation) runtime to an AOT+Interpreter hybrid runtime, thereby natively supporting the dynamic loading of assemblies and fundamentally supporting hot updates from the bottom layer. Games using HybridCLR technology can not only run efficiently on the Android platform but also on all platforms supported by il2cpp, including iOS, Consoles, WebGL, etc. @@ -23,8 +25,6 @@ Welcome to embrace modern native C# hot update technology! - [Quick Start](https://www.hybridclr.cn/en/docs/beginner/quickstart) - [Business Project Cases](https://www.hybridclr.cn/en/docs/other/businesscase) - [LeanCLR](https://github.com/focus-creative-games/leanclr) -- HybridCLR native scripting solutions: Lua-[ZLua](https://github.com/focus-creative-games/zlua)/Typescript-[ZenTS](https://github.com/focus-creative-games/zen-ts) -- Code obfuscation tool [Obfuz](https://github.com/focus-creative-games/obfuz) ## Features @@ -74,7 +74,7 @@ You can view the [list of known top companies using HybridCLR and their launched - Beginner Group 1: 428404198 (Full) - Beginner Group 2: 680274677 (Full) - Beginner Group 3: **920714552 (Recommended)** -- Discord channel: +- Discord channel https://discord.gg/BATfNfJnm2 - Business cooperation email: business#code-philosophy.com - [Commercial Support](https://www.hybridclr.cn/en/docs/business/intro) @@ -86,7 +86,7 @@ LeanCLR can be embedded independently into any app or game project and published ## About the Author -**walon**: Founder of **Code Philosophy (代码哲学)** +**walon**: Founder of **Code Philosophy** Graduated from the Department of Physics at Tsinghua University, gold medalist of the 2006 CMO, member of the National Mathematical Olympiad Training Team, and sent to the Basic Science Class of Tsinghua. Focused on game technology, proficient in development architecture and basic technical infrastructure. diff --git a/RELEASELOG.md b/RELEASELOG.md index 267f135..fd54efa 100644 --- a/RELEASELOG.md +++ b/RELEASELOG.md @@ -1,42 +1,5 @@ # ReleaseLog -## 8.15.0 - -Release Data: 2026-09-29. - -### Runtime - -- fix: Reject not-fully-instantiated types during IL transform -- fix: align explicit interface method override across runtimes -- fix: fix regression bug comes from commit `SHA-1: b11fb5daa6ff2737619bd3b7ef6602d2b34dc3f8 * new: add test case for computing interface vtable implement when re-implements interface in child class.`, leading to interface methods were implicit override by not-public virtual methods. -- refactor: change type of MethodInfo::initInterpCallMethodPointer/isInterpterImpl from bool:1 to uint8_t:1 so all flag fields can be packed in 1 byte. - -### Editor - -- refactor: InstallerController find max-lower-bound version as best match version - -## 8.14.1 - -Release Data: 2026-08-18. - -### Editor - -- fix: fix InstallerController install branch 6000.3.x on 6000.5.x incorrectly - -## 8.14.0 - -Release Data: 2026-08-18. - -### Runtime - -- feat: **support 6000.5.x** -- fix: handle invalid nested type name which contains namespace in custom attribute generated by burst, which lead to TypeNameParser::Parse fail -- fix(tuanjie): Class::SetupEventsLocked call SetupMethods when disable IL2CPP_ENABLE_LAZY_INIT - -### Editor - -- feat: installer support 6000.5.x - ## 8.13.0 Release Data: 2026-08-02. @@ -551,7 +514,7 @@ Release Date: 2024-7-25. ### Editor - [fix] Fixes the bug where `GenerateMethodBridge` did not consider `ClassLayout`, `Layout`, and `FieldOffset` factors when calculating equivalent classes. -- [fix] Fixes the bug where `PatchScriptingAssembliesJsonHook` throws an异常 when the `Library/PlayerDataCache` directory does not exist. +- [fix] Fixes the bug where `PatchScriptingAssembliesJsonHook` throws an exception when the `Library/PlayerDataCache` directory does not exist. ## 6.3.0 @@ -745,7 +708,7 @@ Release Date: 2024-1-2. - [fix] Fixes the serious bug where the size of the instance of a not fully instantiated generic class is calculated as `sizeof(void*)`, resulting in an invalid and excessively large instance. This causes an error when using the generic base class instance to overwrite the instance type value set during `LayoutFieldsLocked` in `UpdateInstanceSizeForGenericClass`. - [change] Supports printing hot update stacks, although the order is not quite correct. - [change] Replaces IL2CPP_MALLOC with HYBRIDCLR_MALLOC and similar allocation functions. -- [refactor] Refactorizes the Config interface to统一ly retrieve and set options through `GetRuntimeOption` and `SetRuntimeOption`. +- [refactor] Refactorizes the Config interface to uniformly retrieve and set options through `GetRuntimeOption` and `SetRuntimeOption`. - [opt] Removes unnecessary memset operations on structures for `NewValueTypeVar` and `NewValueTypeInterpVar` instructions. ### Editor @@ -777,9 +740,9 @@ Release Date: 2023-11-27. - [fix] Fixes the bug where `ConvertInvokeArgs` might pass non-aligned args, causing `CopyStackObject` to crash on platforms like armv7 that require memory alignment. - [fix] Fixes the serious bug where calculating `ClassFieldLayout` when the size is specified by `StructLayout`. -- [fix] Fixes the bug where instructions like `bgt` do not double-negate the judgment, causing incorrect branch execution when comparing floating-point numbers with NaN due to不对称性. +- [fix] Fixes the bug where instructions like `bgt` do not double-negate the judgment, causing incorrect branch execution when comparing floating-point numbers with NaN due to asymmetry. - [fix] Fixes the serious bug where `Class::FromGenericParameter` incorrectly sets `thread_static_fields_size=-1`, causing ThreadStatic memory allocation for it. -- [opt] Allocates `Il2CppGenericInst`统一ly using `MetadataCache::GetGenericInst` to allocate unique pool objects, optimizing memory allocation. +- [opt] Allocates `Il2CppGenericInst` uniformly using `MetadataCache::GetGenericInst` to allocate unique pool objects, optimizing memory allocation. - [opt] Since some Il2CppGenericInst in the Interpreter uses `MetadataCache::GetGenericInst` uniformly, compare `Il2CppGenericContext` by directly comparing class_inst and method_inst pointers. ### Editor @@ -1134,7 +1097,7 @@ Release Date: 2023-07-03. ### Editor -- [fix] Fixes the遗漏 RELEASELOG.md.meta file issue. +- [fix] Fixes the missing RELEASELOG.md.meta file issue. ## 2.4.0 diff --git a/Runtime/HomologousImageMode.cs b/Runtime/HomologousImageMode.cs index f244856..e47c30b 100644 --- a/Runtime/HomologousImageMode.cs +++ b/Runtime/HomologousImageMode.cs @@ -1,10 +1,30 @@ +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. +  namespace HybridCLR { public enum HomologousImageMode - { - Consistent, - SuperSet, - } + { + Consistent, + SuperSet, + } } diff --git a/Runtime/HybridCLR.Runtime.asmdef b/Runtime/HybridCLR.Runtime.asmdef index 98f5d3e..03bcdb3 100644 --- a/Runtime/HybridCLR.Runtime.asmdef +++ b/Runtime/HybridCLR.Runtime.asmdef @@ -1,6 +1,6 @@ { "name": "HybridCLR.Runtime", - "rootNamespace": "", + "rootNamespace": "HybridCLR", "references": [], "includePlatforms": [], "excludePlatforms": [], diff --git a/Runtime/LoadImageErrorCode.cs b/Runtime/LoadImageErrorCode.cs index d327810..7fb4664 100644 --- a/Runtime/LoadImageErrorCode.cs +++ b/Runtime/LoadImageErrorCode.cs @@ -1,10 +1,30 @@ +// Copyright 2026 Code Philosophy +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. +  namespace HybridCLR { public enum LoadImageErrorCode - { - OK = 0, - BAD_IMAGE, // invalid dll file + { + OK = 0, + BAD_IMAGE, // invalid dll file NOT_IMPLEMENT, // not implement feature AOT_ASSEMBLY_NOT_FIND, // AOT assembly not found HOMOLOGOUS_ONLY_SUPPORT_AOT_ASSEMBLY, // can not load supplementary metadata assembly for non-AOT assembly diff --git a/Runtime/ReversePInvokeWrapperGenerationAttribute.cs b/Runtime/ReversePInvokeWrapperGenerationAttribute.cs index 3308313..00c3d47 100644 --- a/Runtime/ReversePInvokeWrapperGenerationAttribute.cs +++ b/Runtime/ReversePInvokeWrapperGenerationAttribute.cs @@ -1,8 +1,24 @@ +// 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; namespace HybridCLR { diff --git a/Runtime/RuntimeApi.cs b/Runtime/RuntimeApi.cs index 1ee67bb..c9f154a 100644 --- a/Runtime/RuntimeApi.cs +++ b/Runtime/RuntimeApi.cs @@ -1,12 +1,27 @@ +// 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.Reflection; using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Text; -using System.Threading.Tasks; -using UnityEditor; using UnityEngine.Scripting; namespace HybridCLR diff --git a/Runtime/RuntimeOptionId.cs b/Runtime/RuntimeOptionId.cs index 25c3417..f4e9db3 100644 --- a/Runtime/RuntimeOptionId.cs +++ b/Runtime/RuntimeOptionId.cs @@ -1,3 +1,23 @@ +// 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 { public enum RuntimeOptionId diff --git a/package.json b/package.json index 8a16ac4..251cf7e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "com.code-philosophy.hybridclr", - "version": "8.15.0", + "version": "9.0.0", "displayName": "HybridCLR", "description": "HybridCLR is a fully featured, zero-cost, high-performance, low-memory solution for Unity's all-platform native c# hotupdate.", "category": "Scripting",