diff --git a/UnityProject/Assets/GameScripts/HotFix/GameLogic/GameApp.cs b/UnityProject/Assets/GameScripts/HotFix/GameLogic/GameApp.cs index f6877d2f..df4954be 100644 --- a/UnityProject/Assets/GameScripts/HotFix/GameLogic/GameApp.cs +++ b/UnityProject/Assets/GameScripts/HotFix/GameLogic/GameApp.cs @@ -1,6 +1,9 @@ using System.Collections.Generic; using System.Reflection; using GameLogic; +#if ENABLE_OBFUZ +using Obfuz; +#endif using TEngine; #pragma warning disable CS0436 @@ -8,6 +11,9 @@ using TEngine; /// /// 游戏App。 /// +#if ENABLE_OBFUZ +[ObfuzIgnore] +#endif public partial class GameApp { private static List _hotfixAssembly; @@ -23,12 +29,13 @@ public partial class GameApp Log.Warning("======= 看到此条日志代表你成功运行了热更新代码 ======="); Log.Warning("======= Entrance GameApp ======="); Utility.Unity.AddDestroyListener(Release); + Log.Warning("======= StartGameLogic ======="); StartGameLogic(); } private static void StartGameLogic() { - GameEvent.Get().ShowLoginUI(); + // GameEvent.Get().ShowLoginUI(); GameModule.UI.ShowUIAsync(); } diff --git a/UnityProject/Assets/GameScripts/HotFix/GameLogic/GameLogic.asmdef b/UnityProject/Assets/GameScripts/HotFix/GameLogic/GameLogic.asmdef index 675be791..adc437b8 100644 --- a/UnityProject/Assets/GameScripts/HotFix/GameLogic/GameLogic.asmdef +++ b/UnityProject/Assets/GameScripts/HotFix/GameLogic/GameLogic.asmdef @@ -10,7 +10,8 @@ "GUID:47f9fc774596be54ebfed7739cd70c86", "GUID:1aa3e8589868c80499255710874679c0", "GUID:d8b63aba1907145bea998dd612889d6b", - "GUID:756335c0388f7114790e504ed368ae1d" + "GUID:756335c0388f7114790e504ed368ae1d", + "GUID:4140bd2e2764f1f47ab93125ecb61942" ], "includePlatforms": [], "excludePlatforms": [], diff --git a/UnityProject/Assets/GameScripts/HotFix/GameLogic/UI/BattleMainUI/BattleMainUI.cs b/UnityProject/Assets/GameScripts/HotFix/GameLogic/UI/BattleMainUI/BattleMainUI.cs index 12557c87..7c19fd7d 100644 --- a/UnityProject/Assets/GameScripts/HotFix/GameLogic/UI/BattleMainUI/BattleMainUI.cs +++ b/UnityProject/Assets/GameScripts/HotFix/GameLogic/UI/BattleMainUI/BattleMainUI.cs @@ -1,9 +1,8 @@ using UnityEngine; -using UnityEngine.UI; -using TEngine; namespace GameLogic { + [Obfuz.ObfuzIgnore(Obfuz.ObfuzScope.TypeName)] [Window(UILayer.UI)] class BattleMainUI : UIWindow { diff --git a/UnityProject/Assets/Obfuz/SymbolObfus/symbol-mapping.xml b/UnityProject/Assets/Obfuz/SymbolObfus/symbol-mapping.xml index 510f5e90..7525a61b 100644 --- a/UnityProject/Assets/Obfuz/SymbolObfus/symbol-mapping.xml +++ b/UnityProject/Assets/Obfuz/SymbolObfus/symbol-mapping.xml @@ -7,21 +7,21 @@ - + - - + + - - + + - + @@ -34,7 +34,7 @@ - + @@ -42,7 +42,7 @@ - + @@ -140,26 +140,6 @@ - - - - - - - - - - - - - - - - - - - - @@ -176,7 +156,6 @@ - @@ -186,7 +165,6 @@ - @@ -194,11 +172,8 @@ - - - @@ -213,19 +188,15 @@ - - - - @@ -237,28 +208,8 @@ - - - - - - - - - - - - - - - - - - - - @@ -349,6 +300,7 @@ + @@ -373,6 +325,7 @@ + @@ -409,6 +362,7 @@ + @@ -487,6 +441,7 @@ + @@ -516,6 +471,7 @@ + @@ -533,6 +489,7 @@ + @@ -666,9 +623,6 @@ - - - @@ -683,7 +637,6 @@ - @@ -753,7 +706,6 @@ - @@ -773,19 +725,13 @@ - - - - - - - - - - - - - + + + + + + + @@ -835,7 +781,7 @@ - + @@ -928,7 +874,7 @@ - + @@ -1284,6 +1230,466 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -5470,6 +5876,7 @@ + @@ -7120,6 +7527,7 @@ + @@ -7177,6 +7585,7 @@ + @@ -7480,6 +7889,7 @@ + @@ -7489,6 +7899,7 @@ + @@ -7496,6 +7907,7 @@ + @@ -7522,6 +7934,7 @@ + @@ -7529,6 +7942,7 @@ + @@ -8065,6 +8479,7 @@ + @@ -8116,6 +8531,7 @@ + @@ -8123,6 +8539,7 @@ + @@ -8134,6 +8551,7 @@ + @@ -8144,6 +8562,7 @@ + @@ -8163,6 +8582,7 @@ + @@ -8313,6 +8733,7 @@ + @@ -8322,6 +8743,7 @@ + @@ -8333,6 +8755,7 @@ + @@ -8347,6 +8770,7 @@ + @@ -8363,6 +8787,7 @@ + @@ -8378,6 +8803,7 @@ + @@ -8393,6 +8819,7 @@ + @@ -8401,6 +8828,7 @@ + @@ -8546,6 +8974,7 @@ + @@ -8560,6 +8989,7 @@ + @@ -8570,6 +9000,7 @@ + @@ -8708,6 +9139,7 @@ + @@ -8715,6 +9147,7 @@ + @@ -8722,6 +9155,7 @@ + @@ -8912,6 +9346,7 @@ + @@ -9006,6 +9441,7 @@ + @@ -9015,6 +9451,7 @@ + @@ -9024,6 +9461,7 @@ + @@ -9031,6 +9469,7 @@ + @@ -9372,18 +9811,21 @@ + + + \ No newline at end of file diff --git a/UnityProject/Packages/com.code-philosophy.hybridclr/Data~/hybridclr_version.json b/UnityProject/Packages/com.code-philosophy.hybridclr/Data~/hybridclr_version.json index afda70ec..93672f79 100644 --- a/UnityProject/Packages/com.code-philosophy.hybridclr/Data~/hybridclr_version.json +++ b/UnityProject/Packages/com.code-philosophy.hybridclr/Data~/hybridclr_version.json @@ -2,37 +2,37 @@ "versions": [ { "unity_version":"2019", - "hybridclr" : { "branch":"v8.3.0"}, + "hybridclr" : { "branch":"v8.4.0"}, "il2cpp_plus": { "branch":"v2019-8.1.0"} }, { "unity_version":"2020", - "hybridclr" : { "branch":"v8.3.0"}, + "hybridclr" : { "branch":"v8.4.0"}, "il2cpp_plus": { "branch":"v2020-8.1.0"} }, { "unity_version":"2021", - "hybridclr" : { "branch":"v8.3.0"}, + "hybridclr" : { "branch":"v8.4.0"}, "il2cpp_plus": { "branch":"v2021-8.1.0"} }, { "unity_version":"2022", - "hybridclr" : { "branch":"v8.3.0"}, + "hybridclr" : { "branch":"v8.4.0"}, "il2cpp_plus": { "branch":"v2022-8.2.0"} }, { "unity_version":"2022-tuanjie", - "hybridclr" : { "branch":"v8.3.0"}, + "hybridclr" : { "branch":"v8.4.0"}, "il2cpp_plus": { "branch":"v2022-tuanjie-8.3.0"} }, { "unity_version":"2023", - "hybridclr" : { "branch":"v8.3.0"}, + "hybridclr" : { "branch":"v8.4.0"}, "il2cpp_plus": { "branch":"v2023-8.1.0"} }, { "unity_version":"6000", - "hybridclr" : { "branch":"v8.3.0"}, + "hybridclr" : { "branch":"v8.4.0"}, "il2cpp_plus": { "branch":"v6000-8.1.0"} } ] diff --git a/UnityProject/Packages/com.code-philosophy.hybridclr/Editor/Commands/StripAOTDllCommand.cs b/UnityProject/Packages/com.code-philosophy.hybridclr/Editor/Commands/StripAOTDllCommand.cs index 8e6560a9..09a6f73a 100644 --- a/UnityProject/Packages/com.code-philosophy.hybridclr/Editor/Commands/StripAOTDllCommand.cs +++ b/UnityProject/Packages/com.code-philosophy.hybridclr/Editor/Commands/StripAOTDllCommand.cs @@ -136,8 +136,8 @@ namespace HybridCLR.Editor.Commands options = buildOptions, target = target, targetGroup = BuildPipeline.GetBuildTargetGroup(target), -#if UNITY_2021_1_OR_NEWER - subtarget = (int)EditorUserBuildSettings.standaloneBuildSubtarget, +#if UNITY_SERVER + subtarget = (int)StandaloneBuildSubtarget.Server, #endif }; diff --git a/UnityProject/Packages/com.code-philosophy.hybridclr/RELEASELOG.md b/UnityProject/Packages/com.code-philosophy.hybridclr/RELEASELOG.md index 372cb43f..8cf8136f 100644 --- a/UnityProject/Packages/com.code-philosophy.hybridclr/RELEASELOG.md +++ b/UnityProject/Packages/com.code-philosophy.hybridclr/RELEASELOG.md @@ -1,5 +1,20 @@ # ReleaseLog +## 8.4.0 + +Release Date: 2025-07-26. + +### Runtime + +- **[new] IMPORTANT! support custom image format** +- [change] the type of field `offset` of ldsfld, stfld, ldthreadlocalfld、stthreadlocalfld changed from uint16_t to uint32_t so that supports class with huge static fields. +- [opt] optimize to use NewValueTypeVar_Ctor_0 for new zero-argument value type and System.Activator.CreateInstance<T>() +- [opt] optimize new ValueType with zero arguments. + +### Editor + +- [fix] fix the issue that `Texture Compression` option in Build Settings was changed after running `HybridCLR/Generate/All` on Android platform + ## 8.3.0 Release Date: 2025-07-04. diff --git a/UnityProject/Packages/com.code-philosophy.hybridclr/Runtime/LoadImageErrorCode.cs b/UnityProject/Packages/com.code-philosophy.hybridclr/Runtime/LoadImageErrorCode.cs index 93d4b386..d3278101 100644 --- a/UnityProject/Packages/com.code-philosophy.hybridclr/Runtime/LoadImageErrorCode.cs +++ b/UnityProject/Packages/com.code-philosophy.hybridclr/Runtime/LoadImageErrorCode.cs @@ -11,6 +11,9 @@ namespace HybridCLR HOMOLOGOUS_ASSEMBLY_HAS_LOADED, // can not load supplementary metadata assembly for the same assembly INVALID_HOMOLOGOUS_MODE, // invalid homologous image mode PDB_BAD_FILE, // invalid pdb file + UNKNOWN_IMAGE_FORMAT, + UNSUPPORT_FORMAT_VERSION, + UNMATCH_FORMAT_VARIANT, }; } diff --git a/UnityProject/Packages/com.code-philosophy.hybridclr/package.json b/UnityProject/Packages/com.code-philosophy.hybridclr/package.json index 47508adf..196808c7 100644 --- a/UnityProject/Packages/com.code-philosophy.hybridclr/package.json +++ b/UnityProject/Packages/com.code-philosophy.hybridclr/package.json @@ -1,6 +1,6 @@ { "name": "com.code-philosophy.hybridclr", - "version": "8.3.0", + "version": "8.4.0", "displayName": "HybridCLR", "description": "HybridCLR is a fully featured, zero-cost, high-performance, low-memory solution for Unity's all-platform native c# hotupdate.", "category": "Scripting", diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor.meta deleted file mode 100644 index e4fe3a4d..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 2326b426d539e084dbddf7f7c23ed1bd -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Conf.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Conf.meta deleted file mode 100644 index d42ac4f6..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Conf.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 241df8eaf3a34dc47a0873c37ddb2695 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Conf/XmlAssemblyTypeMethodRuleParser.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Conf/XmlAssemblyTypeMethodRuleParser.cs deleted file mode 100644 index 8b349974..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Conf/XmlAssemblyTypeMethodRuleParser.cs +++ /dev/null @@ -1,263 +0,0 @@ -using dnlib.DotNet; -using Obfuz.Utils; -using System; -using System.Collections.Generic; -using System.Xml; -using UnityEngine; - -namespace Obfuz.Conf -{ - public interface IRule - { - void InheritParent(T parentRule); - } - - - public interface IMethodRule where R : IRule - { - string Name { get; set; } - NameMatcher NameMatcher { get; set; } - - R Rule { get; set; } - } - - public abstract class MethodRuleBase : IMethodRule where R : IRule - { - public string Name { get; set; } - public NameMatcher NameMatcher { get; set; } - - public R Rule { get; set; } - } - - public interface ITypeRule where T : IMethodRule where R : IRule - { - string Name { get; set; } - - NameMatcher NameMatcher { get; set; } - - R Rule { get; set; } - - List Methods { get; set; } - } - - public abstract class TypeRuleBase : ITypeRule where T : IMethodRule where R : IRule - { - public string Name { get; set; } - - public NameMatcher NameMatcher { get; set; } - - public R Rule { get; set; } - - public List Methods { get; set; } - } - - public interface IAssemblyRule where TType : ITypeRule where TMethod : IMethodRule where TRule : IRule - { - string Name { get; set; } - - TRule Rule { get; set; } - - List Types { get; set; } - } - public abstract class AssemblyRuleBase : IAssemblyRule where TType : ITypeRule where TMethod : IMethodRule where TRule : IRule - { - public string Name { get; set; } - - public TRule Rule { get; set; } - - public List Types { get; set; } - } - - public class XmlAssemblyTypeMethodRuleParser - where TMethod : IMethodRule, new() - where TType : ITypeRule, new() - where TAssembly : IAssemblyRule, new() - where TRule : IRule, new() - { - private readonly HashSet _toObfuscatedAssemblyNames; - private readonly Func _ruleParser; - private readonly Action _unknownNodeTypeHandler; - private readonly Dictionary _assemblySpecs = new Dictionary(); - - public XmlAssemblyTypeMethodRuleParser(IEnumerable toObfuscatedAssemblyNames, Func ruleParser, Action unknownNodeTypeHandler) - { - _toObfuscatedAssemblyNames = new HashSet(toObfuscatedAssemblyNames); - _ruleParser = ruleParser; - _unknownNodeTypeHandler = unknownNodeTypeHandler; - } - - public Dictionary AssemblySpecs => _assemblySpecs; - - public void LoadConfigs(IEnumerable configFiles) - { - foreach (var configFile in configFiles) - { - LoadConfig(configFile); - } - } - - public void LoadConfig(string configFile) - { - if (string.IsNullOrEmpty(configFile)) - { - throw new Exception($"Invalid xml file {configFile}, file name is empty"); - } - Debug.Log($"ConfigurableObfuscationPolicy::LoadConfig {configFile}"); - var doc = new XmlDocument(); - doc.Load(configFile); - var root = doc.DocumentElement; - if (root.Name != "obfuz") - { - throw new Exception($"Invalid xml file {configFile}, root name should be 'obfuz'"); - } - foreach (XmlNode node in root.ChildNodes) - { - if (!(node is XmlElement ele)) - { - continue; - } - switch (ele.Name) - { - case "assembly": - { - TAssembly assSpec = ParseAssembly(configFile, ele); - _assemblySpecs.Add(assSpec.Name, assSpec); - break; - } - default: - { - if (_unknownNodeTypeHandler == null) - { - throw new Exception($"Invalid xml file {configFile}, unknown node {ele.Name}"); - } - _unknownNodeTypeHandler(configFile, ele); - break; - } - } - } - } - - private TAssembly ParseAssembly(string configFile, XmlElement ele) - { - var assemblySpec = new TAssembly(); - string name = ele.GetAttribute("name"); - if (!_toObfuscatedAssemblyNames.Contains(name)) - { - throw new Exception($"Invalid xml file {configFile}, assembly name {name} isn't in toObfuscatedAssemblyNames"); - } - if (_assemblySpecs.ContainsKey(name)) - { - throw new Exception($"Invalid xml file {configFile}, assembly name {name} is duplicated"); - } - assemblySpec.Name = name; - assemblySpec.Rule = _ruleParser(configFile, ele); - - var types = new List(); - assemblySpec.Types = types; - foreach (XmlNode node in ele.ChildNodes) - { - if (!(node is XmlElement childEle)) - { - continue; - } - switch (childEle.Name) - { - case "type": - { - types.Add(ParseType(configFile, childEle)); - break; - } - default: - { - throw new Exception($"Invalid xml file, unknown node {childEle.Name}"); - } - } - } - return assemblySpec; - } - - private TType ParseType(string configFile, XmlElement element) - { - var typeSpec = new TType(); - - string name = element.GetAttribute("name"); - typeSpec.Name = name; - typeSpec.NameMatcher = new NameMatcher(name); - typeSpec.Rule = _ruleParser(configFile, element); - - var methods = new List(); - typeSpec.Methods = methods; - foreach (XmlNode node in element.ChildNodes) - { - if (!(node is XmlElement ele)) - { - continue; - } - switch (ele.Name) - { - case "method": - { - methods.Add(ParseMethod(configFile, ele)); - break; - } - default: - { - throw new Exception($"Invalid xml file, unknown node {ele.Name}"); - } - } - } - return typeSpec; - } - - private TMethod ParseMethod(string configFile, XmlElement element) - { - var methodSpec = new TMethod(); - string name = element.GetAttribute("name"); - methodSpec.Name = name; - methodSpec.NameMatcher = new NameMatcher(name); - methodSpec.Rule = _ruleParser(configFile, element); - return methodSpec; - } - - public TRule GetMethodRule(MethodDef method, TRule defaultRule) - { - var assemblyName = method.DeclaringType.Module.Assembly.Name; - if (!_assemblySpecs.TryGetValue(assemblyName, out var assSpec)) - { - return defaultRule; - } - string declaringTypeName = method.DeclaringType.FullName; - foreach (var typeSpec in assSpec.Types) - { - if (typeSpec.NameMatcher.IsMatch(declaringTypeName)) - { - foreach (var methodSpec in typeSpec.Methods) - { - if (methodSpec.NameMatcher.IsMatch(method.Name)) - { - return methodSpec.Rule; - } - } - return typeSpec.Rule; - } - } - return assSpec.Rule; - } - - public void InheritParentRules(TRule defaultRule) - { - foreach (TAssembly assSpec in _assemblySpecs.Values) - { - assSpec.Rule.InheritParent(defaultRule); - foreach (TType typeSpec in assSpec.Types) - { - typeSpec.Rule.InheritParent(assSpec.Rule); - foreach (TMethod methodSpec in typeSpec.Methods) - { - methodSpec.Rule.InheritParent(typeSpec.Rule); - } - } - } - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Conf/XmlAssemblyTypeMethodRuleParser.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Conf/XmlAssemblyTypeMethodRuleParser.cs.meta deleted file mode 100644 index 84f5aa9b..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Conf/XmlAssemblyTypeMethodRuleParser.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 36a3e142db81f6d4bb54938525e31973 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Conf/XmlFieldRuleParser.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Conf/XmlFieldRuleParser.cs deleted file mode 100644 index 5cef8c98..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Conf/XmlFieldRuleParser.cs +++ /dev/null @@ -1,203 +0,0 @@ -using dnlib.DotNet; -using Obfuz.Utils; -using System; -using System.Collections.Generic; -using System.Xml; - -namespace Obfuz.Conf -{ - - - - public class XmlFieldRuleParser where R : class, new() - { - private readonly HashSet _toObfuscatedAssemblyNames; - private readonly Func _ruleParser; - private readonly Action _unknownNodeTypeHandler; - private readonly Dictionary _assemblySpecs = new Dictionary(); - - - private class FieldSpec - { - public string Name { get; set; } - public NameMatcher NameMatcher { get; set; } - - public R Rule { get; set; } - } - - private class TypeSpec - { - public string Name { get; set; } - - public NameMatcher NameMatcher { get; set; } - - public List Fields { get; set; } - } - - private class AssemblySpec - { - public string Name { get; set; } - - public List Types { get; set; } - } - - public XmlFieldRuleParser(IEnumerable toObfuscatedAssemblyNames, Func ruleParser, Action unknownNodeTypeHandler) - { - _toObfuscatedAssemblyNames = new HashSet(toObfuscatedAssemblyNames); - _ruleParser = ruleParser; - _unknownNodeTypeHandler = unknownNodeTypeHandler; - } - - public void LoadConfigs(IEnumerable configFiles) - { - foreach (var configFile in configFiles) - { - LoadConfig(configFile); - } - } - - public void LoadConfig(string configFile) - { - if (string.IsNullOrEmpty(configFile)) - { - throw new Exception($"Invalid xml file {configFile}, file name is empty"); - } - var doc = new XmlDocument(); - doc.Load(configFile); - var root = doc.DocumentElement; - if (root.Name != "obfuz") - { - throw new Exception($"Invalid xml file {configFile}, root name should be 'obfuz'"); - } - foreach (XmlNode node in root.ChildNodes) - { - if (!(node is XmlElement ele)) - { - continue; - } - switch (ele.Name) - { - case "assembly": - { - AssemblySpec assSpec = ParseAssembly(configFile, ele); - _assemblySpecs.Add(assSpec.Name, assSpec); - break; - } - default: - { - if (_unknownNodeTypeHandler == null) - { - throw new Exception($"Invalid xml file {configFile}, unknown node {ele.Name}"); - } - _unknownNodeTypeHandler(configFile, ele); - break; - } - } - } - } - - private AssemblySpec ParseAssembly(string configFile, XmlElement ele) - { - var assemblySpec = new AssemblySpec(); - string name = ele.GetAttribute("name"); - if (!_toObfuscatedAssemblyNames.Contains(name)) - { - throw new Exception($"Invalid xml file {configFile}, assembly name {name} isn't in toObfuscatedAssemblyNames"); - } - if (_assemblySpecs.ContainsKey(name)) - { - throw new Exception($"Invalid xml file {configFile}, assembly name {name} is duplicated"); - } - assemblySpec.Name = name; - - var types = new List(); - assemblySpec.Types = types; - foreach (XmlNode node in ele.ChildNodes) - { - if (!(node is XmlElement childEle)) - { - continue; - } - switch (childEle.Name) - { - case "type": - { - types.Add(ParseType(configFile, childEle)); - break; - } - default: - { - throw new Exception($"Invalid xml file, unknown node {childEle.Name}"); - } - } - } - return assemblySpec; - } - - private TypeSpec ParseType(string configFile, XmlElement element) - { - var typeSpec = new TypeSpec(); - - string name = element.GetAttribute("name"); - typeSpec.Name = name; - typeSpec.NameMatcher = new NameMatcher(name); - - var fields = new List(); - typeSpec.Fields = fields; - foreach (XmlNode node in element.ChildNodes) - { - if (!(node is XmlElement ele)) - { - continue; - } - switch (ele.Name) - { - case "field": - { - fields.Add(ParseField(configFile, ele)); - break; - } - default: - { - throw new Exception($"Invalid xml file, unknown node {ele.Name}"); - } - } - } - return typeSpec; - } - - private FieldSpec ParseField(string configFile, XmlElement element) - { - var fieldSpec = new FieldSpec(); - string name = element.GetAttribute("name"); - fieldSpec.Name = name; - fieldSpec.NameMatcher = new NameMatcher(name); - fieldSpec.Rule = _ruleParser(configFile, element); - return fieldSpec; - } - - public R GetFieldRule(FieldDef field) - { - var assemblyName = field.DeclaringType.Module.Assembly.Name; - if (!_assemblySpecs.TryGetValue(assemblyName, out var assSpec)) - { - return null; - } - string declaringTypeName = field.DeclaringType.FullName; - foreach (var typeSpec in assSpec.Types) - { - if (typeSpec.NameMatcher.IsMatch(declaringTypeName)) - { - foreach (var fieldSpec in typeSpec.Fields) - { - if (fieldSpec.NameMatcher.IsMatch(field.Name)) - { - return fieldSpec.Rule; - } - } - } - } - return null; - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Conf/XmlFieldRuleParser.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Conf/XmlFieldRuleParser.cs.meta deleted file mode 100644 index d8995b9e..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Conf/XmlFieldRuleParser.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 1578270b9b81e1e4dba84d562c91090f -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ConfigurablePassPolicy.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ConfigurablePassPolicy.cs deleted file mode 100644 index 3a94a919..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ConfigurablePassPolicy.cs +++ /dev/null @@ -1,544 +0,0 @@ -using dnlib.DotNet; -using Obfuz.ObfusPasses; -using Obfuz.Utils; -using System; -using System.Collections.Generic; -using System.Xml; -using UnityEngine; - -namespace Obfuz -{ - public class ConfigurablePassPolicy - { - class PassRule - { - public ObfuscationPassType? enablePasses; - public ObfuscationPassType? disablePasses; - public ObfuscationPassType? addPasses; - public ObfuscationPassType? removePasses; - public ObfuscationPassType finalPasses; - - public void InheritParent(PassRule parentRule, ObfuscationPassType globalEnabledPasses) - { - finalPasses = parentRule.finalPasses; - if (enablePasses != null) - { - finalPasses = enablePasses.Value; - } - if (disablePasses != null) - { - finalPasses = ~disablePasses.Value; - } - if (addPasses != null) - { - finalPasses |= addPasses.Value; - } - if (removePasses != null) - { - finalPasses &= ~removePasses.Value; - } - finalPasses &= globalEnabledPasses; - } - } - - class SpecBase - { - public string name; - public NameMatcher nameMatcher; - public PassRule rule; - } - - class MethodSpec : SpecBase - { - } - - class FieldSpec : SpecBase - { - } - - class PropertySpec : SpecBase - { - } - - class EventSpec : SpecBase - { - } - - class TypeSpec : SpecBase - { - public List fields = new List(); - public List methods = new List(); - public List properties = new List(); - public List events = new List(); - } - - class AssemblySpec - { - public string name; - public NameMatcher nameMatcher; - public PassRule rule; - public List types = new List(); - } - - private readonly ObfuscationPassType _enabledPasses; - private readonly HashSet _toObfuscatedAssemblyNames; - private readonly List _assemblySpecs = new List(); - private readonly PassRule _defaultPassRule; - - private string _curLoadingConfig; - - public ConfigurablePassPolicy(IEnumerable toObfuscatedAssemblyNames, ObfuscationPassType enabledPasses, List configFiles) - { - _toObfuscatedAssemblyNames = new HashSet(toObfuscatedAssemblyNames); - _enabledPasses = enabledPasses; - _defaultPassRule = new PassRule { finalPasses = enabledPasses }; - LoadConfigs(configFiles); - InheritParentRules(enabledPasses); - } - - private void LoadConfigs(IEnumerable configFiles) - { - foreach (var configFile in configFiles) - { - LoadConfig(configFile); - } - } - - private void InheritParentRules(ObfuscationPassType enablePasses) - { - var defaultRule = new PassRule - { - enablePasses = enablePasses, - finalPasses = enablePasses, - }; - foreach (AssemblySpec assSpec in _assemblySpecs) - { - assSpec.rule.InheritParent(defaultRule, enablePasses); - foreach (TypeSpec typeSpec in assSpec.types) - { - typeSpec.rule.InheritParent(assSpec.rule, enablePasses); - foreach (FieldSpec fieldSpec in typeSpec.fields) - { - fieldSpec.rule.InheritParent(typeSpec.rule, enablePasses); - } - foreach (MethodSpec methodSpec in typeSpec.methods) - { - methodSpec.rule.InheritParent(typeSpec.rule, enablePasses); - } - foreach (PropertySpec propertySpec in typeSpec.properties) - { - propertySpec.rule.InheritParent(typeSpec.rule, enablePasses); - } - foreach (EventSpec eventSpec in typeSpec.events) - { - eventSpec.rule.InheritParent(typeSpec.rule, enablePasses); - } - } - } - } - - public void LoadConfig(string configFile) - { - if (string.IsNullOrEmpty(configFile)) - { - throw new Exception($"Invalid xml file {configFile}, file name is empty"); - } - _curLoadingConfig = configFile; - - Debug.Log($"ConfigurablePassPolicy::LoadConfig {configFile}"); - var doc = new XmlDocument(); - doc.Load(configFile); - var root = doc.DocumentElement; - if (root.Name != "obfuz") - { - throw new Exception($"Invalid xml file {configFile}, root name should be 'obfuz'"); - } - foreach (XmlNode node in root.ChildNodes) - { - if (!(node is XmlElement ele)) - { - continue; - } - switch (ele.Name) - { - case "assembly": - { - AssemblySpec assSpec = ParseAssembly(ele); - _assemblySpecs.Add(assSpec); - break; - } - default: - { - throw new Exception($"Invalid xml file {configFile}, unknown node {ele.Name}"); - } - } - } - } - - (bool, ObfuscationPassType) ParseObfuscationType(string obfuscationPassTypesStr) - { - bool delta = false; - if (obfuscationPassTypesStr[0] == '+' || obfuscationPassTypesStr[0] == '-') - { - delta = true; - obfuscationPassTypesStr = obfuscationPassTypesStr.Substring(1); - } - ObfuscationPassType passType = ObfuscationPassType.None; - foreach (var passName in obfuscationPassTypesStr.Split('|')) - { - if (Enum.TryParse(passName, out var pass)) - { - passType |= pass; - } - else - { - throw new Exception($"Invalid xml file {_curLoadingConfig}, unknown pass type {passName}"); - } - } - return (delta, passType); - } - - private PassRule ParseRule(XmlElement ele) - { - var r = new PassRule(); - if (ele.HasAttribute("enable")) - { - string enablePassStr = ele.GetAttribute("enable"); - if (string.IsNullOrEmpty(enablePassStr)) - { - throw new Exception($"Invalid xml file {_curLoadingConfig}, enable attribute is empty"); - } - var (delta, passType) = ParseObfuscationType(enablePassStr); - if (delta) - { - r.addPasses = passType; - } - else - { - r.enablePasses = passType; - } - } - if (ele.HasAttribute("disable")) - { - string disablePassStr = ele.GetAttribute("disable"); - if (string.IsNullOrEmpty(disablePassStr)) - { - throw new Exception($"Invalid xml file {_curLoadingConfig}, disable attribute is empty"); - } - var (delta, passType) = ParseObfuscationType(disablePassStr); - if (delta) - { - r.removePasses = passType; - } - else - { - r.disablePasses = passType; - } - } - if (r.enablePasses != null && (r.disablePasses != null || r.addPasses != null || r.removePasses != null)) - { - throw new Exception($"Invalid xml file {_curLoadingConfig}, enable and disable can't be used together"); - } - if (r.disablePasses != null && (r.enablePasses != null || r.addPasses != null || r.removePasses != null)) - { - throw new Exception($"Invalid xml file {_curLoadingConfig}, disable and enable can't be used together"); - } - return r; - } - - private AssemblySpec ParseAssembly(XmlElement ele) - { - var assemblySpec = new AssemblySpec(); - string name = ele.GetAttribute("name"); - if (!_toObfuscatedAssemblyNames.Contains(name)) - { - throw new Exception($"Invalid xml file {_curLoadingConfig}, assembly name {name} isn't in toObfuscatedAssemblyNames"); - } - assemblySpec.name = name; - assemblySpec.nameMatcher = new NameMatcher(name); - assemblySpec.rule = ParseRule(ele); - - - var types = assemblySpec.types; - foreach (XmlNode node in ele.ChildNodes) - { - if (!(node is XmlElement childEle)) - { - continue; - } - switch (childEle.Name) - { - case "type": - { - types.Add(ParseType(childEle)); - break; - } - default: - { - throw new Exception($"Invalid xml file, unknown node {childEle.Name}"); - } - } - } - return assemblySpec; - } - - private TypeSpec ParseType(XmlElement element) - { - var typeSpec = new TypeSpec(); - - string name = element.GetAttribute("name"); - typeSpec.name = name; - typeSpec.nameMatcher = new NameMatcher(name); - typeSpec.rule = ParseRule(element); - - List fields = typeSpec.fields; - List methods = typeSpec.methods; - List properties = typeSpec.properties; - List events = typeSpec.events; - foreach (XmlNode node in element.ChildNodes) - { - if (!(node is XmlElement ele)) - { - continue; - } - switch (ele.Name) - { - case "field": - { - fields.Add(ParseField(ele)); - break; - } - case "method": - { - methods.Add(ParseMethod(ele)); - break; - } - case "property": - { - properties.Add(ParseProperty(ele)); - break; - } - case "event": - { - events.Add(ParseEvent(ele)); - break; - } - default: - { - throw new Exception($"Invalid xml file, unknown node {ele.Name}"); - } - } - } - return typeSpec; - } - - private void ParseSpecObject(XmlElement element, SpecBase obj) - { - string name = element.GetAttribute("name"); - obj.name = name; - obj.nameMatcher = new NameMatcher(name); - obj.rule = ParseRule(element); - } - - private FieldSpec ParseField(XmlElement element) - { - var fieldSpec = new FieldSpec(); - ParseSpecObject(element, fieldSpec); - return fieldSpec; - } - - private MethodSpec ParseMethod(XmlElement element) - { - var methodSpec = new MethodSpec(); - ParseSpecObject(element, methodSpec); - return methodSpec; - } - - private PropertySpec ParseProperty(XmlElement element) - { - var propertySpec = new PropertySpec(); - ParseSpecObject(element, propertySpec); - return propertySpec; - } - - private EventSpec ParseEvent(XmlElement element) - { - var eventSpec = new EventSpec(); - ParseSpecObject(element, eventSpec); - return eventSpec; - } - - private readonly Dictionary _modulePassRuleCaches = new Dictionary(); - private readonly Dictionary _typePassRuleCaches = new Dictionary(); - private readonly Dictionary _methodPassRuleCaches = new Dictionary(); - private readonly Dictionary _fieldPassRuleCaches = new Dictionary(); - private readonly Dictionary _propertyPassRuleCaches = new Dictionary(); - private readonly Dictionary _eventPassRuleCaches = new Dictionary(); - - - private (AssemblySpec, PassRule) GetAssemblySpec(ModuleDef module) - { - if (!_modulePassRuleCaches.TryGetValue(module, out var result)) - { - result = (null, _defaultPassRule); - string assName = module.Assembly.Name; - foreach (var ass in _assemblySpecs) - { - if (ass.nameMatcher.IsMatch(assName)) - { - result = (ass, ass.rule); - break; - } - } - _modulePassRuleCaches.Add(module, result); - } - return result; - } - - private (TypeSpec, PassRule) GetTypeSpec(TypeDef type) - { - if (!_typePassRuleCaches.TryGetValue(type, out var result)) - { - var assResult = GetAssemblySpec(type.Module); - result = (null, assResult.Item2); - if (assResult.Item1 != null) - { - string typeName = type.FullName; - foreach (var typeSpec in assResult.Item1.types) - { - if (typeSpec.nameMatcher.IsMatch(typeName)) - { - result = (typeSpec, typeSpec.rule); - break; - } - } - } - _typePassRuleCaches.Add(type, result); - } - return result; - } - - private (MethodSpec, PassRule) GetMethodSpec(MethodDef method) - { - if (!_methodPassRuleCaches.TryGetValue(method, out var result)) - { - var typeResult = GetTypeSpec(method.DeclaringType); - result = (null, typeResult.Item2); - if (typeResult.Item1 != null) - { - string methodName = method.Name; - foreach (var methodSpec in typeResult.Item1.methods) - { - if (methodSpec.nameMatcher.IsMatch(methodName)) - { - result = (methodSpec, methodSpec.rule); - break; - } - } - } - _methodPassRuleCaches.Add(method, result); - } - return result; - } - - private (FieldSpec, PassRule) GetFieldSpec(FieldDef field) - { - if (!_fieldPassRuleCaches.TryGetValue(field, out var result)) - { - var typeResult = GetTypeSpec(field.DeclaringType); - result = (null, typeResult.Item2); - if (typeResult.Item1 != null) - { - string fieldName = field.Name; - foreach (var fieldSpec in typeResult.Item1.fields) - { - if (fieldSpec.nameMatcher.IsMatch(fieldName)) - { - result = (fieldSpec, fieldSpec.rule); - break; - } - } - } - _fieldPassRuleCaches.Add(field, result); - } - return result; - } - - private (PropertySpec, PassRule) GetPropertySpec(PropertyDef property) - { - if (!_propertyPassRuleCaches.TryGetValue(property, out var result)) - { - var typeResult = GetTypeSpec(property.DeclaringType); - result = (null, typeResult.Item2); - if (typeResult.Item1 != null) - { - string propertyName = property.Name; - foreach (var propertySpec in typeResult.Item1.properties) - { - if (propertySpec.nameMatcher.IsMatch(propertyName)) - { - result = (propertySpec, propertySpec.rule); - break; - } - } - } - _propertyPassRuleCaches.Add(property, result); - } - return result; - } - - private (EventSpec, PassRule) GetEventSpec(EventDef eventDef) - { - if (!_eventPassRuleCaches.TryGetValue(eventDef, out var result)) - { - var typeResult = GetTypeSpec(eventDef.DeclaringType); - result = (null, typeResult.Item2); - if (typeResult.Item1 != null) - { - string eventName = eventDef.Name; - foreach (var eventSpec in typeResult.Item1.events) - { - if (eventSpec.nameMatcher.IsMatch(eventName)) - { - result = (eventSpec, eventSpec.rule); - break; - } - } - } - _eventPassRuleCaches.Add(eventDef, result); - } - return result; - } - - - public ObfuscationPassType GetAssemblyObfuscationPasses(ModuleDef module) - { - return GetAssemblySpec(module).Item2.finalPasses; - } - - public ObfuscationPassType GetTypeObfuscationPasses(TypeDef type) - { - return GetTypeSpec(type).Item2.finalPasses; - } - - public ObfuscationPassType GetMethodObfuscationPasses(MethodDef method) - { - return GetMethodSpec(method).Item2.finalPasses; - } - - public ObfuscationPassType GetFieldObfuscationPasses(FieldDef field) - { - return GetFieldSpec(field).Item2.finalPasses; - } - - public ObfuscationPassType GetPropertyObfuscationPasses(PropertyDef property) - { - return GetPropertySpec(property).Item2.finalPasses; - } - - public ObfuscationPassType GetEventObfuscationPasses(EventDef eventDef) - { - return GetEventSpec(eventDef).Item2.finalPasses; - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ConfigurablePassPolicy.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ConfigurablePassPolicy.cs.meta deleted file mode 100644 index 9b85183e..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ConfigurablePassPolicy.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 41044699810a34f4780e14de084bf7d7 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ConstValues.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ConstValues.cs deleted file mode 100644 index 90c3a3bd..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ConstValues.cs +++ /dev/null @@ -1,34 +0,0 @@ -using System.Text; - -namespace Obfuz.Editor -{ - public static class ConstValues - { - public const string ObfuzInternalSymbolNamePrefix = "$Obfuz$"; - - public const string ObfuzRuntimeAssemblyName = "Obfuz.Runtime"; - - public const string ObfuzIgnoreAttributeFullName = "Obfuz.ObfuzIgnoreAttribute"; - - public const string ObfuzScopeFullName = "Obfuz.ObfuzScope"; - - public const string EncryptFieldAttributeFullName = "Obfuz.EncryptFieldAttribute"; - public const string GeneratedEncryptionVirtualMachineFullName = "Obfuz.EncryptionVM.GeneratedEncryptionVirtualMachine"; - - public const string EmbeddedAttributeFullName = "Microsoft.CodeAnalysis.EmbeddedAttribute"; - - public const string MonoPInvokeCallbackAttributeName = "MonoPInvokeCallbackAttribute"; - - public const string ZluaLuaInvokeAttributeFullName = "Zlua.LuaInvokeAttribute"; - public const string ZluaLuaCallbackAttributeFullName = "Zlua.LuaCallbackAttribute"; - public const string ZluaLuaMarshalAsAttributeFullName = "Zlua.LuaMarshalAsAttribute"; - - public const string BurstCompileFullName = "Unity.Burst.BurstCompileAttribute"; - public const string DOTSCompilerGeneratedAttributeFullName = "Unity.Jobs.DOTSCompilerGeneratedAttribute"; - - public const string RuntimeInitializedOnLoadMethodAttributeFullName = "UnityEngine.RuntimeInitializeOnLoadMethodAttribute"; - public const string BlackboardEnumAttributeFullName = "Unity.Behavior.BlackboardEnumAttribute"; - - public const string CompilerGeneratedAttributeFullName = "System.Runtime.CompilerServices.CompilerGeneratedAttribute"; - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ConstValues.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ConstValues.cs.meta deleted file mode 100644 index 33f41601..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ConstValues.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: aee7817ed523a5e4ea42104013e8a775 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Data.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Data.meta deleted file mode 100644 index d162ae8e..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Data.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 3319ebe75a42f3d4d996846ca09ed099 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Data/ConstFieldAllocator.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Data/ConstFieldAllocator.cs deleted file mode 100644 index 90f889d1..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Data/ConstFieldAllocator.cs +++ /dev/null @@ -1,269 +0,0 @@ -using dnlib.DotNet; -using dnlib.DotNet.Emit; -using Obfuz.Editor; -using Obfuz.Emit; -using Obfuz.Utils; -using System; -using System.Collections; -using System.Collections.Generic; -using UnityEngine.Assertions; - -namespace Obfuz.Data -{ - public class ConstFieldAllocator : GroupByModuleEntityBase - { - private RandomCreator _randomCreator; - private IEncryptor _encryptor; - - private TypeDef _holderTypeDef; - - class ConstFieldInfo - { - public FieldDef field; - public object value; - } - - class AnyComparer : IEqualityComparer - { - public new bool Equals(object x, object y) - { - if (x is byte[] xBytes && y is byte[] yBytes) - { - return StructuralComparisons.StructuralEqualityComparer.Equals(xBytes, yBytes); - } - return x.Equals(y); - } - - public static int ComputeHashCode(object obj) - { - return HashUtil.ComputePrimitiveOrStringOrBytesHashCode(obj); - } - - public int GetHashCode(object obj) - { - return ComputeHashCode(obj); - } - } - - private readonly Dictionary _allocatedFields = new Dictionary(new AnyComparer()); - private readonly Dictionary _field2Fields = new Dictionary(); - - private readonly List _holderTypeDefs = new List(); - private bool _done; - - - public ConstFieldAllocator() - { - } - - public override void Init() - { - _randomCreator = EncryptionScope.localRandomCreator; - _encryptor = EncryptionScope.encryptor; - } - - const int maxFieldCount = 1000; - - - private TypeSig GetTypeSigOfValue(object value) - { - ModuleDef mod = Module; - if (value is int) - return mod.CorLibTypes.Int32; - if (value is long) - return mod.CorLibTypes.Int64; - if (value is float) - return mod.CorLibTypes.Single; - if (value is double) - return mod.CorLibTypes.Double; - if (value is string) - return mod.CorLibTypes.String; - if (value is byte[]) - return new SZArraySig(mod.CorLibTypes.Byte); - throw new NotSupportedException($"Unsupported type: {value.GetType()}"); - } - - private ConstFieldInfo CreateConstFieldInfo(object value) - { - ModuleDef mod = Module; - if (_holderTypeDef == null || _holderTypeDef.Fields.Count >= maxFieldCount) - { - using (var scope = new DisableTypeDefFindCacheScope(mod)) - { - ITypeDefOrRef objectTypeRef = mod.Import(typeof(object)); - _holderTypeDef = new TypeDefUser($"{ConstValues.ObfuzInternalSymbolNamePrefix}ConstFieldHolder${_holderTypeDefs.Count}", objectTypeRef); - mod.Types.Add(_holderTypeDef); - _holderTypeDefs.Add(_holderTypeDef); - } - } - - var field = new FieldDefUser($"{ConstValues.ObfuzInternalSymbolNamePrefix}RVA_Value{_holderTypeDef.Fields.Count}", new FieldSig(GetTypeSigOfValue(value)), FieldAttributes.Static | FieldAttributes.Public); - field.DeclaringType = _holderTypeDef; - return new ConstFieldInfo - { - field = field, - value = value, - }; - } - - private FieldDef AllocateAny(object value) - { - if (_done) - { - throw new Exception("can't Allocate after done"); - } - if (!_allocatedFields.TryGetValue(value, out var field)) - { - field = CreateConstFieldInfo(value); - _allocatedFields.Add(value, field); - _field2Fields.Add(field.field, field); - } - return field.field; - } - - public FieldDef Allocate(int value) - { - return AllocateAny(value); - } - - public FieldDef Allocate(long value) - { - return AllocateAny(value); - } - - public FieldDef Allocate(float value) - { - return AllocateAny(value); - } - - public FieldDef Allocate(double value) - { - return AllocateAny(value); - } - - public FieldDef Allocate(string value) - { - return AllocateAny(value); - } - - public FieldDef Allocate(byte[] value) - { - return AllocateAny(value); - } - - - private void CreateCCtorOfRvaTypeDef(TypeDef type) - { - ModuleDef mod = Module; - var cctor = new MethodDefUser(".cctor", - MethodSig.CreateStatic(mod.CorLibTypes.Void), - MethodImplAttributes.IL | MethodImplAttributes.Managed, - MethodAttributes.Static | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName | MethodAttributes.Private); - cctor.DeclaringType = type; - var body = new CilBody(); - cctor.Body = body; - var ins = body.Instructions; - - - DefaultMetadataImporter importer = this.GetDefaultModuleMetadataImporter(); - RvaDataAllocator rvaDataAllocator = GetEntity(); - // TODO. obfuscate init codes - foreach (var field in type.Fields) - { - ConstFieldInfo constInfo = _field2Fields[field]; - IRandom localRandom = _randomCreator(HashUtil.ComputePrimitiveOrStringOrBytesHashCode(constInfo.value)); - int ops = EncryptionUtil.GenerateEncryptionOpCodes(localRandom, _encryptor, 4); - int salt = localRandom.NextInt(); - switch (constInfo.value) - { - case int i: - { - int encryptedValue = _encryptor.Encrypt(i, ops, salt); - RvaData rvaData = rvaDataAllocator.Allocate(encryptedValue); - ins.Add(Instruction.Create(OpCodes.Ldsfld, rvaData.field)); - ins.Add(Instruction.CreateLdcI4(rvaData.offset)); - ins.Add(Instruction.CreateLdcI4(ops)); - ins.Add(Instruction.CreateLdcI4(salt)); - ins.Add(Instruction.Create(OpCodes.Call, importer.DecryptFromRvaInt)); - break; - } - case long l: - { - long encryptedValue = _encryptor.Encrypt(l, ops, salt); - RvaData rvaData = rvaDataAllocator.Allocate(encryptedValue); - ins.Add(Instruction.Create(OpCodes.Ldsfld, rvaData.field)); - ins.Add(Instruction.CreateLdcI4(rvaData.offset)); - ins.Add(Instruction.CreateLdcI4(ops)); - ins.Add(Instruction.CreateLdcI4(salt)); - ins.Add(Instruction.Create(OpCodes.Call, importer.DecryptFromRvaLong)); - break; - } - case float f: - { - float encryptedValue = _encryptor.Encrypt(f, ops, salt); - RvaData rvaData = rvaDataAllocator.Allocate(encryptedValue); - ins.Add(Instruction.Create(OpCodes.Ldsfld, rvaData.field)); - ins.Add(Instruction.CreateLdcI4(rvaData.offset)); - ins.Add(Instruction.CreateLdcI4(ops)); - ins.Add(Instruction.CreateLdcI4(salt)); - ins.Add(Instruction.Create(OpCodes.Call, importer.DecryptFromRvaFloat)); - break; - } - case double d: - { - double encryptedValue = _encryptor.Encrypt(d, ops, salt); - RvaData rvaData = rvaDataAllocator.Allocate(encryptedValue); - ins.Add(Instruction.Create(OpCodes.Ldsfld, rvaData.field)); - ins.Add(Instruction.CreateLdcI4(rvaData.offset)); - ins.Add(Instruction.CreateLdcI4(ops)); - ins.Add(Instruction.CreateLdcI4(salt)); - ins.Add(Instruction.Create(OpCodes.Call, importer.DecryptFromRvaDouble)); - break; - } - case string s: - { - byte[] encryptedValue = _encryptor.Encrypt(s, ops, salt); - RvaData rvaData = rvaDataAllocator.Allocate(encryptedValue); - ins.Add(Instruction.Create(OpCodes.Ldsfld, rvaData.field)); - ins.Add(Instruction.CreateLdcI4(rvaData.offset)); - Assert.AreEqual(encryptedValue.Length, rvaData.size); - ins.Add(Instruction.CreateLdcI4(encryptedValue.Length)); - ins.Add(Instruction.CreateLdcI4(ops)); - ins.Add(Instruction.CreateLdcI4(salt)); - ins.Add(Instruction.Create(OpCodes.Call, importer.DecryptFromRvaString)); - break; - } - case byte[] bs: - { - byte[] encryptedValue = _encryptor.Encrypt(bs, 0, bs.Length, ops, salt); - Assert.AreEqual(encryptedValue.Length, bs.Length); - RvaData rvaData = rvaDataAllocator.Allocate(encryptedValue); - ins.Add(Instruction.Create(OpCodes.Ldsfld, rvaData.field)); - ins.Add(Instruction.CreateLdcI4(rvaData.offset)); - ins.Add(Instruction.CreateLdcI4(bs.Length)); - ins.Add(Instruction.CreateLdcI4(ops)); - ins.Add(Instruction.CreateLdcI4(salt)); - ins.Add(Instruction.Create(OpCodes.Call, importer.DecryptFromRvaBytes)); - break; - } - default: throw new NotSupportedException($"Unsupported type: {constInfo.value.GetType()}"); - } - ins.Add(Instruction.Create(OpCodes.Stsfld, field)); - } - ins.Add(Instruction.Create(OpCodes.Ret)); - } - - public override void Done() - { - if (_done) - { - throw new Exception("Already done"); - } - _done = true; - foreach (var typeDef in _holderTypeDefs) - { - CreateCCtorOfRvaTypeDef(typeDef); - } - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Data/ConstFieldAllocator.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Data/ConstFieldAllocator.cs.meta deleted file mode 100644 index 8e64e42e..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Data/ConstFieldAllocator.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: e75f5cdfd47370d4ea6c4dee7e55a881 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Data/RvaDataAllocator.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Data/RvaDataAllocator.cs deleted file mode 100644 index 00736502..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Data/RvaDataAllocator.cs +++ /dev/null @@ -1,324 +0,0 @@ -using dnlib.DotNet; -using dnlib.DotNet.Emit; -using Obfuz.Emit; -using Obfuz.Utils; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Runtime.InteropServices; -using System.Text; -using UnityEngine.Assertions; - -namespace Obfuz.Data -{ - public struct RvaData - { - public readonly FieldDef field; - public readonly int offset; - public readonly int size; - - public RvaData(FieldDef field, int offset, int size) - { - this.field = field; - this.offset = offset; - this.size = size; - } - } - - public class RvaDataAllocator : GroupByModuleEntityBase - { - const int maxRvaDataSize = 2 * 1024; - - // in HybridCLR version below 8.3.0, the max total static field size of a type is 16KB, so we limit the total size of RVA data to 16KB - const int maxTotalRvaDataFieldSizeInHybridCLR = 16 * 1024; - - private IRandom _random; - - class RvaField - { - public FieldDef holderDataField; - public FieldDef runtimeValueField; - public int encryptionOps; - public uint size; - public List bytes; - public int salt; - - public void FillPaddingToSize(int newSize) - { - for (int i = bytes.Count; i < newSize; i++) - { - bytes.Add(0xAB); - } - } - - public void FillPaddingToEnd() - { - // fill with random value - for (int i = bytes.Count; i < size; i++) - { - bytes.Add(0xAB); - } - } - } - - private class RvaTypeDefInfo - { - public readonly TypeDef typeDef; - public readonly int index; - public readonly List rvaFields = new List(); - - public RvaTypeDefInfo(TypeDef typeDef, int index) - { - this.typeDef = typeDef; - this.index = index; - } - } - - private RvaField _currentField; - - private RvaTypeDefInfo _currentRvaType; - private readonly List _rvaTypeDefs = new List(); - - private readonly Dictionary _dataHolderTypeBySizes = new Dictionary(); - private bool _done; - - public RvaDataAllocator() - { - } - - public override void Init() - { - _random = EncryptionScope.localRandomCreator(HashUtil.ComputeHash(Module.Name)); - } - - private (FieldDef, FieldDef) CreateDataHolderRvaField(TypeDef dataHolderType) - { - if (_currentRvaType == null || _currentRvaType.rvaFields.Count >= maxTotalRvaDataFieldSizeInHybridCLR / maxRvaDataSize - 1) - { - using (var scope = new DisableTypeDefFindCacheScope(Module)) - { - var rvaTypeDef = new TypeDefUser($"$Obfuz$RVA${_rvaTypeDefs.Count}", Module.CorLibTypes.Object.ToTypeDefOrRef()); - Module.Types.Add(rvaTypeDef); - _currentRvaType = new RvaTypeDefInfo(rvaTypeDef, _rvaTypeDefs.Count); - _rvaTypeDefs.Add(_currentRvaType); - } - } - - var holderField = new FieldDefUser($"$RVA_Data{_currentRvaType.rvaFields.Count}", new FieldSig(dataHolderType.ToTypeSig()), FieldAttributes.InitOnly | FieldAttributes.Static | FieldAttributes.HasFieldRVA); - holderField.DeclaringType = _currentRvaType.typeDef; - - var runtimeValueField = new FieldDefUser($"$RVA_Value{_currentRvaType.rvaFields.Count}", new FieldSig(new SZArraySig(Module.CorLibTypes.Byte)), FieldAttributes.Static | FieldAttributes.Public); - runtimeValueField.DeclaringType = _currentRvaType.typeDef; - return (holderField, runtimeValueField); - } - - private TypeDef GetDataHolderType(int size) - { - size = (size + 15) & ~15; // align to 16 bytes - if (_dataHolderTypeBySizes.TryGetValue(size, out var type)) - return type; - - using (var scope = new DisableTypeDefFindCacheScope(Module)) - { - var dataHolderType = new TypeDefUser($"$ObfuzRVA$DataHolder{size}", Module.Import(typeof(ValueType))); - dataHolderType.Attributes = TypeAttributes.Public | TypeAttributes.Sealed; - dataHolderType.Layout = TypeAttributes.ExplicitLayout; - dataHolderType.PackingSize = 1; - dataHolderType.ClassSize = (uint)size; - _dataHolderTypeBySizes.Add(size, dataHolderType); - Module.Types.Add(dataHolderType); - return dataHolderType; - } - } - - private static int AlignTo(int size, int alignment) - { - return (size + alignment - 1) & ~(alignment - 1); - } - - private RvaField CreateRvaField(int size) - { - TypeDef dataHolderType = GetDataHolderType(size); - var (holderDataField, runtimeValueField) = CreateDataHolderRvaField(dataHolderType); - var newRvaField = new RvaField - { - holderDataField = holderDataField, - runtimeValueField = runtimeValueField, - size = dataHolderType.ClassSize, - bytes = new List((int)dataHolderType.ClassSize), - encryptionOps = _random.NextInt(), - salt = _random.NextInt(), - }; - _currentRvaType.rvaFields.Add(newRvaField); - return newRvaField; - } - - private RvaField GetRvaField(int preservedSize, int alignment) - { - if (_done) - { - throw new Exception("can't GetRvaField after done"); - } - Assert.IsTrue(preservedSize % alignment == 0); - // for big size, create a new field - if (preservedSize >= maxRvaDataSize) - { - return CreateRvaField(preservedSize); - } - - if (_currentField != null) - { - int offset = AlignTo(_currentField.bytes.Count, alignment); - - int expectedSize = offset + preservedSize; - if (expectedSize <= _currentField.size) - { - _currentField.FillPaddingToSize(offset); - return _currentField; - } - - _currentField.FillPaddingToEnd(); - } - _currentField = CreateRvaField(maxRvaDataSize); - return _currentField; - } - - public RvaData Allocate(int value) - { - RvaField field = GetRvaField(4, 4); - int offset = field.bytes.Count; - Assert.IsTrue(offset % 4 == 0); - field.bytes.AddRange(BitConverter.GetBytes(value)); - return new RvaData(field.runtimeValueField, offset, 4); - } - - public RvaData Allocate(long value) - { - RvaField field = GetRvaField(8, 8); - int offset = field.bytes.Count; - Assert.IsTrue(offset % 8 == 0); - field.bytes.AddRange(BitConverter.GetBytes(value)); - return new RvaData(field.runtimeValueField, offset, 8); - } - - public RvaData Allocate(float value) - { - RvaField field = GetRvaField(4, 4); - int offset = field.bytes.Count; - Assert.IsTrue(offset % 4 == 0); - field.bytes.AddRange(BitConverter.GetBytes(value)); - return new RvaData(field.runtimeValueField, offset, 4); - } - - public RvaData Allocate(double value) - { - RvaField field = GetRvaField(8, 8); - int offset = field.bytes.Count; - Assert.IsTrue(offset % 8 == 0); - field.bytes.AddRange(BitConverter.GetBytes(value)); - return new RvaData(field.runtimeValueField, offset, 8); - } - - public RvaData Allocate(string value) - { - byte[] bytes = Encoding.UTF8.GetBytes(value); - return Allocate(bytes); - } - - public RvaData Allocate(byte[] value) - { - RvaField field = GetRvaField(value.Length, 1); - int offset = field.bytes.Count; - field.bytes.AddRange(value); - return new RvaData(field.runtimeValueField, offset, value.Length); - } - - - private void AddVerifyCodes(IList insts, DefaultMetadataImporter importer) - { - int verifyIntValue = 0x12345678; - EncryptionScopeInfo encryptionScope = this.EncryptionScope; - IRandom verifyRandom = encryptionScope.localRandomCreator(verifyIntValue); - int verifyOps = EncryptionUtil.GenerateEncryptionOpCodes(verifyRandom, encryptionScope.encryptor, 4); - int verifySalt = verifyRandom.NextInt(); - int encryptedVerifyIntValue = encryptionScope.encryptor.Encrypt(verifyIntValue, verifyOps, verifySalt); - - insts.Add(Instruction.Create(OpCodes.Ldc_I4, verifyIntValue)); - insts.Add(Instruction.CreateLdcI4(encryptedVerifyIntValue)); - insts.Add(Instruction.CreateLdcI4(verifyOps)); - insts.Add(Instruction.CreateLdcI4(verifySalt)); - insts.Add(Instruction.Create(OpCodes.Call, importer.DecryptInt)); - insts.Add(Instruction.Create(OpCodes.Call, importer.VerifySecretKey)); - - } - - private void CreateCCtorOfRvaTypeDef() - { - foreach (RvaTypeDefInfo rvaTypeDef in _rvaTypeDefs) - { - ModuleDef mod = rvaTypeDef.typeDef.Module; - var cctorMethod = new MethodDefUser(".cctor", - MethodSig.CreateStatic(Module.CorLibTypes.Void), - MethodImplAttributes.IL | MethodImplAttributes.Managed, - MethodAttributes.Static | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName | MethodAttributes.Private); - cctorMethod.DeclaringType = rvaTypeDef.typeDef; - //_rvaTypeDef.Methods.Add(cctor); - var body = new CilBody(); - cctorMethod.Body = body; - var ins = body.Instructions; - - DefaultMetadataImporter importer = this.GetDefaultModuleMetadataImporter(); - AddVerifyCodes(ins, importer); - foreach (var field in rvaTypeDef.rvaFields) - { - // ldc - // newarr - // dup - // stsfld - // ldtoken - // RuntimeHelpers.InitializeArray(array, fieldHandle); - ins.Add(Instruction.Create(OpCodes.Ldc_I4, (int)field.size)); - ins.Add(Instruction.Create(OpCodes.Newarr, field.runtimeValueField.FieldType.Next.ToTypeDefOrRef())); - ins.Add(Instruction.Create(OpCodes.Dup)); - ins.Add(Instruction.Create(OpCodes.Dup)); - ins.Add(Instruction.Create(OpCodes.Stsfld, field.runtimeValueField)); - ins.Add(Instruction.Create(OpCodes.Ldtoken, field.holderDataField)); - ins.Add(Instruction.Create(OpCodes.Call, importer.InitializedArray)); - - // EncryptionService.DecryptBlock(array, field.encryptionOps, field.salt); - ins.Add(Instruction.CreateLdcI4(field.encryptionOps)); - ins.Add(Instruction.Create(OpCodes.Ldc_I4, field.salt)); - ins.Add(Instruction.Create(OpCodes.Call, importer.DecryptBlock)); - - } - ins.Add(Instruction.Create(OpCodes.Ret)); - } - } - - private void SetFieldsRVA() - { - foreach (var field in _rvaTypeDefs.SelectMany(t => t.rvaFields)) - { - Assert.IsTrue(field.bytes.Count <= field.size); - if (field.bytes.Count < field.size) - { - field.FillPaddingToEnd(); - } - byte[] data = field.bytes.ToArray(); - EncryptionScope.encryptor.EncryptBlock(data, field.encryptionOps, field.salt); - field.holderDataField.InitialValue = data; - } - } - - public override void Done() - { - if (_done) - { - throw new Exception("can't call Done twice"); - } - _done = true; - SetFieldsRVA(); - CreateCCtorOfRvaTypeDef(); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Data/RvaDataAllocator.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Data/RvaDataAllocator.cs.meta deleted file mode 100644 index c1f94e80..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Data/RvaDataAllocator.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: c00ca514f46605645bf40b0135e7e504 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Emit.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Emit.meta deleted file mode 100644 index d13f8ab9..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Emit.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: a513a192808ba5f47b1ef8a3ecf02533 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Emit/BasicBlockCollection.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Emit/BasicBlockCollection.cs deleted file mode 100644 index bab76322..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Emit/BasicBlockCollection.cs +++ /dev/null @@ -1,310 +0,0 @@ -using dnlib.DotNet; -using dnlib.DotNet.Emit; -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Obfuz.Emit -{ - public class BasicBlock - { - public readonly List instructions = new List(); - - public readonly List inBlocks = new List(); - - public readonly List outBlocks = new List(); - - public bool inLoop; - - public void AddTargetBasicBlock(BasicBlock target) - { - if (!outBlocks.Contains(target)) - { - outBlocks.Add(target); - } - if (!target.inBlocks.Contains(this)) - { - target.inBlocks.Add(this); - } - } - } - - public class BasicBlockCollection - { - private readonly MethodDef _method; - - private readonly List _blocks = new List(); - private readonly Dictionary _inst2BlockMap = new Dictionary(); - - public IList Blocks => _blocks; - - public BasicBlockCollection(MethodDef method, bool computeInLoop) - { - _method = method; - HashSet splitPoints = BuildSplitPoint(method); - BuildBasicBlocks(method, splitPoints); - BuildInOutGraph(method); - if (computeInLoop) - { - ComputeBlocksInLoop(); - } - } - - public void ComputeBlocksInLoop() - { - var loopBlocks = FindLoopBlocks(_blocks); - foreach (var block in loopBlocks) - { - block.inLoop = true; - } - } - - public BasicBlock GetBasicBlockByInstruction(Instruction inst) - { - return _inst2BlockMap[inst]; - } - - private HashSet BuildSplitPoint(MethodDef method) - { - var insts = method.Body.Instructions; - var splitPoints = new HashSet(); - foreach (ExceptionHandler eh in method.Body.ExceptionHandlers) - { - if (eh.TryStart != null) - { - splitPoints.Add(eh.TryStart); - } - if (eh.TryEnd != null) - { - splitPoints.Add(eh.TryEnd); - } - if (eh.HandlerStart != null) - { - splitPoints.Add(eh.HandlerStart); - } - if (eh.HandlerEnd != null) - { - splitPoints.Add(eh.HandlerEnd); - } - if (eh.FilterStart != null) - { - splitPoints.Add(eh.FilterStart); - } - } - - for (int i = 0, n = insts.Count; i < n; i++) - { - Instruction curInst = insts[i]; - Instruction nextInst = i + 1 < n ? insts[i + 1] : null; - switch (curInst.OpCode.FlowControl) - { - case FlowControl.Branch: - { - if (nextInst != null) - { - splitPoints.Add(nextInst); - } - splitPoints.Add((Instruction)curInst.Operand); - break; - } - case FlowControl.Cond_Branch: - { - if (nextInst != null) - { - splitPoints.Add(nextInst); - } - if (curInst.Operand is Instruction targetInst) - { - splitPoints.Add(targetInst); - } - else if (curInst.Operand is Instruction[] targetInsts) - { - foreach (var target in targetInsts) - { - splitPoints.Add(target); - } - } - break; - } - case FlowControl.Return: - { - if (nextInst != null) - { - splitPoints.Add(nextInst); - } - break; - } - case FlowControl.Throw: - { - if (nextInst != null) - { - splitPoints.Add(nextInst); - } - break; - } - } - } - return splitPoints; - } - - - private void BuildBasicBlocks(MethodDef method, HashSet splitPoints) - { - var insts = method.Body.Instructions; - - - BasicBlock curBlock = new BasicBlock(); - foreach (Instruction inst in insts) - { - if (splitPoints.Contains(inst) && curBlock.instructions.Count > 0) - { - _blocks.Add(curBlock); - curBlock = new BasicBlock(); - } - curBlock.instructions.Add(inst); - _inst2BlockMap.Add(inst, curBlock); - } - if (curBlock.instructions.Count > 0) - { - _blocks.Add(curBlock); - } - } - - private void BuildInOutGraph(MethodDef method) - { - var insts = method.Body.Instructions; - for (int i = 0, n = _blocks.Count; i < n; i++) - { - BasicBlock curBlock = _blocks[i]; - BasicBlock nextBlock = i + 1 < n ? _blocks[i + 1] : null; - Instruction lastInst = curBlock.instructions.Last(); - switch (lastInst.OpCode.FlowControl) - { - case FlowControl.Branch: - { - Instruction targetInst = (Instruction)lastInst.Operand; - BasicBlock targetBlock = GetBasicBlockByInstruction(targetInst); - curBlock.AddTargetBasicBlock(targetBlock); - break; - } - case FlowControl.Cond_Branch: - { - if (lastInst.Operand is Instruction targetInst) - { - BasicBlock targetBlock = GetBasicBlockByInstruction(targetInst); - curBlock.AddTargetBasicBlock(targetBlock); - } - else if (lastInst.Operand is Instruction[] targetInsts) - { - foreach (var target in targetInsts) - { - BasicBlock targetBlock = GetBasicBlockByInstruction(target); - curBlock.AddTargetBasicBlock(targetBlock); - } - } - else - { - throw new Exception("Invalid operand type for conditional branch"); - } - if (nextBlock != null) - { - curBlock.AddTargetBasicBlock(nextBlock); - } - break; - } - case FlowControl.Call: - case FlowControl.Next: - { - if (nextBlock != null) - { - curBlock.AddTargetBasicBlock(nextBlock); - } - break; - } - case FlowControl.Return: - case FlowControl.Throw: - { - break; - } - default: throw new NotSupportedException($"Unsupported flow control: {lastInst.OpCode.FlowControl} in method {method.FullName}"); - } - } - } - - private static HashSet FindLoopBlocks(List allBlocks) - { - // Tarjan算法找强连通分量 - var sccList = FindStronglyConnectedComponents(allBlocks); - - // 筛选有效循环 - var loopBlocks = new HashSet(); - foreach (var scc in sccList) - { - // 有效循环需满足以下条件之一: - // 1. 分量包含多个块 - // 2. 单个块有自环(跳转自己) - if (scc.Count > 1 || - (scc.Count == 1 && scc[0].outBlocks.Contains(scc[0]))) - { - foreach (var block in scc) - { - loopBlocks.Add(block); - } - } - } - return loopBlocks; - } - - private static List> FindStronglyConnectedComponents(List allBlocks) - { - int index = 0; - var stack = new Stack(); - var indexes = new Dictionary(); - var lowLinks = new Dictionary(); - var onStack = new HashSet(); - var sccList = new List>(); - - foreach (var block in allBlocks.Where(b => !indexes.ContainsKey(b))) - { - StrongConnect(block); - } - - return sccList; - - void StrongConnect(BasicBlock v) - { - indexes[v] = index; - lowLinks[v] = index; - index++; - stack.Push(v); - onStack.Add(v); - - foreach (var w in v.outBlocks) - { - if (!indexes.ContainsKey(w)) - { - StrongConnect(w); - lowLinks[v] = System.Math.Min(lowLinks[v], lowLinks[w]); - } - else if (onStack.Contains(w)) - { - lowLinks[v] = System.Math.Min(lowLinks[v], indexes[w]); - } - } - - if (lowLinks[v] == indexes[v]) - { - var scc = new List(); - BasicBlock w; - do - { - w = stack.Pop(); - onStack.Remove(w); - scc.Add(w); - } while (!w.Equals(v)); - sccList.Add(scc); - } - } - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Emit/BasicBlockCollection.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Emit/BasicBlockCollection.cs.meta deleted file mode 100644 index dabfa3b4..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Emit/BasicBlockCollection.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 77c19c023bb7f77489998d994a3be1bd -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Emit/DefaultMetadataImporter.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Emit/DefaultMetadataImporter.cs deleted file mode 100644 index 6399b428..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Emit/DefaultMetadataImporter.cs +++ /dev/null @@ -1,423 +0,0 @@ -using dnlib.DotNet; -using System; -using System.Reflection; -using UnityEngine.Assertions; - -namespace Obfuz.Emit -{ - public class EncryptionServiceMetadataImporter - { - private readonly ModuleDef _module; - private readonly Type _encryptionServiceType; - - private IMethod _encryptBlock; - private IMethod _decryptBlock; - private IMethod _encryptInt; - private IMethod _decryptInt; - private IMethod _encryptLong; - private IMethod _decryptLong; - private IMethod _encryptFloat; - private IMethod _decryptFloat; - private IMethod _encryptDouble; - private IMethod _decryptDouble; - private IMethod _encryptString; - private IMethod _decryptString; - private IMethod _encryptBytes; - private IMethod _decryptBytes; - - private IMethod _decryptFromRvaInt; - private IMethod _decryptFromRvaLong; - private IMethod _decryptFromRvaFloat; - private IMethod _decryptFromRvaDouble; - private IMethod _decryptFromRvaString; - private IMethod _decryptFromRvaBytes; - - private IMethod _decryptInitializeArray; - - public IMethod EncryptBlock => _encryptBlock; - public IMethod DecryptBlock => _decryptBlock; - - public IMethod EncryptInt => _encryptInt; - public IMethod DecryptInt => _decryptInt; - public IMethod EncryptLong => _encryptLong; - public IMethod DecryptLong => _decryptLong; - public IMethod EncryptFloat => _encryptFloat; - public IMethod DecryptFloat => _decryptFloat; - public IMethod EncryptDouble => _encryptDouble; - public IMethod DecryptDouble => _decryptDouble; - public IMethod EncryptString => _encryptString; - public IMethod DecryptString => _decryptString; - public IMethod EncryptBytes => _encryptBytes; - public IMethod DecryptBytes => _decryptBytes; - - public IMethod DecryptFromRvaInt => _decryptFromRvaInt; - public IMethod DecryptFromRvaLong => _decryptFromRvaLong; - public IMethod DecryptFromRvaFloat => _decryptFromRvaFloat; - public IMethod DecryptFromRvaDouble => _decryptFromRvaDouble; - public IMethod DecryptFromRvaBytes => _decryptFromRvaBytes; - public IMethod DecryptFromRvaString => _decryptFromRvaString; - - public IMethod DecryptInitializeArray => _decryptInitializeArray; - - public EncryptionServiceMetadataImporter(ModuleDef mod, Type encryptionServiceType) - { - _module = mod; - _encryptionServiceType = encryptionServiceType; - _encryptBlock = mod.Import(encryptionServiceType.GetMethod("EncryptBlock", new[] { typeof(byte[]), typeof(int), typeof(int) })); - Assert.IsNotNull(_encryptBlock); - _decryptBlock = mod.Import(encryptionServiceType.GetMethod("DecryptBlock", new[] { typeof(byte[]), typeof(int), typeof(int) })); - Assert.IsNotNull(_decryptBlock); - _encryptInt = mod.Import(encryptionServiceType.GetMethod("Encrypt", new[] { typeof(int), typeof(int), typeof(int) })); - Assert.IsNotNull(_encryptInt); - _decryptInt = mod.Import(encryptionServiceType.GetMethod("Decrypt", new[] { typeof(int), typeof(int), typeof(int) })); - Assert.IsNotNull(_decryptInt); - _encryptLong = mod.Import(encryptionServiceType.GetMethod("Encrypt", new[] { typeof(long), typeof(int), typeof(int) })); - Assert.IsNotNull(_encryptLong); - _decryptLong = mod.Import(encryptionServiceType.GetMethod("Decrypt", new[] { typeof(long), typeof(int), typeof(int) })); - Assert.IsNotNull(_decryptLong); - _encryptFloat = mod.Import(encryptionServiceType.GetMethod("Encrypt", new[] { typeof(float), typeof(int), typeof(int) })); - Assert.IsNotNull(_encryptFloat); - _decryptFloat = mod.Import(encryptionServiceType.GetMethod("Decrypt", new[] { typeof(float), typeof(int), typeof(int) })); - Assert.IsNotNull(_decryptFloat); - _encryptDouble = mod.Import(encryptionServiceType.GetMethod("Encrypt", new[] { typeof(double), typeof(int), typeof(int) })); - Assert.IsNotNull(_encryptDouble); - _decryptDouble = mod.Import(encryptionServiceType.GetMethod("Decrypt", new[] { typeof(double), typeof(int), typeof(int) })); - Assert.IsNotNull(_decryptDouble); - _encryptString = mod.Import(encryptionServiceType.GetMethod("Encrypt", new[] { typeof(string), typeof(int), typeof(int) })); - Assert.IsNotNull(_encryptString); - _decryptString = mod.Import(encryptionServiceType.GetMethod("DecryptString", new[] { typeof(byte[]), typeof(int), typeof(int), typeof(int), typeof(int) })); - Assert.IsNotNull(_decryptString); - _encryptBytes = mod.Import(encryptionServiceType.GetMethod("Encrypt", new[] { typeof(byte[]), typeof(int), typeof(int), typeof(int), typeof(int) })); - Assert.IsNotNull(_encryptBytes); - _decryptBytes = mod.Import(encryptionServiceType.GetMethod("Decrypt", new[] { typeof(byte[]), typeof(int), typeof(int), typeof(int), typeof(int) })); - Assert.IsNotNull(_decryptBytes); - - _decryptFromRvaInt = mod.Import(encryptionServiceType.GetMethod("DecryptFromRvaInt", new[] { typeof(byte[]), typeof(int), typeof(int), typeof(int) })); - Assert.IsNotNull(_decryptFromRvaInt); - _decryptFromRvaLong = mod.Import(encryptionServiceType.GetMethod("DecryptFromRvaLong", new[] { typeof(byte[]), typeof(int), typeof(int), typeof(int) })); - Assert.IsNotNull(_decryptFromRvaLong); - _decryptFromRvaFloat = mod.Import(encryptionServiceType.GetMethod("DecryptFromRvaFloat", new[] { typeof(byte[]), typeof(int), typeof(int), typeof(int) })); - Assert.IsNotNull(_decryptFromRvaFloat); - _decryptFromRvaDouble = mod.Import(encryptionServiceType.GetMethod("DecryptFromRvaDouble", new[] { typeof(byte[]), typeof(int), typeof(int), typeof(int) })); - Assert.IsNotNull(_decryptFromRvaDouble); - _decryptFromRvaBytes = mod.Import(encryptionServiceType.GetMethod("DecryptFromRvaBytes", new[] { typeof(byte[]), typeof(int), typeof(int), typeof(int), typeof(int) })); - Assert.IsNotNull(_decryptFromRvaBytes); - _decryptFromRvaString = mod.Import(encryptionServiceType.GetMethod("DecryptFromRvaString", new[] { typeof(byte[]), typeof(int), typeof(int), typeof(int), typeof(int) })); - Assert.IsNotNull(_decryptFromRvaString); - _decryptInitializeArray = mod.Import(encryptionServiceType.GetMethod("DecryptInitializeArray", new[] { typeof(System.Array), typeof(System.RuntimeFieldHandle), typeof(int), typeof(int), typeof(int) })); - Assert.IsNotNull(_decryptInitializeArray); - } - } - - public class DefaultMetadataImporter : GroupByModuleEntityBase - { - private EncryptionServiceMetadataImporter _defaultEncryptionServiceMetadataImporter; - - - private EncryptionServiceMetadataImporter _staticDefaultEncryptionServiceMetadataImporter; - private EncryptionServiceMetadataImporter _dynamicDefaultEncryptionServiceMetadataImporter; - - public DefaultMetadataImporter() - { - } - - public override void Init() - { - ModuleDef mod = Module; - - var constUtilityType = typeof(ConstUtility); - - _castIntAsFloat = mod.Import(constUtilityType.GetMethod("CastIntAsFloat")); - Assert.IsNotNull(_castIntAsFloat, "CastIntAsFloat not found"); - _castLongAsDouble = mod.Import(constUtilityType.GetMethod("CastLongAsDouble")); - Assert.IsNotNull(_castLongAsDouble, "CastLongAsDouble not found"); - _castFloatAsInt = mod.Import(constUtilityType.GetMethod("CastFloatAsInt")); - Assert.IsNotNull(_castFloatAsInt, "CastFloatAsInt not found"); - _castDoubleAsLong = mod.Import(constUtilityType.GetMethod("CastDoubleAsLong")); - Assert.IsNotNull(_castDoubleAsLong, "CastDoubleAsLong not found"); - - _initializeArray = mod.Import(typeof(System.Runtime.CompilerServices.RuntimeHelpers).GetMethod("InitializeArray", new[] { typeof(Array), typeof(RuntimeFieldHandle) })); - Assert.IsNotNull(_initializeArray); - _verifySecretKey = mod.Import(typeof(AssetUtility).GetMethod("VerifySecretKey", new[] { typeof(int), typeof(int) })); - Assert.IsNotNull(_verifySecretKey, "VerifySecretKey not found"); - - _obfuscationTypeMapperRegisterType = mod.Import(typeof(ObfuscationTypeMapper).GetMethod("RegisterType", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static, null, new[] { typeof(string) }, null)); - Assert.IsNotNull(_obfuscationTypeMapperRegisterType, "ObfuscationTypeMapper.RegisterType not found"); - - var exprUtilityType = typeof(ExprUtility); - _addInt = mod.Import(exprUtilityType.GetMethod("Add", new[] { typeof(int), typeof(int) })); - Assert.IsNotNull(_addInt, "ExprUtility.Add(int, int) not found"); - _addLong = mod.Import(exprUtilityType.GetMethod("Add", new[] { typeof(long), typeof(long) })); - Assert.IsNotNull(_addLong, "ExprUtility.Add(long, long) not found"); - _addFloat = mod.Import(exprUtilityType.GetMethod("Add", new[] { typeof(float), typeof(float) })); - Assert.IsNotNull(_addFloat, "ExprUtility.Add(float, float) not found"); - _addDouble = mod.Import(exprUtilityType.GetMethod("Add", new[] { typeof(double), typeof(double) })); - Assert.IsNotNull(_addDouble, "ExprUtility.Add(double, double) not found"); - _addIntPtr = mod.Import(exprUtilityType.GetMethod("Add", new[] { typeof(IntPtr), typeof(IntPtr) })); - Assert.IsNotNull(_addIntPtr, "ExprUtility.Add(IntPtr, IntPtr) not found"); - _addIntPtrInt = mod.Import(exprUtilityType.GetMethod("Add", new[] { typeof(IntPtr), typeof(int) })); - Assert.IsNotNull(_addIntPtrInt, "ExprUtility.Add(IntPtr, int) not found"); - - _subtractInt = mod.Import(exprUtilityType.GetMethod("Subtract", new[] { typeof(int), typeof(int) })); - Assert.IsNotNull(_subtractInt, "ExprUtility.Subtract(int, int) not found"); - _subtractLong = mod.Import(exprUtilityType.GetMethod("Subtract", new[] { typeof(long), typeof(long) })); - Assert.IsNotNull(_subtractLong, "ExprUtility.Subtract(long, long) not found"); - _subtractFloat = mod.Import(exprUtilityType.GetMethod("Subtract", new[] { typeof(float), typeof(float) })); - Assert.IsNotNull(_subtractFloat, "ExprUtility.Subtract(float, float) not found"); - _subtractDouble = mod.Import(exprUtilityType.GetMethod("Subtract", new[] { typeof(double), typeof(double) })); - Assert.IsNotNull(_subtractDouble, "ExprUtility.Subtract(double, double) not found"); - _subtractIntPtr = mod.Import(exprUtilityType.GetMethod("Subtract", new[] { typeof(IntPtr), typeof(IntPtr) })); - Assert.IsNotNull(_subtractIntPtr, "ExprUtility.Subtract(IntPtr, IntPtr) not found"); - _subtractIntPtrInt = mod.Import(exprUtilityType.GetMethod("Subtract", new[] { typeof(IntPtr), typeof(int) })); - Assert.IsNotNull(_subtractIntPtrInt, "ExprUtility.Subtract(IntPtr, int) not found"); - - _multiplyInt = mod.Import(exprUtilityType.GetMethod("Multiply", new[] { typeof(int), typeof(int) })); - Assert.IsNotNull(_multiplyInt, "ExprUtility.Multiply(int, int) not found"); - _multiplyLong = mod.Import(exprUtilityType.GetMethod("Multiply", new[] { typeof(long), typeof(long) })); - Assert.IsNotNull(_multiplyLong, "ExprUtility.Multiply(long, long) not found"); - _multiplyFloat = mod.Import(exprUtilityType.GetMethod("Multiply", new[] { typeof(float), typeof(float) })); - Assert.IsNotNull(_multiplyFloat, "ExprUtility.Multiply(float, float) not found"); - _multiplyDouble = mod.Import(exprUtilityType.GetMethod("Multiply", new[] { typeof(double), typeof(double) })); - Assert.IsNotNull(_multiplyDouble, "ExprUtility.Multiply(double, double) not found"); - _multiplyIntPtr = mod.Import(exprUtilityType.GetMethod("Multiply", new[] { typeof(IntPtr), typeof(IntPtr) })); - Assert.IsNotNull(_multiplyIntPtr, "ExprUtility.Multiply(IntPtr, IntPtr) not found"); - _multiplyIntPtrInt = mod.Import(exprUtilityType.GetMethod("Multiply", new[] { typeof(IntPtr), typeof(int) })); - Assert.IsNotNull(_multiplyIntPtrInt, "ExprUtility.Multiply(IntPtr, int) not found"); - - _divideInt = mod.Import(exprUtilityType.GetMethod("Divide", new[] { typeof(int), typeof(int) })); - Assert.IsNotNull(_divideInt, "ExprUtility.Divide(int, int) not found"); - _divideLong = mod.Import(exprUtilityType.GetMethod("Divide", new[] { typeof(long), typeof(long) })); - Assert.IsNotNull(_divideLong); - _divideFloat = mod.Import(exprUtilityType.GetMethod("Divide", new[] { typeof(float), typeof(float) })); - Assert.IsNotNull(_divideFloat, "ExprUtility.Divide(float, float) not found"); - _divideDouble = mod.Import(exprUtilityType.GetMethod("Divide", new[] { typeof(double), typeof(double) })); - Assert.IsNotNull(_divideDouble, "ExprUtility.Divide(double, double) not found"); - _divideUnInt = mod.Import(exprUtilityType.GetMethod("DivideUn", new[] { typeof(int), typeof(int) })); - Assert.IsNotNull(_divideUnInt, "ExprUtility.DivideUn(int, int) not found"); - _divideUnLong = mod.Import(exprUtilityType.GetMethod("DivideUn", new[] { typeof(long), typeof(long) })); - Assert.IsNotNull(_divideUnLong, "ExprUtility.DivideUn(long, long) not found"); - _remInt = mod.Import(exprUtilityType.GetMethod("Rem", new[] { typeof(int), typeof(int) })); - Assert.IsNotNull(_remInt, "ExprUtility.Rem(int, int) not found"); - _remLong = mod.Import(exprUtilityType.GetMethod("Rem", new[] { typeof(long), typeof(long) })); - Assert.IsNotNull(_remLong, "ExprUtility.Rem(long, long) not found"); - _remFloat = mod.Import(exprUtilityType.GetMethod("Rem", new[] { typeof(float), typeof(float) })); - Assert.IsNotNull(_remFloat, "ExprUtility.Rem(float, float) not found"); - _remDouble = mod.Import(exprUtilityType.GetMethod("Rem", new[] { typeof(double), typeof(double) })); - Assert.IsNotNull(_remDouble, "ExprUtility.Rem(double, double) not found"); - _remUnInt = mod.Import(exprUtilityType.GetMethod("RemUn", new[] { typeof(int), typeof(int) })); - Assert.IsNotNull(_remUnInt, "ExprUtility.RemUn(int, int) not found"); - _remUnLong = mod.Import(exprUtilityType.GetMethod("RemUn", new[] { typeof(long), typeof(long) })); - Assert.IsNotNull(_remUnLong, "ExprUtility.RemUn(long, long) not found"); - _negInt = mod.Import(exprUtilityType.GetMethod("Negate", new[] { typeof(int) })); - Assert.IsNotNull(_negInt, "ExprUtility.Negate(int) not found"); - _negLong = mod.Import(exprUtilityType.GetMethod("Negate", new[] { typeof(long) })); - Assert.IsNotNull(_negLong, "ExprUtility.Negate(long) not found"); - _negFloat = mod.Import(exprUtilityType.GetMethod("Negate", new[] { typeof(float) })); - Assert.IsNotNull(_negFloat, "ExprUtility.Negate(float) not found"); - _negDouble = mod.Import(exprUtilityType.GetMethod("Negate", new[] { typeof(double) })); - Assert.IsNotNull(_negDouble, "ExprUtility.Negate(double) not found"); - - _andInt = mod.Import(exprUtilityType.GetMethod("And", new[] { typeof(int), typeof(int) })); - Assert.IsNotNull(_andInt, "ExprUtility.And(int, int) not found"); - _andLong = mod.Import(exprUtilityType.GetMethod("And", new[] { typeof(long), typeof(long) })); - Assert.IsNotNull(_andLong, "ExprUtility.And(long, long) not found"); - _orInt = mod.Import(exprUtilityType.GetMethod("Or", new[] { typeof(int), typeof(int) })); - Assert.IsNotNull(_orInt, "ExprUtility.Or(int, int) not found"); - _orLong = mod.Import(exprUtilityType.GetMethod("Or", new[] { typeof(long), typeof(long) })); - Assert.IsNotNull(_orLong, "ExprUtility.Or(long, long) not found"); - _xorInt = mod.Import(exprUtilityType.GetMethod("Xor", new[] { typeof(int), typeof(int) })); - Assert.IsNotNull(_xorInt, "ExprUtility.Xor(int, int) not found"); - _xorLong = mod.Import(exprUtilityType.GetMethod("Xor", new[] { typeof(long), typeof(long) })); - Assert.IsNotNull(_xorLong, "ExprUtility.Xor(long, long) not found"); - _notInt = mod.Import(exprUtilityType.GetMethod("Not", new[] { typeof(int) })); - Assert.IsNotNull(_notInt, "ExprUtility.Not(int) not found"); - _notLong = mod.Import(exprUtilityType.GetMethod("Not", new[] { typeof(long) })); - Assert.IsNotNull(_notLong, "ExprUtility.Not(long) not found"); - - _shlInt = mod.Import(exprUtilityType.GetMethod("ShiftLeft", new[] { typeof(int), typeof(int) })); - Assert.IsNotNull(_shlInt, "ExprUtility.ShiftLeft(int, int) not found"); - _shlLong = mod.Import(exprUtilityType.GetMethod("ShiftLeft", new[] { typeof(long), typeof(int) })); - Assert.IsNotNull(_shlLong, "ExprUtility.ShiftLeft(long, int) not found"); - _shrInt = mod.Import(exprUtilityType.GetMethod("ShiftRight", new[] { typeof(int), typeof(int) })); - Assert.IsNotNull(_shrInt, "ExprUtility.ShiftRight(int, int) not found"); - _shrLong = mod.Import(exprUtilityType.GetMethod("ShiftRight", new[] { typeof(long), typeof(int) })); - Assert.IsNotNull(_shrLong, "ExprUtility.ShiftRight(long, int) not found"); - _shrUnInt = mod.Import(exprUtilityType.GetMethod("ShiftRightUn", new[] { typeof(int), typeof(int) })); - Assert.IsNotNull(_shrUnInt, "ExprUtility.ShiftRightUn(int, int) not found"); - _shrUnLong = mod.Import(exprUtilityType.GetMethod("ShiftRightUn", new[] { typeof(long), typeof(int) })); - Assert.IsNotNull(_shrUnLong, "ExprUtility.ShiftRightUn(long, int) not found"); - - - _staticDefaultEncryptionServiceMetadataImporter = new EncryptionServiceMetadataImporter(mod, typeof(EncryptionService)); - _dynamicDefaultEncryptionServiceMetadataImporter = new EncryptionServiceMetadataImporter(mod, typeof(EncryptionService)); - if (EncryptionScopeProvider.IsDynamicSecretAssembly(mod)) - { - _defaultEncryptionServiceMetadataImporter = _dynamicDefaultEncryptionServiceMetadataImporter; - } - else - { - _defaultEncryptionServiceMetadataImporter = _staticDefaultEncryptionServiceMetadataImporter; - } - } - - public override void Done() - { - - } - - public EncryptionServiceMetadataImporter GetEncryptionServiceMetadataImporterOfModule(ModuleDef mod) - { - return EncryptionScopeProvider.IsDynamicSecretAssembly(mod) ? _dynamicDefaultEncryptionServiceMetadataImporter : _staticDefaultEncryptionServiceMetadataImporter; - } - - private ModuleDef _module; - private IMethod _castIntAsFloat; - private IMethod _castLongAsDouble; - private IMethod _castFloatAsInt; - private IMethod _castDoubleAsLong; - private IMethod _initializeArray; - private IMethod _verifySecretKey; - - private IMethod _obfuscationTypeMapperRegisterType; - - private IMethod _addInt; - private IMethod _addLong; - private IMethod _addFloat; - private IMethod _addDouble; - private IMethod _addIntPtr; - private IMethod _addIntPtrInt; - private IMethod _subtractInt; - private IMethod _subtractLong; - private IMethod _subtractFloat; - private IMethod _subtractDouble; - private IMethod _subtractIntPtr; - private IMethod _subtractIntPtrInt; - private IMethod _multiplyInt; - private IMethod _multiplyLong; - private IMethod _multiplyFloat; - private IMethod _multiplyDouble; - private IMethod _multiplyIntPtr; - private IMethod _multiplyIntPtrInt; - private IMethod _divideInt; - private IMethod _divideLong; - private IMethod _divideFloat; - private IMethod _divideDouble; - private IMethod _divideUnInt; - private IMethod _divideUnLong; - private IMethod _remInt; - private IMethod _remLong; - private IMethod _remFloat; - private IMethod _remDouble; - private IMethod _remUnInt; - private IMethod _remUnLong; - private IMethod _negInt; - private IMethod _negLong; - private IMethod _negFloat; - private IMethod _negDouble; - - private IMethod _andInt; - private IMethod _andLong; - private IMethod _orInt; - private IMethod _orLong; - private IMethod _xorInt; - private IMethod _xorLong; - private IMethod _notInt; - private IMethod _notLong; - - private IMethod _shlInt; - private IMethod _shlLong; - private IMethod _shrInt; - private IMethod _shrLong; - private IMethod _shrUnInt; - private IMethod _shrUnLong; - - public IMethod CastIntAsFloat => _castIntAsFloat; - public IMethod CastLongAsDouble => _castLongAsDouble; - public IMethod CastFloatAsInt => _castFloatAsInt; - public IMethod CastDoubleAsLong => _castDoubleAsLong; - - public IMethod InitializedArray => _initializeArray; - - public IMethod VerifySecretKey => _verifySecretKey; - - public IMethod ObfuscationTypeMapperRegisterType => _obfuscationTypeMapperRegisterType; - - public IMethod EncryptBlock => _defaultEncryptionServiceMetadataImporter.EncryptBlock; - public IMethod DecryptBlock => _defaultEncryptionServiceMetadataImporter.DecryptBlock; - - public IMethod EncryptInt => _defaultEncryptionServiceMetadataImporter.EncryptInt; - public IMethod DecryptInt => _defaultEncryptionServiceMetadataImporter.DecryptInt; - public IMethod EncryptLong => _defaultEncryptionServiceMetadataImporter.EncryptLong; - public IMethod DecryptLong => _defaultEncryptionServiceMetadataImporter.DecryptLong; - public IMethod EncryptFloat => _defaultEncryptionServiceMetadataImporter.EncryptFloat; - public IMethod DecryptFloat => _defaultEncryptionServiceMetadataImporter.DecryptFloat; - public IMethod EncryptDouble => _defaultEncryptionServiceMetadataImporter.EncryptDouble; - public IMethod DecryptDouble => _defaultEncryptionServiceMetadataImporter.DecryptDouble; - public IMethod EncryptString => _defaultEncryptionServiceMetadataImporter.EncryptString; - public IMethod DecryptString => _defaultEncryptionServiceMetadataImporter.DecryptString; - public IMethod EncryptBytes => _defaultEncryptionServiceMetadataImporter.EncryptBytes; - public IMethod DecryptBytes => _defaultEncryptionServiceMetadataImporter.DecryptBytes; - - public IMethod DecryptFromRvaInt => _defaultEncryptionServiceMetadataImporter.DecryptFromRvaInt; - public IMethod DecryptFromRvaLong => _defaultEncryptionServiceMetadataImporter.DecryptFromRvaLong; - public IMethod DecryptFromRvaFloat => _defaultEncryptionServiceMetadataImporter.DecryptFromRvaFloat; - public IMethod DecryptFromRvaDouble => _defaultEncryptionServiceMetadataImporter.DecryptFromRvaDouble; - public IMethod DecryptFromRvaBytes => _defaultEncryptionServiceMetadataImporter.DecryptFromRvaBytes; - public IMethod DecryptFromRvaString => _defaultEncryptionServiceMetadataImporter.DecryptFromRvaString; - - public IMethod DecryptInitializeArray => _defaultEncryptionServiceMetadataImporter.DecryptInitializeArray; - - public IMethod AddInt => _addInt; - public IMethod AddLong => _addLong; - public IMethod AddFloat => _addFloat; - public IMethod AddDouble => _addDouble; - public IMethod AddIntPtr => _addIntPtr; - public IMethod AddIntPtrInt => _addIntPtrInt; - public IMethod SubtractInt => _subtractInt; - public IMethod SubtractLong => _subtractLong; - public IMethod SubtractFloat => _subtractFloat; - public IMethod SubtractDouble => _subtractDouble; - public IMethod SubtractIntPtr => _subtractIntPtr; - public IMethod SubtractIntPtrInt => _subtractIntPtrInt; - - public IMethod MultiplyInt => _multiplyInt; - public IMethod MultiplyLong => _multiplyLong; - public IMethod MultiplyFloat => _multiplyFloat; - public IMethod MultiplyDouble => _multiplyDouble; - public IMethod MultiplyIntPtr => _multiplyIntPtr; - public IMethod MultiplyIntPtrInt => _multiplyIntPtrInt; - - public IMethod DivideInt => _divideInt; - public IMethod DivideLong => _divideLong; - public IMethod DivideFloat => _divideFloat; - public IMethod DivideDouble => _divideDouble; - public IMethod DivideUnInt => _divideUnInt; - public IMethod DivideUnLong => _divideUnLong; - public IMethod RemInt => _remInt; - public IMethod RemLong => _remLong; - public IMethod RemFloat => _remFloat; - public IMethod RemDouble => _remDouble; - public IMethod RemUnInt => _remUnInt; - public IMethod RemUnLong => _remUnLong; - public IMethod NegInt => _negInt; - public IMethod NegLong => _negLong; - public IMethod NegFloat => _negFloat; - public IMethod NegDouble => _negDouble; - public IMethod AndInt => _andInt; - public IMethod AndLong => _andLong; - public IMethod OrInt => _orInt; - public IMethod OrLong => _orLong; - public IMethod XorInt => _xorInt; - public IMethod XorLong => _xorLong; - public IMethod NotInt => _notInt; - public IMethod NotLong => _notLong; - public IMethod ShlInt => _shlInt; - public IMethod ShlLong => _shlLong; - public IMethod ShrInt => _shrInt; - public IMethod ShrLong => _shrLong; - public IMethod ShrUnInt => _shrUnInt; - public IMethod ShrUnLong => _shrUnLong; - - - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Emit/DefaultMetadataImporter.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Emit/DefaultMetadataImporter.cs.meta deleted file mode 100644 index c29c6a94..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Emit/DefaultMetadataImporter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 76438ce96146edd469872feada7857ba -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Emit/EntityExtensions.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Emit/EntityExtensions.cs deleted file mode 100644 index 7bc98808..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Emit/EntityExtensions.cs +++ /dev/null @@ -1,15 +0,0 @@ -namespace Obfuz.Emit -{ - public static class EntityExtensions - { - public static T GetEntity(this IGroupByModuleEntity entity) where T : IGroupByModuleEntity, new() - { - return entity.Manager.GetEntity(entity.Module); - } - - public static DefaultMetadataImporter GetDefaultModuleMetadataImporter(this IGroupByModuleEntity entity) - { - return entity.GetEntity(); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Emit/EntityExtensions.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Emit/EntityExtensions.cs.meta deleted file mode 100644 index 119466e8..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Emit/EntityExtensions.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 6e9557733f180764692756653eb60f88 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Emit/EvalStackCalculator.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Emit/EvalStackCalculator.cs deleted file mode 100644 index a7fd4f3b..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Emit/EvalStackCalculator.cs +++ /dev/null @@ -1,967 +0,0 @@ -using dnlib.DotNet; -using dnlib.DotNet.Emit; -using Obfuz.Utils; -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using UnityEngine.Assertions; - -namespace Obfuz.Emit -{ - enum EvalDataType - { - None, - Int32, - Int64, - Float, - Double, - I, - Ref, - ValueType, - Token, - Unknown, - } - - struct EvalDataTypeWithSig - { - public readonly EvalDataType type; - public readonly TypeSig typeSig; - public EvalDataTypeWithSig(EvalDataType type, TypeSig typeSig) - { - this.type = type; - this.typeSig = typeSig; - } - public override string ToString() - { - return $"{type} ({typeSig})"; - } - } - - class InstructionParameterInfo - { - public readonly EvalDataType op1; - public readonly EvalDataType op2; - public readonly EvalDataType retType; - public InstructionParameterInfo(EvalDataType op1, EvalDataType op2, EvalDataType retType) - { - this.op1 = op1; - this.op2 = op2; - this.retType = retType; - } - } - - - class EvalStackState - { - public bool visited; - - public readonly List inputStackDatas = new List(); - public readonly List runStackDatas = new List(); - } - - class EvalStackCalculator - { - private readonly MethodDef _method; - private readonly BasicBlockCollection _basicBlocks; - private readonly Dictionary _instructionParameterInfos = new Dictionary(); - private readonly Dictionary _evalStackTopDataTypeAfterInstructions = new Dictionary(); - private readonly Dictionary _blockEvalStackStates; - - public EvalStackCalculator(MethodDef method) - { - _method = method; - _basicBlocks = new BasicBlockCollection(method, false); - _blockEvalStackStates = _basicBlocks.Blocks.ToDictionary(b => b, b => new EvalStackState()); - - SimulateRunAllBlocks(); - } - - public BasicBlockCollection BasicBlockCollection => _basicBlocks; - - public bool TryGetParameterInfo(Instruction inst, out InstructionParameterInfo info) - { - return _instructionParameterInfos.TryGetValue(inst, out info); - } - - public bool TryGetPushResult(Instruction inst, out EvalDataType result) - { - return _evalStackTopDataTypeAfterInstructions.TryGetValue(inst, out result); - } - - public EvalStackState GetEvalStackState(BasicBlock basicBlock) - { - return _blockEvalStackStates[basicBlock]; - } - - private void PushStack(List datas, TypeSig type) - { - type = type.RemovePinnedAndModifiers(); - switch (type.ElementType) - { - case ElementType.Void: break; - case ElementType.Boolean: - case ElementType.Char: - case ElementType.I1: - case ElementType.U1: - case ElementType.I2: - case ElementType.U2: - case ElementType.I4: - case ElementType.U4: - datas.Add(new EvalDataTypeWithSig(EvalDataType.Int32, null)); - break; - case ElementType.I8: - case ElementType.U8: - datas.Add(new EvalDataTypeWithSig(EvalDataType.Int64, null)); - break; - case ElementType.R4: - datas.Add(new EvalDataTypeWithSig(EvalDataType.Float, null)); - break; - case ElementType.R8: - datas.Add(new EvalDataTypeWithSig(EvalDataType.Double, null)); - break; - case ElementType.I: - case ElementType.U: - case ElementType.Ptr: - case ElementType.FnPtr: - case ElementType.ByRef: - datas.Add(new EvalDataTypeWithSig(EvalDataType.I, null)); - break; - case ElementType.String: - case ElementType.Class: - case ElementType.Array: - case ElementType.SZArray: - case ElementType.Object: - datas.Add(new EvalDataTypeWithSig(EvalDataType.Ref, type)); - break; - case ElementType.ValueType: - { - TypeDef typeDef = type.ToTypeDefOrRef().ResolveTypeDefThrow(); - if (typeDef.IsEnum) - { - PushStack(datas, typeDef.GetEnumUnderlyingType()); - } - else - { - PushStack(datas, new EvalDataTypeWithSig(EvalDataType.ValueType, type)); - } - break; - } - case ElementType.GenericInst: - { - GenericInstSig genericInstSig = (GenericInstSig)type; - TypeDef typeDef = genericInstSig.GenericType.ToTypeDefOrRef().ResolveTypeDefThrow(); - if (!typeDef.IsValueType) - { - PushStack(datas, new EvalDataTypeWithSig(EvalDataType.Ref, type)); - } - else if (typeDef.IsEnum) - { - PushStack(datas, typeDef.GetEnumUnderlyingType()); - } - else - { - PushStack(datas, new EvalDataTypeWithSig(EvalDataType.ValueType, type)); - } - break; - } - case ElementType.TypedByRef: - { - // TypedByRef is a special type used in dynamic method invocation and reflection. - // It is treated as a reference type in the evaluation stack. - PushStack(datas, new EvalDataTypeWithSig(EvalDataType.ValueType, type)); - break; - } - case ElementType.Var: - case ElementType.MVar: - PushStack(datas, new EvalDataTypeWithSig(EvalDataType.ValueType, type)); - break; - case ElementType.ValueArray: - case ElementType.R: - case ElementType.CModOpt: - case ElementType.CModReqd: - case ElementType.Internal: - case ElementType.Module: - case ElementType.Sentinel: - PushStack(datas, EvalDataType.Unknown); - break; - - default: throw new Exception($"Unsupported type: {type} in method: {_method.FullName}."); - } - } - - private void PushStack(List datas, ITypeDefOrRef type) - { - PushStack(datas, type.ToTypeSig()); - } - - private void PushStack(List datas, EvalDataType type) - { - Assert.IsTrue(type != EvalDataType.ValueType, "Cannot push EvalDataType.Value without type sig onto the stack."); - datas.Add(new EvalDataTypeWithSig(type, null)); - } - - private void PushStack(List datas, EvalDataTypeWithSig type) - { - datas.Add(type); - } - - private void PushStackObject(List datas) - { - datas.Add(new EvalDataTypeWithSig(EvalDataType.Ref, _method.Module.CorLibTypes.Object)); - } - - private EvalDataType CalcBasicBinOpRetType(EvalDataType op1, EvalDataType op2) - { - switch (op1) - { - case EvalDataType.Int32: - { - switch (op2) - { - case EvalDataType.Int32: return EvalDataType.Int32; - case EvalDataType.Int64: return EvalDataType.Int64; - case EvalDataType.I: return EvalDataType.I; - default: throw new Exception($"Unsupported operand type: {op2} for {op1} in binary operation."); - } - } - case EvalDataType.Int64: - { - switch (op2) - { - case EvalDataType.Int32: return EvalDataType.Int64; - case EvalDataType.Int64: - case EvalDataType.I: - return EvalDataType.Int64; - default: throw new Exception($"Unsupported operand type: {op2} for {op1} in binary operation."); - } - } - case EvalDataType.I: - { - switch (op2) - { - case EvalDataType.Int32: return EvalDataType.I; - case EvalDataType.Int64: return EvalDataType.Int64; - case EvalDataType.I: return EvalDataType.I; - default: throw new Exception($"Unsupported operand type: {op2} for {op1} in binary operation."); - } - } - case EvalDataType.Float: - { - switch (op2) - { - case EvalDataType.Float: return EvalDataType.Float; - case EvalDataType.Double: return EvalDataType.Double; - default: throw new Exception($"Unsupported operand type: {op2} for {op1} in binary operation."); - } - } - case EvalDataType.Double: - { - switch (op2) - { - case EvalDataType.Float: - case EvalDataType.Double: return EvalDataType.Double; - default: throw new Exception($"Unsupported operand type: {op2} for {op1} in binary operation."); - } - } - default: throw new Exception($"Unsupported operand type: {op1} in binary operation."); - } - } - - private void SimulateRunAllBlocks() - { - bool methodHasReturnValue = !MetaUtil.IsVoidType(_method.ReturnType); - - CilBody body = _method.Body; - if (body.HasExceptionHandlers) - { - foreach (ExceptionHandler handler in body.ExceptionHandlers) - { - if (handler.IsFilter) - { - BasicBlock bb = _basicBlocks.GetBasicBlockByInstruction(handler.FilterStart); - var inputStackDatas = _blockEvalStackStates[bb].inputStackDatas; - if (inputStackDatas.Count == 0) - { - inputStackDatas.Add(new EvalDataTypeWithSig(EvalDataType.Ref, handler.CatchType.ToTypeSig())); - } - } - if (handler.IsCatch || handler.IsFilter) - { - BasicBlock bb = _basicBlocks.GetBasicBlockByInstruction(handler.HandlerStart); - var inputStackDatas = _blockEvalStackStates[bb].inputStackDatas; - if (inputStackDatas.Count == 0) - { - inputStackDatas.Add(new EvalDataTypeWithSig(EvalDataType.Ref, handler.CatchType.ToTypeSig())); - } - } - } - } - - var newPushedDatas = new List(); - IList methodTypeGenericArgument = _method.DeclaringType.GenericParameters.Count > 0 - ? (IList)_method.DeclaringType.GenericParameters.Select(p => (TypeSig)new GenericVar(p.Number)).ToList() - : null; - IList methodMethodGenericArgument = _method.GenericParameters.Count > 0 - ? (IList)_method.GenericParameters.Select(p => (TypeSig)new GenericMVar(p.Number)).ToList() - : null; - var gac = new GenericArgumentContext(methodTypeGenericArgument, methodMethodGenericArgument); - var corLibTypes = _method.Module.CorLibTypes; - - var blockWalkStack = new Stack(_basicBlocks.Blocks.Reverse()); - while (blockWalkStack.Count > 0) - { - BasicBlock block = blockWalkStack.Pop(); - EvalStackState state = _blockEvalStackStates[block]; - if (state.visited) - continue; - state.visited = true; - state.runStackDatas.AddRange(state.inputStackDatas); - List stackDatas = state.runStackDatas; - foreach (var inst in block.instructions) - { - int stackSize = stackDatas.Count; - newPushedDatas.Clear(); - switch (inst.OpCode.Code) - { - case Code.Nop: break; - case Code.Break: break; - case Code.Ldarg_0: - case Code.Ldarg_1: - case Code.Ldarg_2: - case Code.Ldarg_3: - case Code.Ldarg: - case Code.Ldarg_S: - { - PushStack(newPushedDatas, inst.GetParameter(_method.Parameters).Type); - break; - } - case Code.Ldarga: - case Code.Ldarga_S: - { - PushStack(newPushedDatas, EvalDataType.I); - break; - } - case Code.Ldloc_0: - case Code.Ldloc_1: - case Code.Ldloc_2: - case Code.Ldloc_3: - case Code.Ldloc: - case Code.Ldloc_S: - { - PushStack(newPushedDatas, inst.GetLocal(body.Variables).Type); - break; - } - case Code.Ldloca: - case Code.Ldloca_S: - { - PushStack(newPushedDatas, EvalDataType.I); - break; - } - case Code.Stloc_0: - case Code.Stloc_1: - case Code.Stloc_2: - case Code.Stloc_3: - case Code.Stloc: - case Code.Stloc_S: - { - Assert.IsTrue(stackSize > 0); - break; - } - case Code.Starg: - case Code.Starg_S: - { - Assert.IsTrue(stackSize > 0); - break; - } - case Code.Ldnull: - { - PushStackObject(newPushedDatas); - break; - } - case Code.Ldc_I4_M1: - case Code.Ldc_I4_0: - case Code.Ldc_I4_1: - case Code.Ldc_I4_2: - case Code.Ldc_I4_3: - case Code.Ldc_I4_4: - case Code.Ldc_I4_5: - case Code.Ldc_I4_6: - case Code.Ldc_I4_7: - case Code.Ldc_I4_8: - case Code.Ldc_I4: - case Code.Ldc_I4_S: - { - PushStack(newPushedDatas, EvalDataType.Int32); - break; - } - case Code.Ldc_I8: - { - PushStack(newPushedDatas, EvalDataType.Int64); - break; - } - case Code.Ldc_R4: - { - PushStack(newPushedDatas, EvalDataType.Float); - break; - } - case Code.Ldc_R8: - { - PushStack(newPushedDatas, EvalDataType.Double); - break; - } - case Code.Dup: - { - Assert.IsTrue(stackSize > 0); - EvalDataTypeWithSig type = stackDatas[stackSize - 1]; - PushStack(newPushedDatas, type); - PushStack(newPushedDatas, type); - break; - } - case Code.Pop: - { - break; - } - case Code.Jmp: - { - break; - } - case Code.Call: - case Code.Callvirt: - { - IMethod calledMethod = (IMethod)inst.Operand; - MethodSig methodSig = MetaUtil.GetInflatedMethodSig(calledMethod, gac); - PushStack(newPushedDatas, methodSig.RetType); - break; - } - case Code.Calli: - { - MethodSig methodSig = (MethodSig)inst.Operand; - PushStack(newPushedDatas, methodSig.RetType); - break; - } - case Code.Ret: - { - break; - } - case Code.Br: - case Code.Br_S: - case Code.Brfalse: - case Code.Brfalse_S: - case Code.Brtrue: - case Code.Brtrue_S: - case Code.Beq: - case Code.Beq_S: - case Code.Bge: - case Code.Bge_S: - case Code.Bge_Un: - case Code.Bge_Un_S: - case Code.Bgt: - case Code.Bgt_S: - case Code.Bgt_Un: - case Code.Bgt_Un_S: - case Code.Ble: - case Code.Ble_S: - case Code.Ble_Un: - case Code.Ble_Un_S: - case Code.Blt: - case Code.Blt_S: - case Code.Blt_Un: - case Code.Blt_Un_S: - case Code.Bne_Un: - case Code.Bne_Un_S: - { - // Branch instructions do not change the stack. - break; - } - case Code.Ceq: - case Code.Cgt: - case Code.Cgt_Un: - case Code.Clt: - case Code.Clt_Un: - { - Assert.IsTrue(stackSize >= 2); - EvalDataType op2 = stackDatas[stackSize - 1].type; - EvalDataType op1 = stackDatas[stackSize - 2].type; - EvalDataType ret = EvalDataType.Int32; - _instructionParameterInfos.Add(inst, new InstructionParameterInfo(op1, op2, ret)); - PushStack(newPushedDatas, ret); - break; - } - case Code.Switch: - { - // Switch instruction does not change the stack. - break; - } - case Code.Ldind_I1: - case Code.Ldind_U1: - case Code.Ldind_I2: - case Code.Ldind_U2: - case Code.Ldind_I4: - case Code.Ldind_U4: - { - Assert.IsTrue(stackSize > 0); - PushStack(newPushedDatas, EvalDataType.Int32); - break; - } - case Code.Ldind_I8: - { - Assert.IsTrue(stackSize > 0); - PushStack(newPushedDatas, EvalDataType.Int64); - break; - } - case Code.Ldind_I: - { - Assert.IsTrue(stackSize > 0); - PushStack(newPushedDatas, EvalDataType.I); - break; - } - case Code.Ldind_Ref: - { - Assert.IsTrue(stackSize > 0); - PushStackObject(newPushedDatas); - break; - } - case Code.Ldind_R4: - { - Assert.IsTrue(stackSize > 0); - PushStack(newPushedDatas, EvalDataType.Float); - break; - } - case Code.Ldind_R8: - { - Assert.IsTrue(stackSize > 0); - PushStack(newPushedDatas, EvalDataType.Double); - break; - } - case Code.Stind_I1: - case Code.Stind_I2: - case Code.Stind_I4: - case Code.Stind_I8: - case Code.Stind_I: - case Code.Stind_R4: - case Code.Stind_R8: - case Code.Stind_Ref: - { - Assert.IsTrue(stackSize >= 2); - break; - } - - case Code.Add: - case Code.Add_Ovf: - case Code.Add_Ovf_Un: - case Code.Sub: - case Code.Sub_Ovf: - case Code.Sub_Ovf_Un: - case Code.Mul: - case Code.Mul_Ovf: - case Code.Mul_Ovf_Un: - case Code.Div: - case Code.Div_Un: - case Code.Rem: - case Code.Rem_Un: - - case Code.And: - case Code.Or: - case Code.Xor: - { - Assert.IsTrue(stackSize >= 2); - EvalDataType op2 = stackDatas[stackSize - 1].type; - EvalDataType op1 = stackDatas[stackSize - 2].type; - EvalDataType ret = CalcBasicBinOpRetType(op1, op2); - _instructionParameterInfos.Add(inst, new InstructionParameterInfo(op1, op2, ret)); - PushStack(newPushedDatas, ret); - break; - } - case Code.Shl: - case Code.Shr: - case Code.Shr_Un: - { - Assert.IsTrue(stackSize >= 2); - EvalDataType op2 = stackDatas[stackSize - 1].type; - EvalDataType op1 = stackDatas[stackSize - 2].type; - if (op1 != EvalDataType.Int32 && op1 != EvalDataType.Int64 && op1 != EvalDataType.I) - throw new Exception($"Unsupported operand type: {op1} in shift operation."); - if (op2 != EvalDataType.Int32 && op2 != EvalDataType.Int64) - throw new Exception($"Unsupported operand type: {op2} for {op1} in shift operation."); - EvalDataType ret = op1; - _instructionParameterInfos.Add(inst, new InstructionParameterInfo(op1, op2, ret)); - PushStack(newPushedDatas, ret); - break; - } - case Code.Neg: - { - Assert.IsTrue(stackSize > 0); - EvalDataType op = stackDatas[stackSize - 1].type; - EvalDataType ret = op; - switch (op) - { - case EvalDataType.Int32: - case EvalDataType.Int64: - case EvalDataType.I: - case EvalDataType.Float: - case EvalDataType.Double: - break; - default: - throw new Exception($"Unsupported operand type: {op} in unary operation."); - } - _instructionParameterInfos.Add(inst, new InstructionParameterInfo(op, EvalDataType.None, ret)); - PushStack(newPushedDatas, ret); - break; - } - case Code.Not: - { - Assert.IsTrue(stackSize > 0); - EvalDataType op = stackDatas[stackSize - 1].type; - EvalDataType ret = op; - if (op != EvalDataType.Int32 && op != EvalDataType.Int64 && op != EvalDataType.I) - throw new Exception($"Unsupported operand type: {op} in unary operation."); - _instructionParameterInfos.Add(inst, new InstructionParameterInfo(op, EvalDataType.None, ret)); - PushStack(newPushedDatas, ret); - break; - } - case Code.Conv_I1: - case Code.Conv_U1: - case Code.Conv_I2: - case Code.Conv_U2: - case Code.Conv_I4: - case Code.Conv_U4: - { - PushStack(newPushedDatas, EvalDataType.Int32); - break; - } - case Code.Conv_I8: - case Code.Conv_U8: - { - PushStack(newPushedDatas, EvalDataType.Int64); - break; - } - case Code.Conv_I: - case Code.Conv_U: - { - PushStack(newPushedDatas, EvalDataType.I); - break; - } - case Code.Conv_R4: - { - PushStack(newPushedDatas, EvalDataType.Float); - break; - } - case Code.Conv_R8: - { - PushStack(newPushedDatas, EvalDataType.Double); - break; - } - case Code.Conv_Ovf_I1: - case Code.Conv_Ovf_I1_Un: - case Code.Conv_Ovf_U1: - case Code.Conv_Ovf_U1_Un: - case Code.Conv_Ovf_I2: - case Code.Conv_Ovf_I2_Un: - case Code.Conv_Ovf_U2: - case Code.Conv_Ovf_U2_Un: - case Code.Conv_Ovf_I4: - case Code.Conv_Ovf_I4_Un: - case Code.Conv_Ovf_U4: - case Code.Conv_Ovf_U4_Un: - { - PushStack(newPushedDatas, EvalDataType.Int32); - break; - } - case Code.Conv_Ovf_I8: - case Code.Conv_Ovf_I8_Un: - case Code.Conv_Ovf_U8: - case Code.Conv_Ovf_U8_Un: - { - PushStack(newPushedDatas, EvalDataType.Int64); - break; - } - case Code.Conv_Ovf_I: - case Code.Conv_Ovf_I_Un: - case Code.Conv_Ovf_U: - case Code.Conv_Ovf_U_Un: - { - PushStack(newPushedDatas, EvalDataType.I); - break; - } - case Code.Conv_R_Un: - { - PushStack(newPushedDatas, EvalDataType.Double); - break; - } - case Code.Cpobj: - case Code.Initobj: - case Code.Stobj: - { - break; - } - case Code.Ldobj: - { - PushStack(newPushedDatas, (ITypeDefOrRef)inst.Operand); - break; - } - case Code.Ldstr: - { - PushStack(newPushedDatas, new EvalDataTypeWithSig(EvalDataType.Ref, corLibTypes.String)); - break; - } - case Code.Newobj: - { - IMethod ctor = (IMethod)inst.Operand; - PushStack(newPushedDatas, ctor.DeclaringType); - break; - } - case Code.Castclass: - { - PushStack(newPushedDatas, (ITypeDefOrRef)inst.Operand); - break; - } - case Code.Isinst: - { - Assert.IsTrue(stackSize > 0); - var obj = stackDatas[stackSize - 1]; - Assert.IsTrue(obj.type == EvalDataType.Ref); - PushStack(newPushedDatas, obj); - break; - } - case Code.Unbox: - { - Assert.IsTrue(stackSize > 0); - PushStack(newPushedDatas, EvalDataType.I); - break; - } - case Code.Unbox_Any: - { - Assert.IsTrue(stackSize > 0); - PushStack(newPushedDatas, (ITypeDefOrRef)inst.Operand); - break; - } - case Code.Box: - { - Assert.IsTrue(stackSize > 0); - PushStackObject(newPushedDatas); - break; - } - case Code.Throw: - { - // Throw instruction does not change the stack. - break; - } - case Code.Rethrow: - { - // Rethrow instruction does not change the stack. - break; - } - case Code.Ldfld: - case Code.Ldsfld: - { - IField field = (IField)inst.Operand; - TypeSig fieldType = MetaUtil.InflateFieldSig(field, gac); - PushStack(newPushedDatas, fieldType); - break; - } - case Code.Ldflda: - case Code.Ldsflda: - { - PushStack(newPushedDatas, EvalDataType.I); - break; - } - case Code.Stfld: - case Code.Stsfld: - { - break; - } - case Code.Newarr: - { - Assert.IsTrue(stackSize > 0); - PushStack(newPushedDatas, new SZArraySig(((ITypeDefOrRef)inst.Operand).ToTypeSig())); - break; - } - case Code.Ldlen: - { - Assert.IsTrue(stackSize > 0); - PushStack(newPushedDatas, EvalDataType.I); - break; - } - case Code.Ldelema: - { - Assert.IsTrue(stackSize >= 2); - PushStack(newPushedDatas, EvalDataType.I); - break; - } - case Code.Ldelem_I1: - case Code.Ldelem_U1: - case Code.Ldelem_I2: - case Code.Ldelem_U2: - case Code.Ldelem_I4: - case Code.Ldelem_U4: - { - Assert.IsTrue(stackSize >= 2); - PushStack(newPushedDatas, EvalDataType.Int32); - break; - } - case Code.Ldelem_I8: - { - Assert.IsTrue(stackSize >= 2); - PushStack(newPushedDatas, EvalDataType.Int64); - break; - } - case Code.Ldelem_I: - { - Assert.IsTrue(stackSize >= 2); - PushStack(newPushedDatas, EvalDataType.I); - break; - } - case Code.Ldelem_R4: - { - Assert.IsTrue(stackSize >= 2); - PushStack(newPushedDatas, EvalDataType.Float); - break; - } - case Code.Ldelem_R8: - { - Assert.IsTrue(stackSize >= 2); - PushStack(newPushedDatas, EvalDataType.Double); - break; - } - case Code.Ldelem_Ref: - { - Assert.IsTrue(stackSize >= 2); - PushStackObject(newPushedDatas); - break; - } - case Code.Ldelem: - { - Assert.IsTrue(stackSize >= 2); - PushStack(newPushedDatas, (ITypeDefOrRef)inst.Operand); - break; - } - case Code.Stelem_I1: - case Code.Stelem_I2: - case Code.Stelem_I4: - case Code.Stelem_I8: - case Code.Stelem_I: - case Code.Stelem_R4: - case Code.Stelem_R8: - case Code.Stelem_Ref: - case Code.Stelem: - { - Assert.IsTrue(stackSize >= 3); - break; - } - case Code.Mkrefany: - { - PushStack(newPushedDatas, new EvalDataTypeWithSig(EvalDataType.ValueType, _method.Module.CorLibTypes.TypedReference)); - break; - } - case Code.Refanytype: - { - PushStack(newPushedDatas, EvalDataType.Token); - break; - } - case Code.Refanyval: - { - Assert.IsTrue(stackSize > 0); - PushStack(newPushedDatas, EvalDataType.I); - break; - } - case Code.Ldtoken: - { - PushStack(newPushedDatas, EvalDataType.Token); - break; - } - case Code.Endfinally: - case Code.Leave: - case Code.Leave_S: - { - break; - } - case Code.Endfilter: - { - break; - } - case Code.Arglist: - { - break; - } - case Code.Ldftn: - case Code.Ldvirtftn: - { - PushStack(newPushedDatas, EvalDataType.Unknown); - break; - } - case Code.Localloc: - { - PushStack(newPushedDatas, EvalDataType.I); - break; - } - case Code.Unaligned: - case Code.Volatile: - case Code.Tailcall: - case Code.No: - case Code.Readonly: - case Code.Constrained: - { - break; - } - case Code.Cpblk: - case Code.Initblk: - { - break; - } - case Code.Sizeof: - { - PushStack(newPushedDatas, EvalDataType.Int32); - break; - } - default: throw new Exception($"not supported opcode: {inst} in method: {_method.FullName}."); - } - - inst.CalculateStackUsage(methodHasReturnValue, out var pushed, out var pops); - if (pushed != newPushedDatas.Count) - { - throw new Exception($"Instruction {inst} in method {_method.FullName} pushed {newPushedDatas.Count} items, but expected {pushed} items."); - } - if (pops == -1) - { - stackDatas.Clear(); - } - else - { - if (stackSize < pops) - { - throw new Exception($"Instruction {inst} in method {_method.FullName} pops {pops} items, but only {stackSize} items are available on the stack."); - } - stackDatas.RemoveRange(stackDatas.Count - pops, pops); - stackDatas.AddRange(newPushedDatas); - Assert.AreEqual(stackSize + pushed - pops, stackDatas.Count); - } - if (pushed > 0 && stackDatas.Count > 0) - { - _evalStackTopDataTypeAfterInstructions[inst] = stackDatas.Last().type; - } - } - foreach (BasicBlock outBb in block.outBlocks) - { - EvalStackState outState = _blockEvalStackStates[outBb]; - if (outState.visited) - { - if (stackDatas.Count != outState.inputStackDatas.Count) - { - throw new Exception($"Block {block} in method {_method.FullName} has inconsistent stack data. Expected {outState.inputStackDatas.Count}, but got {stackDatas.Count}."); - } - } - else if (outState.inputStackDatas.Count != stackDatas.Count) - { - if (outState.inputStackDatas.Count > 0) - { - throw new Exception($"Block {outBb} in method {_method.FullName} has inconsistent stack data. Expected {outState.inputStackDatas.Count}, but got {stackDatas.Count}."); - } - outState.inputStackDatas.AddRange(stackDatas); - blockWalkStack.Push(outBb); - } - } - } - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Emit/EvalStackCalculator.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Emit/EvalStackCalculator.cs.meta deleted file mode 100644 index 0e3c9de0..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Emit/EvalStackCalculator.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: f25425a3077f6db41873dee4223d0abc -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Emit/GroupByModuleEntityManager.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Emit/GroupByModuleEntityManager.cs deleted file mode 100644 index 97e8f286..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Emit/GroupByModuleEntityManager.cs +++ /dev/null @@ -1,89 +0,0 @@ -using dnlib.DotNet; -using System; -using System.Collections.Generic; - -namespace Obfuz.Emit -{ - public interface IGroupByModuleEntity - { - GroupByModuleEntityManager Manager { get; set; } - - ModuleDef Module { get; set; } - - public EncryptionScopeProvider EncryptionScopeProvider { get; } - - EncryptionScopeInfo EncryptionScope { get; set; } - - void Init(); - - void Done(); - } - - public abstract class GroupByModuleEntityBase : IGroupByModuleEntity - { - public GroupByModuleEntityManager Manager { get; set; } - - public ModuleDef Module { get; set; } - - public EncryptionScopeInfo EncryptionScope { get; set; } - - public EncryptionScopeProvider EncryptionScopeProvider => Manager.EncryptionScopeProvider; - - public T GetEntity() where T : IGroupByModuleEntity, new() - { - return Manager.GetEntity(Module); - } - - public abstract void Init(); - - public abstract void Done(); - } - - public class GroupByModuleEntityManager - { - private readonly Dictionary<(ModuleDef, Type), IGroupByModuleEntity> _moduleEntityManagers = new Dictionary<(ModuleDef, Type), IGroupByModuleEntity>(); - - public EncryptionScopeProvider EncryptionScopeProvider { get; set; } - - public T GetEntity(ModuleDef mod) where T : IGroupByModuleEntity, new() - { - var key = (mod, typeof(T)); - if (_moduleEntityManagers.TryGetValue(key, out var emitManager)) - { - return (T)emitManager; - } - else - { - T newEmitManager = new T(); - newEmitManager.Manager = this; - newEmitManager.Module = mod; - newEmitManager.EncryptionScope = EncryptionScopeProvider.GetScope(mod); - newEmitManager.Init(); - _moduleEntityManagers[key] = newEmitManager; - return newEmitManager; - } - } - - public List GetEntities() where T : IGroupByModuleEntity, new() - { - var managers = new List(); - foreach (var kv in _moduleEntityManagers) - { - if (kv.Key.Item2 == typeof(T)) - { - managers.Add((T)kv.Value); - } - } - return managers; - } - - public void Done() where T : IGroupByModuleEntity, new() - { - var managers = GetEntities(); - foreach (var manager in managers) - { - manager.Done(); - } - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Emit/GroupByModuleEntityManager.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Emit/GroupByModuleEntityManager.cs.meta deleted file mode 100644 index a6b76025..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Emit/GroupByModuleEntityManager.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 0bfcb2b5a87851f469d201fc8978c109 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Emit/LocalVariableAllocator.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Emit/LocalVariableAllocator.cs deleted file mode 100644 index 3fb0015e..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Emit/LocalVariableAllocator.cs +++ /dev/null @@ -1,74 +0,0 @@ -using dnlib.DotNet; -using dnlib.DotNet.Emit; -using System; -using System.Collections.Generic; - -namespace Obfuz.Emit -{ - class ScopeLocalVariables : IDisposable - { - private readonly LocalVariableAllocator _localVariableAllocator; - - private readonly List _allocatedVars = new List(); - - public IReadOnlyList AllocatedLocals => _allocatedVars; - - - public ScopeLocalVariables(LocalVariableAllocator localVariableAllocator) - { - _localVariableAllocator = localVariableAllocator; - } - - public Local AllocateLocal(TypeSig type) - { - var local = _localVariableAllocator.AllocateLocal(type); - _allocatedVars.Add(local); - return local; - } - - public void Dispose() - { - foreach (var local in _allocatedVars) - { - _localVariableAllocator.ReturnLocal(local); - } - } - } - - class LocalVariableAllocator - { - private readonly MethodDef _method; - private readonly List _freeLocals = new List(); - - public LocalVariableAllocator(MethodDef method) - { - _method = method; - } - - public Local AllocateLocal(TypeSig type) - { - foreach (var local in _freeLocals) - { - if (TypeEqualityComparer.Instance.Equals(local.Type, type)) - { - _freeLocals.Remove(local); - return local; - } - } - var newLocal = new Local(type); - // _freeLocals.Add(newLocal); - _method.Body.Variables.Add(newLocal); - return newLocal; - } - - public void ReturnLocal(Local local) - { - _freeLocals.Add(local); - } - - public ScopeLocalVariables CreateScope() - { - return new ScopeLocalVariables(this); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Emit/LocalVariableAllocator.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Emit/LocalVariableAllocator.cs.meta deleted file mode 100644 index 6561078c..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Emit/LocalVariableAllocator.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 955da34fbde179641a94108ec53405ce -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM.meta deleted file mode 100644 index e8e65c15..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: fec4187cc1b96d5439ff908bcecd988f -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/EncryptionInstructionWithOpCode.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/EncryptionInstructionWithOpCode.cs deleted file mode 100644 index 19ded458..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/EncryptionInstructionWithOpCode.cs +++ /dev/null @@ -1,25 +0,0 @@ -namespace Obfuz.EncryptionVM -{ - public class EncryptionInstructionWithOpCode - { - public readonly ushort code; - - public readonly IEncryptionInstruction function; - - public EncryptionInstructionWithOpCode(ushort code, IEncryptionInstruction function) - { - this.code = code; - this.function = function; - } - - public int Encrypt(int value, int[] secretKey, int salt) - { - return function.Encrypt(value, secretKey, salt); - } - - public int Decrypt(int value, int[] secretKey, int salt) - { - return function.Decrypt(value, secretKey, salt); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/EncryptionInstructionWithOpCode.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/EncryptionInstructionWithOpCode.cs.meta deleted file mode 100644 index cd63f212..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/EncryptionInstructionWithOpCode.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ca9bd232ed2583f4bb5f330886a329e6 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/IEncryptionInstruction.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/IEncryptionInstruction.cs deleted file mode 100644 index 49808c43..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/IEncryptionInstruction.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System.Collections.Generic; - -namespace Obfuz.EncryptionVM -{ - public interface IEncryptionInstruction - { - int Encrypt(int value, int[] secretKey, int salt); - - int Decrypt(int value, int[] secretKey, int salt); - - void GenerateEncryptCode(List lines, string indent); - - void GenerateDecryptCode(List lines, string indent); - } - - public abstract class EncryptionInstructionBase : IEncryptionInstruction - { - public abstract int Encrypt(int value, int[] secretKey, int salt); - public abstract int Decrypt(int value, int[] secretKey, int salt); - - public abstract void GenerateEncryptCode(List lines, string indent); - public abstract void GenerateDecryptCode(List lines, string indent); - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/IEncryptionInstruction.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/IEncryptionInstruction.cs.meta deleted file mode 100644 index ab7f3a60..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/IEncryptionInstruction.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: f7b9d087de770a5488a9069ddf697c2f -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions.meta deleted file mode 100644 index fa569881..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 981355cf75a9d234883b2a15c446f478 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/AddInstruction.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/AddInstruction.cs deleted file mode 100644 index 2681fff0..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/AddInstruction.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System.Collections.Generic; - -namespace Obfuz.EncryptionVM.Instructions -{ - public class AddInstruction : EncryptionInstructionBase - { - private readonly int _addValue; - private readonly int _opKeyIndex; - - public AddInstruction(int addValue, int opKeyIndex) - { - _addValue = addValue; - _opKeyIndex = opKeyIndex; - } - public override int Encrypt(int value, int[] secretKey, int salt) - { - return ((value + secretKey[_opKeyIndex]) ^ salt) + _addValue; - } - - public override int Decrypt(int value, int[] secretKey, int salt) - { - return ((value - _addValue) ^ salt) - secretKey[_opKeyIndex]; - } - - public override void GenerateEncryptCode(List lines, string indent) - { - lines.Add(indent + $"value = ((value + _secretKey[{_opKeyIndex}]) ^ salt) + {_addValue};"); - } - - public override void GenerateDecryptCode(List lines, string indent) - { - lines.Add(indent + $"value = ((value - {_addValue}) ^ salt) - _secretKey[{_opKeyIndex}];"); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/AddInstruction.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/AddInstruction.cs.meta deleted file mode 100644 index d1d20319..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/AddInstruction.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 6bdbdc5fd983f044a87e7b8ab8647aeb -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/AddRotateXorInstruction.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/AddRotateXorInstruction.cs deleted file mode 100644 index 44933213..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/AddRotateXorInstruction.cs +++ /dev/null @@ -1,62 +0,0 @@ -using System.Collections.Generic; - -namespace Obfuz.EncryptionVM.Instructions -{ - public class AddRotateXorInstruction : EncryptionInstructionBase - { - // x = x + p1 + secretKey[index1]; - // x = Rotate(x, p2) - // x = x ^ p3 ^ salt; - - private readonly int _addValue; - private readonly int _index1; - private readonly int _rotateBitNum; - private readonly int _xorValue; - - public AddRotateXorInstruction(int addValue, int index1, int rotateBitNum, int xorValue) - { - _addValue = addValue; - _index1 = index1; - _rotateBitNum = rotateBitNum; - _xorValue = xorValue; - } - - public override int Encrypt(int value, int[] secretKey, int salt) - { - value += _addValue + secretKey[_index1]; - uint part1 = (uint)value << _rotateBitNum; - uint part2 = (uint)value >> (32 - _rotateBitNum); - value = (int)(part1 | part2); - value ^= _xorValue ^ salt; - return value; - } - - public override int Decrypt(int value, int[] secretKey, int salt) - { - value ^= _xorValue ^ salt; - uint value2 = (uint)value >> _rotateBitNum; - uint part1 = (uint)value << (32 - _rotateBitNum); - value = (int)(value2 | part1); - value -= _addValue + secretKey[_index1]; - return value; - } - - public override void GenerateEncryptCode(List lines, string indent) - { - lines.Add(indent + $"value += {_addValue} + _secretKey[{_index1}];"); - lines.Add(indent + $"uint part1 = (uint)value << {_rotateBitNum};"); - lines.Add(indent + $"uint part2 = (uint)value >> (32 - {_rotateBitNum});"); - lines.Add(indent + $"value = (int)(part1 | part2);"); - lines.Add(indent + $"value ^= {_xorValue} ^ salt;"); - } - - public override void GenerateDecryptCode(List lines, string indent) - { - lines.Add(indent + $"value ^= {_xorValue} ^ salt;"); - lines.Add(indent + $"uint value2 = (uint)value >> {_rotateBitNum};"); - lines.Add(indent + $"uint part1 = (uint)value << (32 - {_rotateBitNum});"); - lines.Add(indent + $"value = (int)(value2 | part1);"); - lines.Add(indent + $"value -= {_addValue} + _secretKey[{_index1}];"); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/AddRotateXorInstruction.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/AddRotateXorInstruction.cs.meta deleted file mode 100644 index 6101fdb1..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/AddRotateXorInstruction.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: cda67c0dd0cadd24ea02c2988e34281a -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/AddXorRotateInstruction.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/AddXorRotateInstruction.cs deleted file mode 100644 index d2aa6f15..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/AddXorRotateInstruction.cs +++ /dev/null @@ -1,62 +0,0 @@ -using System.Collections.Generic; - -namespace Obfuz.EncryptionVM.Instructions -{ - public class AddXorRotateInstruction : EncryptionInstructionBase - { - // x = x + p1 + secretKey[index1]; - // x = x ^ p3 ^ salt; - // x = Rotate(x, p2) - - private readonly int _addValue; - private readonly int _index1; - private readonly int _rotateBitNum; - private readonly int _xorValue; - - public AddXorRotateInstruction(int addValue, int index1, int xorValue, int rotateBitNum) - { - _addValue = addValue; - _index1 = index1; - _rotateBitNum = rotateBitNum; - _xorValue = xorValue; - } - - public override int Encrypt(int value, int[] secretKey, int salt) - { - value += _addValue + secretKey[_index1]; - value ^= _xorValue ^ salt; - uint part1 = (uint)value << _rotateBitNum; - uint part2 = (uint)value >> (32 - _rotateBitNum); - value = (int)(part1 | part2); - return value; - } - - public override int Decrypt(int value, int[] secretKey, int salt) - { - uint value2 = (uint)value >> _rotateBitNum; - uint part1 = (uint)value << (32 - _rotateBitNum); - value = (int)(value2 | part1); - value ^= _xorValue ^ salt; - value -= _addValue + secretKey[_index1]; - return value; - } - - public override void GenerateEncryptCode(List lines, string indent) - { - lines.Add(indent + $"value += {_addValue} + _secretKey[{_index1}];"); - lines.Add(indent + $"value ^= {_xorValue} ^ salt;"); - lines.Add(indent + $"uint part1 = (uint)value << {_rotateBitNum};"); - lines.Add(indent + $"uint part2 = (uint)value >> (32 - {_rotateBitNum});"); - lines.Add(indent + $"value = (int)(part1 | part2);"); - } - - public override void GenerateDecryptCode(List lines, string indent) - { - lines.Add(indent + $"uint part1 = (uint)value >> {_rotateBitNum};"); - lines.Add(indent + $"uint part2 = (uint)value << (32 - {_rotateBitNum});"); - lines.Add(indent + $"value = (int)(part1 | part2);"); - lines.Add(indent + $"value ^= {_xorValue} ^ salt;"); - lines.Add(indent + $"value -= {_addValue} + _secretKey[{_index1}];"); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/AddXorRotateInstruction.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/AddXorRotateInstruction.cs.meta deleted file mode 100644 index abde16f0..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/AddXorRotateInstruction.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: d806305e627be06469fb2d2c2cf98816 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/BitRotateInstruction.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/BitRotateInstruction.cs deleted file mode 100644 index 2d9dcd14..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/BitRotateInstruction.cs +++ /dev/null @@ -1,46 +0,0 @@ -using System.Collections.Generic; - -namespace Obfuz.EncryptionVM.Instructions -{ - public class BitRotateInstruction : EncryptionInstructionBase - { - private readonly int _rotateBitNum; - private readonly int _opKeyIndex; - - public BitRotateInstruction(int rotateBitNum, int opKeyIndex) - { - _rotateBitNum = rotateBitNum; - _opKeyIndex = opKeyIndex; - } - - public override int Encrypt(int value, int[] secretKey, int salt) - { - uint part1 = (uint)value << _rotateBitNum; - uint part2 = (uint)value >> (32 - _rotateBitNum); - return ((int)(part1 | part2) ^ secretKey[_opKeyIndex]) + salt; - } - - public override int Decrypt(int value, int[] secretKey, int salt) - { - uint value2 = (uint)((value - salt) ^ secretKey[_opKeyIndex]); - uint part1 = value2 >> _rotateBitNum; - uint part2 = value2 << (32 - _rotateBitNum); - return (int)(part1 | part2); - } - - public override void GenerateEncryptCode(List lines, string indent) - { - lines.Add(indent + $"uint part1 = (uint)value << {_rotateBitNum};"); - lines.Add(indent + $"uint part2 = (uint)value >> (32 - {_rotateBitNum});"); - lines.Add(indent + $"value = ((int)(part1 | part2) ^ _secretKey[{_opKeyIndex}]) + salt;"); - } - - public override void GenerateDecryptCode(List lines, string indent) - { - lines.Add(indent + $"uint value2 = (uint)((value - salt) ^ _secretKey[{_opKeyIndex}]);"); - lines.Add(indent + $"uint part1 = value2 >> {_rotateBitNum};"); - lines.Add(indent + $"uint part2 = value2 << (32 - {_rotateBitNum});"); - lines.Add(indent + $"value = (int)(part1 | part2);"); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/BitRotateInstruction.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/BitRotateInstruction.cs.meta deleted file mode 100644 index b4b0b9a5..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/BitRotateInstruction.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: bccff31b9f07fcf4f821cee671f82caf -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/EncryptFunction.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/EncryptFunction.cs deleted file mode 100644 index 7abafecd..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/EncryptFunction.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace Obfuz.EncryptionVM.Instructions -{ - - public class EncryptFunction : EncryptionInstructionBase - { - private readonly IEncryptionInstruction[] _instructions; - - public EncryptFunction(IEncryptionInstruction[] instructions) - { - _instructions = instructions; - } - - public override int Encrypt(int value, int[] secretKey, int salt) - { - foreach (var instruction in _instructions) - { - value = instruction.Encrypt(value, secretKey, salt); - } - return value; - } - - public override int Decrypt(int value, int[] secretKey, int salt) - { - for (int i = _instructions.Length - 1; i >= 0; i--) - { - value = _instructions[i].Decrypt(value, secretKey, salt); - } - return value; - } - - public override void GenerateEncryptCode(List lines, string indent) - { - throw new NotImplementedException(); - } - - public override void GenerateDecryptCode(List lines, string indent) - { - throw new NotImplementedException(); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/EncryptFunction.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/EncryptFunction.cs.meta deleted file mode 100644 index 0ee2250b..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/EncryptFunction.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: feafdb30f7b6d5143a89c7659bc16171 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/MultipleInstruction.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/MultipleInstruction.cs deleted file mode 100644 index a788a678..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/MultipleInstruction.cs +++ /dev/null @@ -1,46 +0,0 @@ -using Obfuz.Utils; -using System.Collections.Generic; - -namespace Obfuz.EncryptionVM.Instructions -{ - public class MultipleInstruction : EncryptionInstructionBase - { - private readonly int _multiValue; - private readonly int _revertMultiValue; - private readonly int _opKeyIndex; - - public MultipleInstruction(int addValue, int opKeyIndex) - { - _multiValue = addValue; - _opKeyIndex = opKeyIndex; - _revertMultiValue = MathUtil.ModInverse32(addValue); - Verify(); - } - - private void Verify() - { - int a = 1122334; - UnityEngine.Assertions.Assert.AreEqual(a, a * _multiValue * _revertMultiValue); - } - - public override int Encrypt(int value, int[] secretKey, int salt) - { - return value * _multiValue + secretKey[_opKeyIndex] + salt; - } - - public override int Decrypt(int value, int[] secretKey, int salt) - { - return (value - secretKey[_opKeyIndex] - salt) * _revertMultiValue; - } - - public override void GenerateEncryptCode(List lines, string indent) - { - lines.Add(indent + $"value = value * {_multiValue} + _secretKey[{_opKeyIndex}] + salt;"); - } - - public override void GenerateDecryptCode(List lines, string indent) - { - lines.Add(indent + $"value = (value - _secretKey[{_opKeyIndex}] - salt) * {_revertMultiValue};"); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/MultipleInstruction.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/MultipleInstruction.cs.meta deleted file mode 100644 index 478ba088..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/MultipleInstruction.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: fd5fdfad694e0ae469bf6ca04c913220 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/MultipleRotateXorInstruction.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/MultipleRotateXorInstruction.cs deleted file mode 100644 index 62fc609a..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/MultipleRotateXorInstruction.cs +++ /dev/null @@ -1,65 +0,0 @@ -using Obfuz.Utils; -using System.Collections.Generic; - -namespace Obfuz.EncryptionVM.Instructions -{ - public class MultipleRotateXorInstruction : EncryptionInstructionBase - { - // x = x * p1 + secretKey[index1]; - // x = Rotate(x, p2) - // x = x ^ p3 ^ salt; - - private readonly int _multipleValue; - private readonly int _revertMultipleValue; - private readonly int _index1; - private readonly int _rotateBitNum; - private readonly int _xorValue; - - public MultipleRotateXorInstruction(int multipleValue, int index1, int rotateBitNum, int xorValue) - { - _multipleValue = multipleValue; - _revertMultipleValue = MathUtil.ModInverse32(multipleValue); - _index1 = index1; - _rotateBitNum = rotateBitNum; - _xorValue = xorValue; - } - - public override int Encrypt(int value, int[] secretKey, int salt) - { - value = value * _multipleValue + secretKey[_index1]; - uint part1 = (uint)value << _rotateBitNum; - uint part2 = (uint)value >> (32 - _rotateBitNum); - value = (int)(part1 | part2); - value ^= _xorValue ^ salt; - return value; - } - - public override int Decrypt(int value, int[] secretKey, int salt) - { - value ^= _xorValue ^ salt; - uint value2 = (uint)value >> _rotateBitNum; - uint part1 = (uint)value << (32 - _rotateBitNum); - value = (int)(value2 | part1); - value = (value - secretKey[_index1]) * _revertMultipleValue; - return value; - } - - public override void GenerateEncryptCode(List lines, string indent) - { - lines.Add(indent + $"value = value * {_multipleValue} + _secretKey[{_index1}];"); - lines.Add(indent + $"uint part1 = (uint)value << {_rotateBitNum};"); - lines.Add(indent + $"uint part2 = (uint)value >> (32 - {_rotateBitNum});"); - lines.Add(indent + $"value = (int)(part1 | part2);"); - lines.Add(indent + $"value ^= {_xorValue} ^ salt;"); - } - - public override void GenerateDecryptCode(List lines, string indent) - { - lines.Add(indent + $"value ^= {_xorValue} ^ salt;"); - lines.Add(indent + $"uint value2 = (uint)value >> {_rotateBitNum};"); - lines.Add(indent + $"uint part1 = (uint)value << (32 - {_rotateBitNum});"); - lines.Add(indent + $"value = (int)(value2 | part1);"); - lines.Add(indent + $"value = (value - _secretKey[{_index1}]) * {_revertMultipleValue};"); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/MultipleRotateXorInstruction.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/MultipleRotateXorInstruction.cs.meta deleted file mode 100644 index 7f4e53a7..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/MultipleRotateXorInstruction.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: e3c8b55b35ff1554489fa657a714f485 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/MultipleXorRotateInstruction.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/MultipleXorRotateInstruction.cs deleted file mode 100644 index a8a69326..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/MultipleXorRotateInstruction.cs +++ /dev/null @@ -1,65 +0,0 @@ -using Obfuz.Utils; -using System.Collections.Generic; - -namespace Obfuz.EncryptionVM.Instructions -{ - public class MultipleXorRotateInstruction : EncryptionInstructionBase - { - // x = x * p1 + secretKey[index1]; - // x = x ^ p3 ^ salt; - // x = Rotate(x, p2) - - private readonly int _multipleValue; - private readonly int _revertMultipleValue; - private readonly int _index1; - private readonly int _rotateBitNum; - private readonly int _xorValue; - - public MultipleXorRotateInstruction(int multipleValue, int index1, int xorValue, int rotateBitNum) - { - _multipleValue = multipleValue; - _revertMultipleValue = MathUtil.ModInverse32(multipleValue); - _index1 = index1; - _rotateBitNum = rotateBitNum; - _xorValue = xorValue; - } - - public override int Encrypt(int value, int[] secretKey, int salt) - { - value = value * _multipleValue + secretKey[_index1]; - value ^= _xorValue ^ salt; - uint part1 = (uint)value << _rotateBitNum; - uint part2 = (uint)value >> (32 - _rotateBitNum); - value = (int)(part1 | part2); - return value; - } - - public override int Decrypt(int value, int[] secretKey, int salt) - { - uint value2 = (uint)value >> _rotateBitNum; - uint part1 = (uint)value << (32 - _rotateBitNum); - value = (int)(value2 | part1); - value ^= _xorValue ^ salt; - value = (value - secretKey[_index1]) * _revertMultipleValue; - return value; - } - - public override void GenerateEncryptCode(List lines, string indent) - { - lines.Add(indent + $"value = value * {_multipleValue} + _secretKey[{_index1}];"); - lines.Add(indent + $"value ^= {_xorValue} ^ salt;"); - lines.Add(indent + $"uint part1 = (uint)value << {_rotateBitNum};"); - lines.Add(indent + $"uint part2 = (uint)value >> (32 - {_rotateBitNum});"); - lines.Add(indent + $"value = (int)(part1 | part2);"); - } - - public override void GenerateDecryptCode(List lines, string indent) - { - lines.Add(indent + $"uint value2 = (uint)value >> {_rotateBitNum};"); - lines.Add(indent + $"uint part1 = (uint)value << (32 - {_rotateBitNum});"); - lines.Add(indent + $"value = (int)(value2 | part1);"); - lines.Add(indent + $"value ^= {_xorValue} ^ salt;"); - lines.Add(indent + $"value = (value - _secretKey[{_index1}]) * {_revertMultipleValue};"); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/MultipleXorRotateInstruction.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/MultipleXorRotateInstruction.cs.meta deleted file mode 100644 index 0e6a6534..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/MultipleXorRotateInstruction.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: adc3dcde66795744fa4bdc753a2c599f -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/XorAddRotateInstruction.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/XorAddRotateInstruction.cs deleted file mode 100644 index 97cc6e43..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/XorAddRotateInstruction.cs +++ /dev/null @@ -1,62 +0,0 @@ -using System.Collections.Generic; - -namespace Obfuz.EncryptionVM.Instructions -{ - public class XorAddRotateInstruction : EncryptionInstructionBase - { - // x = x ^ p3 ^ salt; - // x = x + p1 + secretKey[index1]; - // x = Rotate(x, p2) - - private readonly int _addValue; - private readonly int _index1; - private readonly int _rotateBitNum; - private readonly int _xorValue; - - public XorAddRotateInstruction(int xorValue, int addValue, int index1, int rotateBitNum) - { - _addValue = addValue; - _index1 = index1; - _rotateBitNum = rotateBitNum; - _xorValue = xorValue; - } - - public override int Encrypt(int value, int[] secretKey, int salt) - { - value ^= _xorValue ^ salt; - value += _addValue + secretKey[_index1]; - uint part1 = (uint)value << _rotateBitNum; - uint part2 = (uint)value >> (32 - _rotateBitNum); - value = (int)(part1 | part2); - return value; - } - - public override int Decrypt(int value, int[] secretKey, int salt) - { - uint value2 = (uint)value >> _rotateBitNum; - uint part1 = (uint)value << (32 - _rotateBitNum); - value = (int)(value2 | part1); - value -= _addValue + secretKey[_index1]; - value ^= _xorValue ^ salt; - return value; - } - - public override void GenerateEncryptCode(List lines, string indent) - { - lines.Add(indent + $"value ^= {_xorValue} ^ salt;"); - lines.Add(indent + $"value += {_addValue} + _secretKey[{_index1}];"); - lines.Add(indent + $"uint part1 = (uint)value << {_rotateBitNum};"); - lines.Add(indent + $"uint part2 = (uint)value >> (32 - {_rotateBitNum});"); - lines.Add(indent + $"value = (int)(part1 | part2);"); - } - - public override void GenerateDecryptCode(List lines, string indent) - { - lines.Add(indent + $"uint value2 = (uint)value >> {_rotateBitNum};"); - lines.Add(indent + $"uint part1 = (uint)value << (32 - {_rotateBitNum});"); - lines.Add(indent + $"value = (int)(value2 | part1);"); - lines.Add(indent + $"value -= {_addValue} + _secretKey[{_index1}];"); - lines.Add(indent + $"value ^= {_xorValue} ^ salt;"); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/XorAddRotateInstruction.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/XorAddRotateInstruction.cs.meta deleted file mode 100644 index d1a6d086..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/XorAddRotateInstruction.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ad8f4dd724d7ff845b0dd65861054d37 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/XorInstruction.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/XorInstruction.cs deleted file mode 100644 index 353a4f6f..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/XorInstruction.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Collections.Generic; - -namespace Obfuz.EncryptionVM.Instructions -{ - public class XorInstruction : EncryptionInstructionBase - { - private readonly int _xorValue; - private readonly int _opKeyIndex; - - public XorInstruction(int xorValue, int opKeyIndex) - { - _xorValue = xorValue; - _opKeyIndex = opKeyIndex; - } - - public override int Encrypt(int value, int[] secretKey, int salt) - { - return ((value ^ secretKey[_opKeyIndex]) + salt) ^ _xorValue; - } - - public override int Decrypt(int value, int[] secretKey, int salt) - { - return ((value ^ _xorValue) - salt) ^ secretKey[_opKeyIndex]; - } - - public override void GenerateEncryptCode(List lines, string indent) - { - lines.Add(indent + $"value = ((value ^ _secretKey[{_opKeyIndex}]) + salt) ^ {_xorValue};"); - } - - public override void GenerateDecryptCode(List lines, string indent) - { - lines.Add(indent + $"value = ((value ^ {_xorValue}) - salt) ^ _secretKey[{_opKeyIndex}];"); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/XorInstruction.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/XorInstruction.cs.meta deleted file mode 100644 index e246896d..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/XorInstruction.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 2f16dd868e4473b45bfa9daaf7fabaf8 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/XorMultipleRotateInstruction.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/XorMultipleRotateInstruction.cs deleted file mode 100644 index ab823312..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/XorMultipleRotateInstruction.cs +++ /dev/null @@ -1,65 +0,0 @@ -using Obfuz.Utils; -using System.Collections.Generic; - -namespace Obfuz.EncryptionVM.Instructions -{ - public class XorMultipleRotateInstruction : EncryptionInstructionBase - { - // x = x ^ p3 ^ salt; - // x = x * p1 + secretKey[index1]; - // x = Rotate(x, p2) - - private readonly int _multipleValue; - private readonly int _revertMultipleValue; - private readonly int _index1; - private readonly int _rotateBitNum; - private readonly int _xorValue; - - public XorMultipleRotateInstruction(int xorValue, int multipleValue, int index1, int rotateBitNum) - { - _multipleValue = multipleValue; - _revertMultipleValue = MathUtil.ModInverse32(multipleValue); - _index1 = index1; - _rotateBitNum = rotateBitNum; - _xorValue = xorValue; - } - - public override int Encrypt(int value, int[] secretKey, int salt) - { - value ^= _xorValue ^ salt; - value = value * _multipleValue + secretKey[_index1]; - uint part1 = (uint)value << _rotateBitNum; - uint part2 = (uint)value >> (32 - _rotateBitNum); - value = (int)(part1 | part2); - return value; - } - - public override int Decrypt(int value, int[] secretKey, int salt) - { - uint value2 = (uint)value >> _rotateBitNum; - uint part1 = (uint)value << (32 - _rotateBitNum); - value = (int)(value2 | part1); - value = (value - secretKey[_index1]) * _revertMultipleValue; - value ^= _xorValue ^ salt; - return value; - } - - public override void GenerateEncryptCode(List lines, string indent) - { - lines.Add(indent + $"value ^= {_xorValue} ^ salt;"); - lines.Add(indent + $"value = value * {_multipleValue} + _secretKey[{_index1}];"); - lines.Add(indent + $"uint part1 = (uint)value << {_rotateBitNum};"); - lines.Add(indent + $"uint part2 = (uint)value >> (32 - {_rotateBitNum});"); - lines.Add(indent + $"value = (int)(part1 | part2);"); - } - - public override void GenerateDecryptCode(List lines, string indent) - { - lines.Add(indent + $"uint value2 = (uint)value >> {_rotateBitNum};"); - lines.Add(indent + $"uint part1 = (uint)value << (32 - {_rotateBitNum});"); - lines.Add(indent + $"value = (int)(value2 | part1);"); - lines.Add(indent + $"value = (value - _secretKey[{_index1}]) * {_revertMultipleValue};"); - lines.Add(indent + $"value ^= {_xorValue} ^ salt;"); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/XorMultipleRotateInstruction.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/XorMultipleRotateInstruction.cs.meta deleted file mode 100644 index e95af06a..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/Instructions/XorMultipleRotateInstruction.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 3eb7e6d475cfc14459d3850c5964ba52 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/VirtualMachine.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/VirtualMachine.cs deleted file mode 100644 index 1ca1a598..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/VirtualMachine.cs +++ /dev/null @@ -1,17 +0,0 @@ -namespace Obfuz.EncryptionVM -{ - public class VirtualMachine - { - public const int SecretKeyLength = 1024; - - public readonly int version; - public readonly string codeGenerationSecretKey; - public readonly EncryptionInstructionWithOpCode[] opCodes; - - public VirtualMachine(int version, string codeGenerationSecretKey, EncryptionInstructionWithOpCode[] opCodes) - { - this.codeGenerationSecretKey = codeGenerationSecretKey; - this.opCodes = opCodes; - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/VirtualMachine.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/VirtualMachine.cs.meta deleted file mode 100644 index e932d330..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/VirtualMachine.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: c6970e037654dcb49912783a40f3e1ba -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/VirtualMachineCodeGenerator.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/VirtualMachineCodeGenerator.cs deleted file mode 100644 index f12d3688..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/VirtualMachineCodeGenerator.cs +++ /dev/null @@ -1,203 +0,0 @@ -using Obfuz.Utils; -using System.Collections.Generic; -using System.IO; -using System.Text; -using System.Text.RegularExpressions; -using UnityEngine; - -namespace Obfuz.EncryptionVM -{ - public class VirtualMachineCodeGenerator - { - private readonly int _opCodeCount; - private readonly int _opCodeBits; - private readonly VirtualMachine _vm; - - public VirtualMachineCodeGenerator(string vmCodeGenerateSecretKey, int opCodeCount) - { - _opCodeCount = opCodeCount; - _opCodeBits = EncryptionUtil.GetBitCount(opCodeCount - 1); - _vm = new VirtualMachineCreator(vmCodeGenerateSecretKey).CreateVirtualMachine(opCodeCount); - } - - public VirtualMachineCodeGenerator(VirtualMachine vm) - { - _opCodeCount = vm.opCodes.Length; - _opCodeBits = EncryptionUtil.GetBitCount(_opCodeCount - 1); - _vm = vm; - } - - - public bool ValidateMatch(string outputFile) - { - if (!File.Exists(outputFile)) - { - return false; - } - string oldCode = NormalizeText(File.ReadAllText(outputFile, Encoding.UTF8)); - string newCode = NormalizeText(GenerateCode()); - return oldCode == newCode; - } - - private static string NormalizeText(string input) - { - return Regex.Replace(input, @"\s+", string.Empty); - } - - public void Generate(string outputFile) - { - FileUtil.CreateParentDir(outputFile); - - string code = GenerateCode(); - - File.WriteAllText(outputFile, code, Encoding.UTF8); - Debug.Log($"Generate EncryptionVM code to {outputFile}"); - } - - private string GenerateCode() - { - var lines = new List(); - AppendHeader(lines); - AppendEncryptCodes(lines); - AppendDecryptCodes(lines); - AppendTailer(lines); - return string.Join("\n", lines); - } - - private void AppendEncryptCodes(List lines) - { - lines.Add(@" - private int ExecuteEncrypt(int value, int opCode, int salt) - { - switch (opCode) - {"); - foreach (var opCode in _vm.opCodes) - { - lines.Add($@" case {opCode.code}: - {{ - // {opCode.function.GetType().Name}"); - AppendEncryptCode(lines, opCode.function); - lines.Add(@" return value; - }"); - } - - lines.Add(@" - default: - throw new System.Exception($""Invalid opCode:{opCode}""); - } - }"); - } - - private void AppendDecryptCodes(List lines) - { - lines.Add(@" - private int ExecuteDecrypt(int value, int opCode, int salt) - { - switch (opCode) - {"); - foreach (var opCode in _vm.opCodes) - { - lines.Add($@" case {opCode.code}: - {{ - // {opCode.function.GetType().Name}"); - AppendDecryptCode(lines, opCode.function); - lines.Add(@" return value; - }"); - } - - lines.Add(@" - default: - throw new System.Exception($""Invalid opCode:{opCode}""); - } - }"); - } - - private void AppendHeader(List lines) - { - - lines.Add($"/// This file is auto-generated by Obfuz. Do not modify it."); - lines.Add($"///"); - //lines.Add($"/// Created Time: {DateTime.Now}"); - - lines.Add($"/// Version: {_vm.version}"); - lines.Add($"/// SecretKey: {_vm.codeGenerationSecretKey}"); - lines.Add($"/// OpCodeCount: {_vm.opCodes.Length}"); - - lines.Add(@" -namespace Obfuz.EncryptionVM -{ - public class GeneratedEncryptionVirtualMachine : Obfuz.EncryptorBase - {"); - lines.Add($@" - private const int kOpCodeBits = {_opCodeBits}; - - private const int kOpCodeCount = {_opCodeCount}; - - private const int kOpCodeMask = {_opCodeCount - 1}; -"); - lines.Add(@" - - private readonly int[] _secretKey; - - public GeneratedEncryptionVirtualMachine(byte[] secretKey) - { - this._secretKey = ConvertToIntKey(secretKey); - } - - public override int OpCodeCount => kOpCodeCount; - - public override int Encrypt(int value, int opts, int salt) - { - uint uopts = (uint)opts; - uint revertOps = 0; - while (uopts != 0) - { - uint opCode = uopts & kOpCodeMask; - revertOps <<= kOpCodeBits; - revertOps |= opCode; - uopts >>= kOpCodeBits; - } - - while (revertOps != 0) - { - uint opCode = revertOps & kOpCodeMask; - value = ExecuteEncrypt(value, (int)opCode, salt); - revertOps >>= kOpCodeBits; - } - return value; - } - - public override int Decrypt(int value, int opts, int salt) - { - uint uopts = (uint)opts; - while (uopts != 0) - { - uint opCode = uopts & kOpCodeMask; - value = ExecuteDecrypt(value, (int)opCode, salt); - uopts >>= kOpCodeBits; - } - return value; - } -"); - } - - private void AppendTailer(List lines) - { - lines.Add(@" - } -} - -"); - } - - private void AppendEncryptCode(List lines, IEncryptionInstruction instruction) - { - instruction.GenerateEncryptCode(lines, " "); - } - - private void AppendDecryptCode(List lines, IEncryptionInstruction instruction) - { - instruction.GenerateDecryptCode(lines, " "); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/VirtualMachineCodeGenerator.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/VirtualMachineCodeGenerator.cs.meta deleted file mode 100644 index 956402cb..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/VirtualMachineCodeGenerator.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 2246e9d3369eb3c45bc19ae0748d76ba -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/VirtualMachineCreator.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/VirtualMachineCreator.cs deleted file mode 100644 index e0fca883..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/VirtualMachineCreator.cs +++ /dev/null @@ -1,68 +0,0 @@ -using Obfuz.EncryptionVM.Instructions; -using Obfuz.Utils; -using System; -using System.Collections.Generic; - -namespace Obfuz.EncryptionVM -{ - public class VirtualMachineCreator - { - private readonly string _vmGenerationSecretKey; - private readonly IRandom _random; - - public const int CodeGenerationSecretKeyLength = 1024; - - public const int VirtualMachineVersion = 1; - - public VirtualMachineCreator(string vmGenerationSecretKey) - { - _vmGenerationSecretKey = vmGenerationSecretKey; - byte[] byteGenerationSecretKey = KeyGenerator.GenerateKey(vmGenerationSecretKey, CodeGenerationSecretKeyLength); - int[] intGenerationSecretKey = KeyGenerator.ConvertToIntKey(byteGenerationSecretKey); - _random = new RandomWithKey(intGenerationSecretKey, 0); - } - - private readonly List> _instructionCreators = new List> - { - (r, len) => new AddInstruction(r.NextInt(), r.NextInt(len)), - (r, len) => new XorInstruction(r.NextInt(), r.NextInt(len)), - (r, len) => new BitRotateInstruction(r.NextInt(32), r.NextInt(len)), - (r, len) => new MultipleInstruction(r.NextInt() | 0x1, r.NextInt(len)), - (r, len) => new AddRotateXorInstruction(r.NextInt(), r.NextInt(len), r.NextInt(32), r.NextInt()), - (r, len) => new AddXorRotateInstruction(r.NextInt(), r.NextInt(len), r.NextInt(), r.NextInt(32)), - (r, len) => new XorAddRotateInstruction(r.NextInt(), r.NextInt(), r.NextInt(len), r.NextInt(32)), - (r, len) => new MultipleRotateXorInstruction(r.NextInt() | 0x1, r.NextInt(len), r.NextInt(32), r.NextInt()), - (r, len) => new MultipleXorRotateInstruction(r.NextInt() | 0x1, r.NextInt(len), r.NextInt(), r.NextInt(32)), - (r, len) => new XorMultipleRotateInstruction(r.NextInt(), r.NextInt() | 0x1, r.NextInt(len), r.NextInt(32)), - }; - - private IEncryptionInstruction CreateRandomInstruction(int intSecretKeyLength) - { - return _instructionCreators[_random.NextInt(_instructionCreators.Count)](_random, intSecretKeyLength); - } - - private EncryptionInstructionWithOpCode CreateEncryptOpCode(ushort code) - { - IEncryptionInstruction inst = CreateRandomInstruction(VirtualMachine.SecretKeyLength / sizeof(int)); - return new EncryptionInstructionWithOpCode(code, inst); - } - - public VirtualMachine CreateVirtualMachine(int opCodeCount) - { - if (opCodeCount < 64) - { - throw new System.Exception("OpCode count should be >= 64"); - } - if ((opCodeCount & (opCodeCount - 1)) != 0) - { - throw new System.Exception("OpCode count should be power of 2"); - } - var opCodes = new EncryptionInstructionWithOpCode[opCodeCount]; - for (int i = 0; i < opCodes.Length; i++) - { - opCodes[i] = CreateEncryptOpCode((ushort)i); - } - return new VirtualMachine(VirtualMachineVersion, _vmGenerationSecretKey, opCodes); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/VirtualMachineCreator.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/VirtualMachineCreator.cs.meta deleted file mode 100644 index 3124bb7b..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/VirtualMachineCreator.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 77d95ff5cf0b3aa4e96a055e37c381ba -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/VirtualMachineSimulator.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/VirtualMachineSimulator.cs deleted file mode 100644 index 175881f2..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/VirtualMachineSimulator.cs +++ /dev/null @@ -1,90 +0,0 @@ -using Obfuz.Utils; -using System.Collections.Generic; -using UnityEngine.Assertions; - -namespace Obfuz.EncryptionVM -{ - - public class VirtualMachineSimulator : EncryptorBase - { - private readonly EncryptionInstructionWithOpCode[] _opCodes; - private readonly int[] _secretKey; - - public override int OpCodeCount => _opCodes.Length; - - public VirtualMachineSimulator(VirtualMachine vm, byte[] byteSecretKey) - { - _opCodes = vm.opCodes; - _secretKey = KeyGenerator.ConvertToIntKey(byteSecretKey); - - VerifyInstructions(); - } - - private void VerifyInstructions() - { - int value = 0x11223344; - for (int i = 0; i < _opCodes.Length; i++) - { - int encryptedValue = _opCodes[i].Encrypt(value, _secretKey, i); - int decryptedValue = _opCodes[i].Decrypt(encryptedValue, _secretKey, i); - //Debug.Log($"instruction type:{_opCodes[i].function.GetType()}"); - Assert.AreEqual(value, decryptedValue); - } - - int ops = 11223344; - int salt = 789; - Assert.AreEqual(1, Decrypt(Encrypt(1, ops, salt), ops, salt)); - Assert.AreEqual(1L, Decrypt(Encrypt(1L, ops, salt), ops, salt)); - Assert.AreEqual(1.0f, Decrypt(Encrypt(1.0f, ops, salt), ops, salt)); - Assert.AreEqual(1.0, Decrypt(Encrypt(1.0, ops, salt), ops, salt)); - - byte[] strBytes = Encrypt("abcdef", ops, salt); - Assert.AreEqual("abcdef", DecryptString(strBytes, 0, strBytes.Length, ops, salt)); - var arr = new byte[100]; - for (int i = 0; i < arr.Length; i++) - { - arr[i] = (byte)i; - } - EncryptBlock(arr, ops, salt); - DecryptBlock(arr, ops, salt); - for (int i = 0; i < arr.Length; i++) - { - Assert.AreEqual(i, arr[i]); - } - } - - private List DecodeOps(uint ops) - { - var codes = new List(); - while (ops != 0) - { - uint code = ops % (uint)_opCodes.Length; - codes.Add(code); - ops /= (uint)_opCodes.Length; - } - return codes; - } - - public override int Encrypt(int value, int ops, int salt) - { - var codes = DecodeOps((uint)ops); - for (int i = codes.Count - 1; i >= 0; i--) - { - var opCode = _opCodes[codes[i]]; - value = opCode.Encrypt(value, _secretKey, salt); - } - return value; - } - - public override int Decrypt(int value, int ops, int salt) - { - var codes = DecodeOps((uint)ops); - foreach (var code in codes) - { - var opCode = _opCodes[code]; - value = opCode.Decrypt(value, _secretKey, salt); - } - return value; - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/VirtualMachineSimulator.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/VirtualMachineSimulator.cs.meta deleted file mode 100644 index 532a4985..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/EncryptionVM/VirtualMachineSimulator.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 4f86f4d6faf49764a915d5c675091375 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/GarbageCodeGeneration.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/GarbageCodeGeneration.meta deleted file mode 100644 index 29fa1339..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/GarbageCodeGeneration.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: f47f2abd9eb7ba8469ba5cb1bb085d33 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/GarbageCodeGeneration/ConfigGarbageCodeGenerator.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/GarbageCodeGeneration/ConfigGarbageCodeGenerator.cs deleted file mode 100644 index 06a7aebb..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/GarbageCodeGeneration/ConfigGarbageCodeGenerator.cs +++ /dev/null @@ -1,117 +0,0 @@ -using Obfuz.Utils; -using System; -using System.Linq; -using System.Text; - -namespace Obfuz.GarbageCodeGeneration -{ - - public class ConfigGarbageCodeGenerator : SpecificGarbageCodeGeneratorBase - { - - private readonly string[] _types = new string[] - { - "bool", - "byte", - "short", - "int", - "long", - "float", - "double", - }; - - private string CreateRandomType(IRandom random) - { - return _types[random.NextInt(_types.Length)]; - } - - private string GetReadMethodNameOfType(string type) - { - switch (type) - { - case "bool": return "ReadBoolean"; - case "byte": return "ReadByte"; - case "short": return "ReadInt16"; - case "int": return "ReadInt32"; - case "long": return "ReadInt64"; - case "float": return "ReadSingle"; - case "double": return "ReadDouble"; - default: throw new ArgumentException($"Unsupported type: {type}"); - } - } - class FieldGenerationInfo - { - public int index; - public string name; - public string type; - } - - class MethodGenerationInfo - { - public int index; - public string name; - } - - protected override object CreateField(int index, IRandom random, GenerationParameters parameters) - { - return new FieldGenerationInfo - { - index = index, - name = $"x{index}", - type = CreateRandomType(random), - }; - } - - protected override object CreateMethod(int index, IRandom random, GenerationParameters parameters) - { - return new MethodGenerationInfo - { - index = index, - name = $"Load{index}", - }; - } - - protected override void GenerateUsings(StringBuilder result, IClassGenerationInfo cgi) - { - } - - protected override void GenerateField(StringBuilder result, IClassGenerationInfo cgi, IRandom random, object field, string indent) - { - var fgi = (FieldGenerationInfo)field; - result.AppendLine($"{indent}public {fgi.type} {fgi.name};"); - } - - protected override void GenerateMethod(StringBuilder result, IClassGenerationInfo cgi, IRandom random, object method, string indent) - { - var mgi = (MethodGenerationInfo)method; - result.AppendLine($"{indent}public void {mgi.name}(BinaryReader reader)"); - result.AppendLine($"{indent}{{"); - - string indent2 = indent + " "; - result.AppendLine($"{indent2}int a = 0;"); - result.AppendLine($"{indent2}int b = 0;"); - int maxN = 100; - var shuffledFields = cgi.Fields.ToList(); - RandomUtil.ShuffleList(shuffledFields, random); - foreach (FieldGenerationInfo fgi in shuffledFields) - { - result.AppendLine($"{indent2}this.{fgi.name} = reader.{GetReadMethodNameOfType(fgi.type)}();"); - if (random.NextInPercentage(0.5f)) - { - result.AppendLine($"{indent2}a = b * {random.NextInt(maxN)} + reader.ReadInt32();"); - result.AppendLine($"{indent2}b = a * reader.ReadInt32() + {random.NextInt(maxN)};"); - } - if (random.NextInPercentage(0.5f)) - { - result.AppendLine($"{indent2}a += {random.NextInt(0, 10000)};"); - } - if (random.NextInPercentage(0.5f)) - { - result.AppendLine($"{indent2}b += {random.NextInt(0, 10000)};"); - } - } - - result.AppendLine($"{indent}}}"); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/GarbageCodeGeneration/ConfigGarbageCodeGenerator.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/GarbageCodeGeneration/ConfigGarbageCodeGenerator.cs.meta deleted file mode 100644 index c47c0405..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/GarbageCodeGeneration/ConfigGarbageCodeGenerator.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 327cb4a465ff23944a5fea30bf3beeeb -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/GarbageCodeGeneration/GarbageCodeGenerator.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/GarbageCodeGeneration/GarbageCodeGenerator.cs deleted file mode 100644 index 2b00c446..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/GarbageCodeGeneration/GarbageCodeGenerator.cs +++ /dev/null @@ -1,92 +0,0 @@ -using Obfuz.Settings; -using Obfuz.Utils; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using UnityEngine; - -namespace Obfuz.GarbageCodeGeneration -{ - - public class GarbageCodeGenerator - { - private const int CodeGenerationSecretKeyLength = 1024; - - private readonly GarbageCodeGenerationSettings _settings; - private readonly int[] _intGenerationSecretKey; - - public GarbageCodeGenerator(GarbageCodeGenerationSettings settings) - { - _settings = settings; - - byte[] byteGenerationSecretKey = KeyGenerator.GenerateKey(settings.codeGenerationSecret, CodeGenerationSecretKeyLength); - _intGenerationSecretKey = KeyGenerator.ConvertToIntKey(byteGenerationSecretKey); - } - - public void Generate() - { - GenerateTask(_settings.defaultTask); - if (_settings.additionalTasks != null && _settings.additionalTasks.Length > 0) - { - foreach (var task in _settings.additionalTasks) - { - GenerateTask(task); - } - } - } - - public void CleanCodes() - { - Debug.Log($"Cleaning generated garbage codes begin."); - if (_settings.defaultTask != null) - { - FileUtil.RemoveDir(_settings.defaultTask.outputPath, true); - } - if (_settings.additionalTasks != null && _settings.additionalTasks.Length > 0) - { - foreach (var task in _settings.additionalTasks) - { - FileUtil.RemoveDir(task.outputPath, true); - } - } - } - - private void GenerateTask(GarbageCodeGenerationTask task) - { - Debug.Log($"Generating garbage code with seed: {task.codeGenerationRandomSeed}, class count: {task.classCount}, method count per class: {task.methodCountPerClass}, types: {task.garbageCodeType}, output path: {task.outputPath}"); - - if (string.IsNullOrWhiteSpace(task.outputPath)) - { - throw new Exception("outputPath of GarbageCodeGenerationTask is empty!"); - } - - var generator = CreateSpecificCodeGenerator(task.garbageCodeType); - - var parameters = new GenerationParameters - { - random = new RandomWithKey(_intGenerationSecretKey, task.codeGenerationRandomSeed), - classNamespace = task.classNamespace, - classNamePrefix = task.classNamePrefix, - classCount = task.classCount, - methodCountPerClass = task.methodCountPerClass, - fieldCountPerClass = task.fieldCountPerClass, - outputPath = task.outputPath, - }; - generator.Generate(parameters); - - Debug.Log($"Generate garbage code end."); - } - - private ISpecificGarbageCodeGenerator CreateSpecificCodeGenerator(GarbageCodeType type) - { - switch (type) - { - case GarbageCodeType.Config: return new ConfigGarbageCodeGenerator(); - case GarbageCodeType.UI: return new UIGarbageCodeGenerator(); - default: throw new NotSupportedException($"Garbage code type {type} is not supported."); - } - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/GarbageCodeGeneration/GarbageCodeGenerator.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/GarbageCodeGeneration/GarbageCodeGenerator.cs.meta deleted file mode 100644 index 4939c45d..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/GarbageCodeGeneration/GarbageCodeGenerator.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ff64fd1e6f7b8874db5a5228fab159f9 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/GarbageCodeGeneration/ISpecificGarbageCodeGenerator.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/GarbageCodeGeneration/ISpecificGarbageCodeGenerator.cs deleted file mode 100644 index 9deda5cc..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/GarbageCodeGeneration/ISpecificGarbageCodeGenerator.cs +++ /dev/null @@ -1,22 +0,0 @@ -using Obfuz.Settings; -using Obfuz.Utils; - -namespace Obfuz.GarbageCodeGeneration -{ - public class GenerationParameters - { - public IRandom random; - - public string classNamespace; - public string classNamePrefix; - public int classCount; - public int methodCountPerClass; - public int fieldCountPerClass; - public string outputPath; - } - - public interface ISpecificGarbageCodeGenerator - { - void Generate(GenerationParameters parameters); - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/GarbageCodeGeneration/ISpecificGarbageCodeGenerator.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/GarbageCodeGeneration/ISpecificGarbageCodeGenerator.cs.meta deleted file mode 100644 index 9cb265c7..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/GarbageCodeGeneration/ISpecificGarbageCodeGenerator.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 74a17802b5aab2e40a3c89e0ddbcec0d -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/GarbageCodeGeneration/SpecificGarbageCodeGeneratorBase.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/GarbageCodeGeneration/SpecificGarbageCodeGeneratorBase.cs deleted file mode 100644 index c237343f..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/GarbageCodeGeneration/SpecificGarbageCodeGeneratorBase.cs +++ /dev/null @@ -1,106 +0,0 @@ -using Obfuz.Utils; -using System.Collections.Generic; -using System.IO; -using System.Text; -using UnityEngine; - -namespace Obfuz.GarbageCodeGeneration -{ - public abstract class SpecificGarbageCodeGeneratorBase : ISpecificGarbageCodeGenerator - { - protected interface IClassGenerationInfo - { - string Namespace { get; set; } - - string Name { get; set; } - - IList Fields { get; set; } - - IList Methods { get; set; } - } - - protected class ClassGenerationInfo : IClassGenerationInfo - { - public string Namespace { get; set; } - public string Name { get; set; } - public IList Fields { get; set; } = new List(); - public IList Methods { get; set; } = new List(); - } - - public virtual void Generate(GenerationParameters parameters) - { - FileUtil.RecreateDir(parameters.outputPath); - - for (int i = 0; i < parameters.classCount; i++) - { - Debug.Log($"[{GetType().Name}] Generating class {i}"); - var localRandom = new RandomWithKey(((RandomWithKey)parameters.random).Key, parameters.random.NextInt()); - string outputFile = $"{parameters.outputPath}/__GeneratedGarbageClass_{i}.cs"; - var result = new StringBuilder(64 * 1024); - GenerateClass(i, localRandom, result, parameters); - File.WriteAllText(outputFile, result.ToString(), Encoding.UTF8); - Debug.Log($"[{GetType().Name}] Generated class {i} to {outputFile}"); - } - } - - protected abstract object CreateField(int index, IRandom random, GenerationParameters parameters); - - protected abstract object CreateMethod(int index, IRandom random, GenerationParameters parameters); - - protected virtual IClassGenerationInfo CreateClassGenerationInfo(string classNamespace, string className, IRandom random, GenerationParameters parameters) - { - var cgi = new ClassGenerationInfo - { - Namespace = classNamespace, - Name = className, - }; - - for (int i = 0; i < parameters.fieldCountPerClass; i++) - { - cgi.Fields.Add(CreateField(i, random, parameters)); - } - - for (int i = 0; i < parameters.methodCountPerClass; i++) - { - cgi.Methods.Add(CreateMethod(i, random, parameters)); - } - - return cgi; - } - - protected virtual void GenerateClass(int classIndex, IRandom random, StringBuilder result, GenerationParameters parameters) - { - IClassGenerationInfo cgi = CreateClassGenerationInfo(parameters.classNamespace, $"{parameters.classNamePrefix}{classIndex}", random, parameters); - result.AppendLine("using System;"); - result.AppendLine("using System.Collections.Generic;"); - result.AppendLine("using System.Linq;"); - result.AppendLine("using System.IO;"); - result.AppendLine("using UnityEngine;"); - - GenerateUsings(result, cgi); - - result.AppendLine($"namespace {cgi.Namespace}"); - result.AppendLine("{"); - result.AppendLine($" public class {cgi.Name}"); - result.AppendLine(" {"); - - string indent = " "; - foreach (object field in cgi.Fields) - { - GenerateField(result, cgi, random, field, indent); - } - foreach (object method in cgi.Methods) - { - GenerateMethod(result, cgi, random, method, indent); - } - result.AppendLine(" }"); - result.AppendLine("}"); - } - - protected abstract void GenerateUsings(StringBuilder result, IClassGenerationInfo cgi); - - protected abstract void GenerateField(StringBuilder result, IClassGenerationInfo cgi, IRandom random, object field, string indent); - - protected abstract void GenerateMethod(StringBuilder result, IClassGenerationInfo cgi, IRandom random, object method, string indent); - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/GarbageCodeGeneration/SpecificGarbageCodeGeneratorBase.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/GarbageCodeGeneration/SpecificGarbageCodeGeneratorBase.cs.meta deleted file mode 100644 index 7696864a..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/GarbageCodeGeneration/SpecificGarbageCodeGeneratorBase.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: bae18fd49482f00439d37f28a6a78d9b -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/GarbageCodeGeneration/UIGarbageCodeGenerator.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/GarbageCodeGeneration/UIGarbageCodeGenerator.cs deleted file mode 100644 index 7287dce7..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/GarbageCodeGeneration/UIGarbageCodeGenerator.cs +++ /dev/null @@ -1,157 +0,0 @@ -using Obfuz.Utils; -using System; -using System.Linq; -using System.Text; - -namespace Obfuz.GarbageCodeGeneration -{ - - public class UIGarbageCodeGenerator : SpecificGarbageCodeGeneratorBase - { - /* - * - * public Button b1; - public Image b2; - public RawImage b30; - public Text b3; - public Slider b4; - public ScrollRect b5; - public Scrollbar b6; - public Mask b7; - public RectMask2D b70; - public Canvas b8; - public CanvasGroup b9; - public RectTransform b10; - public Transform b11; - public GameObject b12; - */ - - private readonly string[] _types = new string[] - { - "Button", - "Image", - "RawImage", - "Text", - "Slider", - "ScrollRect", - "Scrollbar", - "Mask", - "RectMask2D", - "Canvas", - "CanvasGroup", - "RectTransform", - //"Transform", - //"GameObject", - }; - - private string CreateRandomType(IRandom random) - { - return _types[random.NextInt(_types.Length)]; - } - - private string GetReadMethodNameOfType(string type) - { - switch (type) - { - case "bool": return "ReadBoolean"; - case "byte": return "ReadByte"; - case "short": return "ReadInt16"; - case "int": return "ReadInt32"; - case "long": return "ReadInt64"; - case "float": return "ReadSingle"; - case "double": return "ReadDouble"; - default: throw new ArgumentException($"Unsupported type: {type}"); - } - } - class FieldGenerationInfo - { - public int index; - public string name; - public string type; - } - - class MethodGenerationInfo - { - public int index; - public string name; - } - - protected override object CreateField(int index, IRandom random, GenerationParameters parameters) - { - return new FieldGenerationInfo - { - index = index, - name = $"x{index}", - type = CreateRandomType(random), - }; - } - - protected override object CreateMethod(int index, IRandom random, GenerationParameters parameters) - { - return new MethodGenerationInfo - { - index = index, - name = $"Init{index}", - }; - } - - protected override void GenerateUsings(StringBuilder result, IClassGenerationInfo cgi) - { - result.AppendLine("using UnityEngine.UI;"); - } - - protected override void GenerateField(StringBuilder result, IClassGenerationInfo cgi, IRandom random, object field, string indent) - { - var fgi = (FieldGenerationInfo)field; - result.AppendLine($"{indent}public {fgi.type} {fgi.name};"); - } - - protected override void GenerateMethod(StringBuilder result, IClassGenerationInfo cgi, IRandom random, object method, string indent) - { - var mgi = (MethodGenerationInfo)method; - result.AppendLine($"{indent}public void {mgi.name}(GameObject go)"); - result.AppendLine($"{indent}{{"); - - string indent2 = indent + " "; - result.AppendLine($"{indent2}int a = 0;"); - result.AppendLine($"{indent2}int b = 0;"); - int maxN = 100; - var shuffledFields = cgi.Fields.ToList(); - RandomUtil.ShuffleList(shuffledFields, random); - foreach (FieldGenerationInfo fgi in shuffledFields) - { - if (random.NextInPercentage(0.5f)) - { - result.AppendLine($"{indent2}this.{fgi.name} = go.transform.Find(\"ui/{fgi.name}\").GetComponent<{fgi.type}>();"); - } - else - { - result.AppendLine($"{indent2}this.{fgi.name} = go.GetComponent<{fgi.type}>();"); - } - if (random.NextInPercentage(0.5f)) - { - result.AppendLine($"{indent2}a = b * {random.NextInt(maxN)} + go.layer;"); - result.AppendLine($"{indent2}b = a * go.layer + {random.NextInt(maxN)};"); - } - if (random.NextInPercentage(0.5f)) - { - result.AppendLine($"{indent2}a *= {random.NextInt(0, 10000)};"); - } - if (random.NextInPercentage(0.5f)) - { - result.AppendLine($"{indent2}b /= {random.NextInt(0, 10000)};"); - } - if (random.NextInPercentage(0.5f)) - { - result.AppendLine($"{indent2}a = a * b << {random.NextInt(0, 10000)};"); - } - if (random.NextInPercentage(0.5f)) - { - result.AppendLine($"{indent2}b = a / b & {random.NextInt(0, 10000)};"); - } - } - - result.AppendLine($"{indent}}}"); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/GarbageCodeGeneration/UIGarbageCodeGenerator.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/GarbageCodeGeneration/UIGarbageCodeGenerator.cs.meta deleted file mode 100644 index 1dc2d282..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/GarbageCodeGeneration/UIGarbageCodeGenerator.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 5071c4b9c7f5aef409f3e7fdb45ecd8d -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/IObfuscationPass.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/IObfuscationPass.cs deleted file mode 100644 index 84c56f71..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/IObfuscationPass.cs +++ /dev/null @@ -1,15 +0,0 @@ -using Obfuz.ObfusPasses; - -namespace Obfuz -{ - public interface IObfuscationPass - { - ObfuscationPassType Type { get; } - - void Start(); - - void Stop(); - - void Process(); - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/IObfuscationPass.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/IObfuscationPass.cs.meta deleted file mode 100644 index cd501adc..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/IObfuscationPass.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: b7003f9503025794b8aa775d9ade335c -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses.meta deleted file mode 100644 index ed7f92c1..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 120b2dcffd582e84dbb92003240824d1 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/BasicBlockObfuscationPassBase.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/BasicBlockObfuscationPassBase.cs deleted file mode 100644 index 2b7deb35..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/BasicBlockObfuscationPassBase.cs +++ /dev/null @@ -1,53 +0,0 @@ -using dnlib.DotNet; -using dnlib.DotNet.Emit; -using Obfuz.Emit; -using System.Collections.Generic; - -namespace Obfuz.ObfusPasses -{ - public abstract class BasicBlockObfuscationPassBase : ObfuscationMethodPassBase - { - protected virtual bool ComputeBlockInLoop => true; - - protected abstract bool TryObfuscateInstruction(MethodDef callingMethod, Instruction inst, BasicBlock block, int instructionIndex, - IList globalInstructions, List outputInstructions, List totalFinalInstructions); - - protected override void ObfuscateData(MethodDef method) - { - BasicBlockCollection bbc = new BasicBlockCollection(method, ComputeBlockInLoop); - - IList instructions = method.Body.Instructions; - - var outputInstructions = new List(); - var totalFinalInstructions = new List(); - for (int i = 0; i < instructions.Count; i++) - { - Instruction inst = instructions[i]; - BasicBlock block = bbc.GetBasicBlockByInstruction(inst); - outputInstructions.Clear(); - if (TryObfuscateInstruction(method, inst, block, i, instructions, outputInstructions, totalFinalInstructions)) - { - // current instruction may be the target of control flow instruction, so we can't remove it directly. - // we replace it with nop now, then remove it in CleanUpInstructionPass - inst.OpCode = outputInstructions[0].OpCode; - inst.Operand = outputInstructions[0].Operand; - totalFinalInstructions.Add(inst); - for (int k = 1; k < outputInstructions.Count; k++) - { - totalFinalInstructions.Add(outputInstructions[k]); - } - } - else - { - totalFinalInstructions.Add(inst); - } - } - - instructions.Clear(); - foreach (var obInst in totalFinalInstructions) - { - instructions.Add(obInst); - } - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/BasicBlockObfuscationPassBase.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/BasicBlockObfuscationPassBase.cs.meta deleted file mode 100644 index 027d02b9..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/BasicBlockObfuscationPassBase.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ae83aaf003665614092aabceabff3cf8 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus.meta deleted file mode 100644 index a5ed3334..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: cf68e45551825c547b137f6e5189937e -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/CallObfusPass.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/CallObfusPass.cs deleted file mode 100644 index 6a099f91..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/CallObfusPass.cs +++ /dev/null @@ -1,166 +0,0 @@ -using dnlib.DotNet; -using dnlib.DotNet.Emit; -using Obfuz.Emit; -using Obfuz.Settings; -using Obfuz.Utils; -using System.Collections.Generic; - -namespace Obfuz.ObfusPasses.CallObfus -{ - class ObfusMethodContext - { - public MethodDef method; - public LocalVariableAllocator localVariableAllocator; - public IRandom localRandom; - public EncryptionScopeInfo encryptionScope; - } - - public class CallObfusPass : ObfuscationMethodPassBase - { - public static CallObfuscationSettingsFacade CurrentSettings { get; private set; } - - private readonly CallObfuscationSettingsFacade _settings; - private readonly SpecialWhiteListMethodCalculator _specialWhiteListMethodCache; - - private IObfuscator _dynamicProxyObfuscator; - private IObfuscationPolicy _dynamicProxyPolicy; - - public override ObfuscationPassType Type => ObfuscationPassType.CallObfus; - - public CallObfusPass(CallObfuscationSettingsFacade settings) - { - _settings = settings; - CurrentSettings = settings; - - _specialWhiteListMethodCache = new SpecialWhiteListMethodCalculator(settings.obfuscateCallToMethodInMscorlib); - } - - public override void Stop() - { - _dynamicProxyObfuscator.Done(); - } - - public override void Start() - { - var ctx = ObfuscationPassContext.Current; - _dynamicProxyObfuscator = CreateObfuscator(ctx, _settings.proxyMode); - _dynamicProxyPolicy = new ConfigurableObfuscationPolicy(ctx.coreSettings.assembliesToObfuscate, _settings.ruleFiles); - } - - private IObfuscator CreateObfuscator(ObfuscationPassContext ctx, ProxyMode mode) - { - switch (mode) - { - case ProxyMode.Dispatch: - return new DispatchProxyObfuscator(ctx.moduleEntityManager); - case ProxyMode.Delegate: - return new DelegateProxyObfuscator(ctx.moduleEntityManager); - default: - throw new System.NotSupportedException($"Unsupported proxy mode: {mode}"); - } - } - - protected override void ObfuscateData(MethodDef method) - { - BasicBlockCollection bbc = new BasicBlockCollection(method, false); - - IList instructions = method.Body.Instructions; - - var outputInstructions = new List(); - var totalFinalInstructions = new List(); - - ObfuscationPassContext ctx = ObfuscationPassContext.Current; - var encryptionScope = ctx.moduleEntityManager.EncryptionScopeProvider.GetScope(method.Module); - var localRandom = encryptionScope.localRandomCreator(MethodEqualityComparer.CompareDeclaringTypes.GetHashCode(method)); - var omc = new ObfusMethodContext - { - method = method, - localVariableAllocator = new LocalVariableAllocator(method), - localRandom = localRandom, - encryptionScope = encryptionScope, - }; - Instruction lastInst = null; - for (int i = 0; i < instructions.Count; i++) - { - Instruction inst = instructions[i]; - BasicBlock block = bbc.GetBasicBlockByInstruction(inst); - outputInstructions.Clear(); - if (TryObfuscateInstruction(method, lastInst, inst, outputInstructions, omc)) - { - // current instruction may be the target of control flow instruction, so we can't remove it directly. - // we replace it with nop now, then remove it in CleanUpInstructionPass - inst.OpCode = outputInstructions[0].OpCode; - inst.Operand = outputInstructions[0].Operand; - totalFinalInstructions.Add(inst); - for (int k = 1; k < outputInstructions.Count; k++) - { - totalFinalInstructions.Add(outputInstructions[k]); - } - } - else - { - totalFinalInstructions.Add(inst); - } - lastInst = inst; - } - - instructions.Clear(); - foreach (var obInst in totalFinalInstructions) - { - instructions.Add(obInst); - } - } - - protected override bool NeedObfuscateMethod(MethodDef method) - { - return _dynamicProxyPolicy.NeedObfuscateCallInMethod(method); - } - - private bool TryObfuscateInstruction(MethodDef callerMethod, Instruction lastInst, Instruction inst, List outputInstructions, ObfusMethodContext ctx) - { - IMethod calledMethod = inst.Operand as IMethod; - if (calledMethod == null || !calledMethod.IsMethod) - { - return false; - } - if (MetaUtil.ContainsContainsGenericParameter(calledMethod)) - { - return false; - } - - bool callVir; - switch (inst.OpCode.Code) - { - case Code.Call: - { - callVir = false; - break; - } - case Code.Callvirt: - { - if (lastInst != null && lastInst.OpCode.Code == Code.Constrained) - { - return false; - } - callVir = true; - break; - } - default: return false; - } - - - if (_specialWhiteListMethodCache.IsInWhiteList(calledMethod)) - { - return false; - } - - - if (!_dynamicProxyPolicy.NeedObfuscateCalledMethod(callerMethod, calledMethod, callVir)) - { - return false; - } - - return _dynamicProxyObfuscator.Obfuscate(callerMethod, calledMethod, callVir, outputInstructions); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/CallObfusPass.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/CallObfusPass.cs.meta deleted file mode 100644 index b15eb819..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/CallObfusPass.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 112178b770868274fb8119a4997a3420 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/ConfigurableObfuscationPolicy.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/ConfigurableObfuscationPolicy.cs deleted file mode 100644 index 57a30e58..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/ConfigurableObfuscationPolicy.cs +++ /dev/null @@ -1,300 +0,0 @@ -using dnlib.DotNet; -using Obfuz.Conf; -using Obfuz.Settings; -using Obfuz.Utils; -using System; -using System.Collections.Generic; -using System.Xml; - -namespace Obfuz.ObfusPasses.CallObfus -{ - public class ConfigurableObfuscationPolicy : ObfuscationPolicyBase - { - class WhiteListAssembly - { - public string name; - public NameMatcher nameMatcher; - public bool? obfuscate; - public List types = new List(); - } - - class WhiteListType - { - public string name; - public NameMatcher nameMatcher; - public bool? obfuscate; - public List methods = new List(); - } - - class WhiteListMethod - { - public string name; - public NameMatcher nameMatcher; - public bool? obfuscate; - } - - class ObfuscationRule : IRule - { - public ObfuscationLevel? obfuscationLevel; - - public void InheritParent(ObfuscationRule parentRule) - { - if (obfuscationLevel == null) - obfuscationLevel = parentRule.obfuscationLevel; - } - } - - class AssemblySpec : AssemblyRuleBase - { - } - - class TypeSpec : TypeRuleBase - { - } - - class MethodSpec : MethodRuleBase - { - - } - - private static readonly ObfuscationRule s_default = new ObfuscationRule() - { - obfuscationLevel = ObfuscationLevel.Basic, - }; - - private readonly XmlAssemblyTypeMethodRuleParser _configParser; - - private ObfuscationRule _global; - private readonly List _whiteListAssemblies = new List(); - - private readonly CachedDictionary _whiteListMethodCache; - private readonly Dictionary _methodRuleCache = new Dictionary(); - - public ConfigurableObfuscationPolicy(List toObfuscatedAssemblyNames, List xmlConfigFiles) - { - _whiteListMethodCache = new CachedDictionary(MethodEqualityComparer.CompareDeclaringTypes, this.ComputeIsInWhiteList); - _configParser = new XmlAssemblyTypeMethodRuleParser(toObfuscatedAssemblyNames, - ParseObfuscationRule, ParseGlobalElement); - LoadConfigs(xmlConfigFiles); - } - - private void LoadConfigs(List configFiles) - { - _configParser.LoadConfigs(configFiles); - - if (_global == null) - { - _global = s_default; - } - else - { - _global.InheritParent(s_default); - } - _configParser.InheritParentRules(_global); - InheritWhitelistRules(); - } - - private void InheritWhitelistRules() - { - foreach (var ass in _whiteListAssemblies) - { - foreach (var type in ass.types) - { - if (type.obfuscate == null) - { - type.obfuscate = ass.obfuscate; - } - foreach (var method in type.methods) - { - if (method.obfuscate == null) - { - method.obfuscate = type.obfuscate; - } - } - } - } - } - - private void ParseGlobalElement(string configFile, XmlElement ele) - { - switch (ele.Name) - { - case "global": _global = ParseObfuscationRule(configFile, ele); break; - case "whitelist": ParseWhitelist(ele); break; - default: throw new Exception($"Invalid xml file {configFile}, unknown node {ele.Name}"); - } - } - - private ObfuscationRule ParseObfuscationRule(string configFile, XmlElement ele) - { - var rule = new ObfuscationRule(); - if (ele.HasAttribute("obfuscationLevel")) - { - rule.obfuscationLevel = ConfigUtil.ParseObfuscationLevel(ele.GetAttribute("obfuscationLevel")); - } - return rule; - } - - private void ParseWhitelist(XmlElement ruleEle) - { - foreach (XmlNode xmlNode in ruleEle.ChildNodes) - { - if (!(xmlNode is XmlElement childEle)) - { - continue; - } - switch (childEle.Name) - { - case "assembly": - { - var ass = ParseWhiteListAssembly(childEle); - _whiteListAssemblies.Add(ass); - break; - } - default: throw new Exception($"Invalid xml file, unknown node {childEle.Name}"); - } - } - } - - private WhiteListAssembly ParseWhiteListAssembly(XmlElement element) - { - var ass = new WhiteListAssembly(); - ass.name = element.GetAttribute("name"); - ass.nameMatcher = new NameMatcher(ass.name); - - ass.obfuscate = ConfigUtil.ParseNullableBool(element.GetAttribute("obfuscate")) ?? false; - - foreach (XmlNode node in element.ChildNodes) - { - if (!(node is XmlElement ele)) - { - continue; - } - switch (ele.Name) - { - case "type": - ass.types.Add(ParseWhiteListType(ele)); - break; - default: - throw new Exception($"Invalid xml file, unknown node {ele.Name}"); - } - } - return ass; - } - - private WhiteListType ParseWhiteListType(XmlElement element) - { - var type = new WhiteListType(); - type.name = element.GetAttribute("name"); - type.nameMatcher = new NameMatcher(type.name); - type.obfuscate = ConfigUtil.ParseNullableBool(element.GetAttribute("obfuscate")); - - foreach (XmlNode node in element.ChildNodes) - { - if (!(node is XmlElement ele)) - { - continue; - } - switch (ele.Name) - { - case "method": - { - type.methods.Add(ParseWhiteListMethod(ele)); - break; - } - default: throw new Exception($"Invalid xml file, unknown node {ele.Name}"); - } - } - - return type; - } - - private WhiteListMethod ParseWhiteListMethod(XmlElement element) - { - var method = new WhiteListMethod(); - method.name = element.GetAttribute("name"); - method.nameMatcher = new NameMatcher(method.name); - method.obfuscate = ConfigUtil.ParseNullableBool(element.GetAttribute("obfuscate")); - return method; - } - - private ObfuscationRule GetMethodObfuscationRule(MethodDef method) - { - if (!_methodRuleCache.TryGetValue(method, out var rule)) - { - rule = _configParser.GetMethodRule(method, _global); - _methodRuleCache[method] = rule; - } - return rule; - } - - public override bool NeedObfuscateCallInMethod(MethodDef method) - { - ObfuscationRule rule = GetMethodObfuscationRule(method); - return rule.obfuscationLevel != null && rule.obfuscationLevel.Value >= ObfuscationLevel.Basic; - } - - private bool ComputeIsInWhiteList(IMethod calledMethod) - { - ITypeDefOrRef declaringType = calledMethod.DeclaringType; - TypeSig declaringTypeSig = calledMethod.DeclaringType.ToTypeSig(); - declaringTypeSig = declaringTypeSig.RemovePinnedAndModifiers(); - switch (declaringTypeSig.ElementType) - { - case ElementType.ValueType: - case ElementType.Class: - { - break; - } - case ElementType.GenericInst: - { - if (MetaUtil.ContainsContainsGenericParameter(calledMethod)) - { - return true; - } - break; - } - default: return true; - } - - TypeDef typeDef = declaringType.ResolveTypeDef(); - - string assName = typeDef.Module.Assembly.Name; - string typeFullName = typeDef.FullName; - string methodName = calledMethod.Name; - foreach (var ass in _whiteListAssemblies) - { - if (!ass.nameMatcher.IsMatch(assName)) - { - continue; - } - foreach (var type in ass.types) - { - if (!type.nameMatcher.IsMatch(typeFullName)) - { - continue; - } - foreach (var method in type.methods) - { - if (method.nameMatcher.IsMatch(methodName)) - { - return !method.obfuscate.Value; - } - } - return !type.obfuscate.Value; - } - return !ass.obfuscate.Value; - } - return false; - } - - public override bool NeedObfuscateCalledMethod(MethodDef callerMethod, IMethod calledMethod, bool callVir) - { - if (_whiteListMethodCache.GetValue(calledMethod)) - { - return false; - } - return true; - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/ConfigurableObfuscationPolicy.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/ConfigurableObfuscationPolicy.cs.meta deleted file mode 100644 index c970eec6..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/ConfigurableObfuscationPolicy.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: d9ea12b16c4b296459db8a60fb1615d6 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/DelegateProxyAllocator.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/DelegateProxyAllocator.cs deleted file mode 100644 index 7b9b6e04..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/DelegateProxyAllocator.cs +++ /dev/null @@ -1,263 +0,0 @@ -using dnlib.DotNet; -using dnlib.DotNet.Emit; -using Obfuz.Data; -using Obfuz.Emit; -using Obfuz.Settings; -using Obfuz.Utils; -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Obfuz.ObfusPasses.CallObfus -{ - - struct DelegateProxyMethodData - { - public readonly FieldDef delegateInstanceField; - public readonly MethodDef delegateInvokeMethod; - - public DelegateProxyMethodData(FieldDef delegateInstanceField, MethodDef delegateInvokeMethod) - { - this.delegateInstanceField = delegateInstanceField; - this.delegateInvokeMethod = delegateInvokeMethod; - } - } - - class DelegateProxyAllocator : GroupByModuleEntityBase - { - private readonly CachedDictionary _delegateTypes; - private readonly HashSet _allocatedDelegateNames = new HashSet(); - - private TypeDef _delegateInstanceHolderType; - private bool _done; - - class CallInfo - { - public string key1; - public int key2; - public IMethod method; - public bool callVir; - - public int index; - public TypeDef delegateType; - public FieldDef delegateInstanceField; - public MethodDef delegateInvokeMethod; - public MethodDef proxyMethod; - } - private readonly Dictionary _callMethods = new Dictionary(); - - public DelegateProxyAllocator() - { - _delegateTypes = new CachedDictionary(SignatureEqualityComparer.Instance, CreateDelegateForSignature); - } - - public override void Init() - { - _delegateInstanceHolderType = CreateDelegateInstanceHolderTypeDef(); - } - - private string AllocateDelegateTypeName(MethodSig delegateInvokeSig) - { - uint hashCode = (uint)SignatureEqualityComparer.Instance.GetHashCode(delegateInvokeSig); - string typeName = $"$Obfuz$Delegate_{hashCode}"; - if (_allocatedDelegateNames.Add(typeName)) - { - return typeName; - } - for (int i = 0; ;i++) - { - typeName = $"$Obfuz$Delegate_{hashCode}_{i}"; - if (_allocatedDelegateNames.Add(typeName)) - { - return typeName; - } - } - } - - private TypeDef CreateDelegateForSignature(MethodSig delegateInvokeSig) - { - ModuleDef mod = Module; - using (var scope = new DisableTypeDefFindCacheScope(mod)) - { - - string typeName = AllocateDelegateTypeName(delegateInvokeSig); - mod.Import(typeof(MulticastDelegate)); - - TypeDef delegateType = new TypeDefUser("", typeName, mod.CorLibTypes.GetTypeRef("System", "MulticastDelegate")); - delegateType.Attributes = TypeAttributes.Class | TypeAttributes.Sealed | TypeAttributes.Public; - mod.Types.Add(delegateType); - - MethodDef ctor = new MethodDefUser( - ".ctor", - MethodSig.CreateInstance(mod.CorLibTypes.Void, mod.CorLibTypes.Object, mod.CorLibTypes.IntPtr), - MethodImplAttributes.Runtime, - MethodAttributes.RTSpecialName | MethodAttributes.SpecialName | MethodAttributes.HideBySig | MethodAttributes.Public - ); - ctor.DeclaringType = delegateType; - - - MethodDef invokeMethod = new MethodDefUser( - "Invoke", - MethodSig.CreateInstance(delegateInvokeSig.RetType, delegateInvokeSig.Params.ToArray()), - MethodImplAttributes.Runtime, - MethodAttributes.HideBySig | MethodAttributes.Public | MethodAttributes.NewSlot | MethodAttributes.Virtual - ); - invokeMethod.DeclaringType = delegateType; - return delegateType; - } - } - - private TypeDef CreateDelegateInstanceHolderTypeDef() - { - ModuleDef mod = Module; - using (var scope = new DisableTypeDefFindCacheScope(mod)) - { - string typeName = "$Obfuz$DelegateInstanceHolder"; - TypeDef holderType = new TypeDefUser("", typeName, mod.CorLibTypes.Object.ToTypeDefOrRef()); - holderType.Attributes = TypeAttributes.Class | TypeAttributes.Public; - mod.Types.Add(holderType); - return holderType; - } - } - - private string AllocateFieldName(IMethod method, bool callVir) - { - uint hashCode = (uint)MethodEqualityComparer.CompareDeclaringTypes.GetHashCode(method); - string typeName = $"$Obfuz$Delegate$Field_{hashCode}_{callVir}"; - if (_allocatedDelegateNames.Add(typeName)) - { - return typeName; - } - for (int i = 0; ; i++) - { - typeName = $"$Obfuz$Delegate$Field_{hashCode}_{callVir}_{i}"; - if (_allocatedDelegateNames.Add(typeName)) - { - return typeName; - } - } - } - - private MethodDef CreateProxyMethod(string name, IMethod calledMethod, bool callVir, MethodSig delegateInvokeSig) - { - var proxyMethod = new MethodDefUser(name, delegateInvokeSig, MethodImplAttributes.Managed, MethodAttributes.Public | MethodAttributes.Static); - var body = new CilBody(); - proxyMethod.Body = body; - var ins = body.Instructions; - - foreach (Parameter param in proxyMethod.Parameters) - { - ins.Add(Instruction.Create(OpCodes.Ldarg, param)); - } - - ins.Add(Instruction.Create(callVir ? OpCodes.Callvirt : OpCodes.Call, calledMethod)); - ins.Add(Instruction.Create(OpCodes.Ret)); - return proxyMethod; - } - - public DelegateProxyMethodData Allocate(IMethod method, bool callVir, MethodSig delegateInvokeSig) - { - var key = new MethodKey(method, callVir); - if (!_callMethods.TryGetValue(key, out var callInfo)) - { - TypeDef delegateType = _delegateTypes.GetValue(delegateInvokeSig); - MethodDef delegateInvokeMethod = delegateType.FindMethod("Invoke"); - string fieldName = AllocateFieldName(method, callVir); - FieldDef delegateInstanceField = new FieldDefUser(fieldName, new FieldSig(delegateType.ToTypeSig()), FieldAttributes.Public | FieldAttributes.Static | FieldAttributes.InitOnly); - string key1 = $"{method.FullName}_{callVir}"; - callInfo = new CallInfo - { - key1 = key1, - key2 = HashUtil.ComputePrimitiveOrStringOrBytesHashCode(key1) * 33445566, - method = method, - callVir = callVir, - delegateType = delegateType, - delegateInstanceField = delegateInstanceField, - delegateInvokeMethod = delegateInvokeMethod, - proxyMethod = CreateProxyMethod($"{fieldName}$Proxy", method, callVir, delegateInvokeSig), - }; - _callMethods.Add(key, callInfo); - } - return new DelegateProxyMethodData(callInfo.delegateInstanceField, callInfo.delegateInvokeMethod); - } - - public override void Done() - { - if (_done) - { - throw new Exception("Already done"); - } - _done = true; - - ModuleDef mod = Module; - - // for stable order, we sort methods by name - List callMethodList = _callMethods.Values.ToList(); - callMethodList.Sort((a, b) => a.key1.CompareTo(b.key1)); - - var cctor = new MethodDefUser(".cctor", - MethodSig.CreateStatic(mod.CorLibTypes.Void), - MethodImplAttributes.IL | MethodImplAttributes.Managed, - MethodAttributes.Static | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName | MethodAttributes.Private); - cctor.DeclaringType = _delegateInstanceHolderType; - //_rvaTypeDef.Methods.Add(cctor); - var body = new CilBody(); - cctor.Body = body; - var ins = body.Instructions; - - // var arr = new array[]; - // var d = new delegate; - // arr[index] = d; - int index = 0; - ins.Add(Instruction.CreateLdcI4(callMethodList.Count)); - ins.Add(Instruction.Create(OpCodes.Newarr, mod.CorLibTypes.Object)); - foreach (CallInfo ci in callMethodList) - { - ci.index = index; - _delegateInstanceHolderType.Methods.Add(ci.proxyMethod); - ins.Add(Instruction.Create(OpCodes.Dup)); - ins.Add(Instruction.CreateLdcI4(index)); - ins.Add(Instruction.Create(OpCodes.Ldnull)); - ins.Add(Instruction.Create(OpCodes.Ldftn, ci.proxyMethod)); - MethodDef ctor = ci.delegateType.FindMethod(".ctor"); - UnityEngine.Assertions.Assert.IsNotNull(ctor, $"Delegate type {ci.delegateType.FullName} does not have a constructor."); - ins.Add(Instruction.Create(OpCodes.Newobj, ctor)); - ins.Add(Instruction.Create(OpCodes.Stelem_Ref)); - ++index; - } - - - - List callMethodList2 = callMethodList.ToList(); - callMethodList2.Sort((a, b) => a.key2.CompareTo(b.key2)); - - EncryptionScopeInfo encryptionScope = EncryptionScope; - DefaultMetadataImporter importer = this.GetDefaultModuleMetadataImporter(); - RvaDataAllocator rvaDataAllocator = this.GetEntity(); - foreach (CallInfo ci in callMethodList2) - { - _delegateInstanceHolderType.Fields.Add(ci.delegateInstanceField); - - - ins.Add(Instruction.Create(OpCodes.Dup)); - - IRandom localRandom = encryptionScope.localRandomCreator(HashUtil.ComputePrimitiveOrStringOrBytesHashCode(ci.key1)); - int ops = EncryptionUtil.GenerateEncryptionOpCodes(localRandom, encryptionScope.encryptor, 4); - int salt = localRandom.NextInt(); - - int encryptedValue = encryptionScope.encryptor.Encrypt(ci.index, ops, salt); - RvaData rvaData = rvaDataAllocator.Allocate(encryptedValue); - ins.Add(Instruction.Create(OpCodes.Ldsfld, rvaData.field)); - ins.Add(Instruction.CreateLdcI4(rvaData.offset)); - ins.Add(Instruction.CreateLdcI4(ops)); - ins.Add(Instruction.CreateLdcI4(salt)); - ins.Add(Instruction.Create(OpCodes.Call, importer.DecryptFromRvaInt)); - ins.Add(Instruction.Create(OpCodes.Ldelem_Ref)); - ins.Add(Instruction.Create(OpCodes.Stsfld, ci.delegateInstanceField)); - } - - ins.Add(Instruction.Create(OpCodes.Pop)); - ins.Add(Instruction.Create(OpCodes.Ret)); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/DelegateProxyAllocator.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/DelegateProxyAllocator.cs.meta deleted file mode 100644 index d324d9aa..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/DelegateProxyAllocator.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 02761bacbed8a8b489ae3e7f49f0f84a -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/DelegateProxyObfuscator.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/DelegateProxyObfuscator.cs deleted file mode 100644 index bc6ce18c..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/DelegateProxyObfuscator.cs +++ /dev/null @@ -1,83 +0,0 @@ -using dnlib.DotNet; -using dnlib.DotNet.Emit; -using Obfuz.Data; -using Obfuz.Emit; -using Obfuz.Settings; -using Obfuz.Utils; -using System.Collections.Generic; -using System.Linq; - -namespace Obfuz.ObfusPasses.CallObfus -{ - - public class DelegateProxyObfuscator : ObfuscatorBase - { - private readonly GroupByModuleEntityManager _entityManager; - - public DelegateProxyObfuscator(GroupByModuleEntityManager moduleEntityManager) - { - _entityManager = moduleEntityManager; - } - - public override void Done() - { - _entityManager.Done(); - } - - private MethodSig CreateProxyMethodSig(ModuleDef module, IMethod method) - { - MethodSig methodSig = MetaUtil.ToSharedMethodSig(module.CorLibTypes, MetaUtil.GetInflatedMethodSig(method, null)); - //MethodSig methodSig = MetaUtil.GetInflatedMethodSig(method).Clone(); - //methodSig.Params - switch (MetaUtil.GetThisArgType(method)) - { - case ThisArgType.Class: - { - methodSig.Params.Insert(0, module.CorLibTypes.Object); - break; - } - case ThisArgType.ValueType: - { - methodSig.Params.Insert(0, module.CorLibTypes.IntPtr); - break; - } - } - return MethodSig.CreateStatic(methodSig.RetType, methodSig.Params.ToArray()); - } - - public override bool Obfuscate(MethodDef callingMethod, IMethod calledMethod, bool callVir, List obfuscatedInstructions) - { - DelegateProxyAllocator allocator = _entityManager.GetEntity(callingMethod.Module); - LocalVariableAllocator localVarAllocator = new LocalVariableAllocator(callingMethod); - MethodSig methodSig = CreateProxyMethodSig(callingMethod.Module, calledMethod); - DelegateProxyMethodData proxyData = allocator.Allocate(calledMethod, callVir, methodSig); - bool isVoidReturn = MetaUtil.IsVoidType(methodSig.RetType); - - using (var varScope = localVarAllocator.CreateScope()) - { - List localVars = new List(); - if (!isVoidReturn) - { - varScope.AllocateLocal(methodSig.RetType); - } - foreach (var p in methodSig.Params) - { - localVars.Add(varScope.AllocateLocal(p)); - } - // save args - for (int i = localVars.Count - 1; i >= 0; i--) - { - obfuscatedInstructions.Add(Instruction.Create(OpCodes.Stloc, localVars[i])); - } - obfuscatedInstructions.Add(Instruction.Create(OpCodes.Ldsfld, proxyData.delegateInstanceField)); - foreach (var local in localVars) - { - obfuscatedInstructions.Add(Instruction.Create(OpCodes.Ldloc, local)); - } - obfuscatedInstructions.Add(Instruction.Create(OpCodes.Callvirt, proxyData.delegateInvokeMethod)); - } - - return true; - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/DelegateProxyObfuscator.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/DelegateProxyObfuscator.cs.meta deleted file mode 100644 index 4cb75c37..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/DelegateProxyObfuscator.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 1102cd9f03de27c4b9fde3d6a87277c7 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/DispatchProxyAllocator.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/DispatchProxyAllocator.cs deleted file mode 100644 index f4fe3bc8..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/DispatchProxyAllocator.cs +++ /dev/null @@ -1,273 +0,0 @@ -using dnlib.DotNet; -using dnlib.DotNet.Emit; -using Obfuz.Editor; -using Obfuz.Emit; -using Obfuz.Settings; -using Obfuz.Utils; -using System; -using System.Collections.Generic; -using System.Linq; -using MethodImplAttributes = dnlib.DotNet.MethodImplAttributes; -using TypeAttributes = dnlib.DotNet.TypeAttributes; - -namespace Obfuz.ObfusPasses.CallObfus -{ - - public struct ProxyCallMethodData - { - public readonly MethodDef proxyMethod; - public readonly int encryptOps; - public readonly int salt; - public readonly int encryptedIndex; - public readonly int index; - - public ProxyCallMethodData(MethodDef proxyMethod, int encryptOps, int salt, int encryptedIndex, int index) - { - this.proxyMethod = proxyMethod; - this.encryptOps = encryptOps; - this.salt = salt; - this.encryptedIndex = encryptedIndex; - this.index = index; - } - } - - class ModuleDispatchProxyAllocator : GroupByModuleEntityBase - { - private bool _done; - private CallObfuscationSettingsFacade _settings; - - - class MethodProxyInfo - { - public MethodDef proxyMethod; - - public int index; - public int encryptedOps; - public int salt; - public int encryptedIndex; - } - - private readonly Dictionary _methodProxys = new Dictionary(); - - class CallInfo - { - public string id; - public IMethod method; - public bool callVir; - } - - class DispatchMethodInfo - { - public MethodDef methodDef; - public List methods = new List(); - } - - private readonly Dictionary> _dispatchMethods = new Dictionary>(SignatureEqualityComparer.Instance); - - - private TypeDef _proxyTypeDef; - - public ModuleDispatchProxyAllocator() - { - } - - public override void Init() - { - _settings = CallObfusPass.CurrentSettings; - } - - private TypeDef CreateProxyTypeDef() - { - ModuleDef mod = Module; - using (var scope = new DisableTypeDefFindCacheScope(mod)) - { - var typeDef = new TypeDefUser($"{ConstValues.ObfuzInternalSymbolNamePrefix}ProxyCall", mod.CorLibTypes.Object.ToTypeDefOrRef()); - typeDef.Attributes = TypeAttributes.NotPublic | TypeAttributes.Sealed; - mod.Types.Add(typeDef); - return typeDef; - } - } - - private readonly HashSet _uniqueMethodNames = new HashSet(); - - - private string ToUniqueMethodName(string originalName) - { - if (_uniqueMethodNames.Add(originalName)) - { - return originalName; - } - for (int index = 1; ; index++) - { - string uniqueName = $"{originalName}${index}"; - if (_uniqueMethodNames.Add(uniqueName)) - { - return uniqueName; - } - } - } - - private string CreateDispatchMethodName(MethodSig methodSig, int index) - { - // use a stable name for the dispatch method, so that we can reuse it across different modules - // this is important for cross-module calls - return ToUniqueMethodName($"{ConstValues.ObfuzInternalSymbolNamePrefix}Dispatch_{HashUtil.ComputeHash(methodSig.Params) & 0xFFFF}_{HashUtil.ComputeHash(methodSig.RetType) & 0xFFFFFF}"); - } - - private MethodDef CreateDispatchMethodInfo(MethodSig methodSig, int index) - { - if (_proxyTypeDef == null) - { - _proxyTypeDef = CreateProxyTypeDef(); - } - MethodDef methodDef = new MethodDefUser(CreateDispatchMethodName(methodSig, index), methodSig, - MethodImplAttributes.IL | MethodImplAttributes.Managed, - MethodAttributes.Static | MethodAttributes.Public); - methodDef.DeclaringType = _proxyTypeDef; - return methodDef; - } - - private MethodSig CreateDispatchMethodSig(IMethod method) - { - ModuleDef mod = Module; - MethodSig methodSig = MetaUtil.ToSharedMethodSig(mod.CorLibTypes, MetaUtil.GetInflatedMethodSig(method, null)); - //MethodSig methodSig = MetaUtil.GetInflatedMethodSig(method).Clone(); - //methodSig.Params - switch (MetaUtil.GetThisArgType(method)) - { - case ThisArgType.Class: - { - methodSig.Params.Insert(0, mod.CorLibTypes.Object); - break; - } - case ThisArgType.ValueType: - { - methodSig.Params.Insert(0, mod.CorLibTypes.IntPtr); - break; - } - } - // extra param for index - methodSig.Params.Add(mod.CorLibTypes.Int32); - return MethodSig.CreateStatic(methodSig.RetType, methodSig.Params.ToArray()); - } - - private int GenerateSalt(IRandom random) - { - return random.NextInt(); - } - - private int GenerateEncryptOps(IRandom random) - { - return EncryptionUtil.GenerateEncryptionOpCodes(random, EncryptionScope.encryptor, _settings.obfuscationLevel); - } - - private DispatchMethodInfo GetDispatchMethod(IMethod method) - { - MethodSig methodSig = CreateDispatchMethodSig(method); - if (!_dispatchMethods.TryGetValue(methodSig, out var dispatchMethods)) - { - dispatchMethods = new List(); - _dispatchMethods.Add(methodSig, dispatchMethods); - } - if (dispatchMethods.Count == 0 || dispatchMethods.Last().methods.Count >= _settings.maxProxyMethodCountPerDispatchMethod) - { - var newDispatchMethodInfo = new DispatchMethodInfo - { - methodDef = CreateDispatchMethodInfo(methodSig, dispatchMethods.Count), - }; - dispatchMethods.Add(newDispatchMethodInfo); - } - return dispatchMethods.Last(); - } - - private IRandom CreateRandomForMethod(IMethod method, bool callVir) - { - int seed = MethodEqualityComparer.CompareDeclaringTypes.GetHashCode(method); - return EncryptionScope.localRandomCreator(seed); - } - - public ProxyCallMethodData Allocate(IMethod method, bool callVir) - { - if (_done) - { - throw new Exception("can't Allocate after done"); - } - var key = new MethodKey(method, callVir); - if (!_methodProxys.TryGetValue(key, out var proxyInfo)) - { - var methodDispatcher = GetDispatchMethod(method); - - int index = methodDispatcher.methods.Count; - IRandom localRandom = CreateRandomForMethod(method, callVir); - int encryptOps = GenerateEncryptOps(localRandom); - int salt = GenerateSalt(localRandom); - int encryptedIndex = EncryptionScope.encryptor.Encrypt(index, encryptOps, salt); - proxyInfo = new MethodProxyInfo() - { - proxyMethod = methodDispatcher.methodDef, - index = index, - encryptedOps = encryptOps, - salt = salt, - encryptedIndex = encryptedIndex, - }; - methodDispatcher.methods.Add(new CallInfo { id = $"{method}{(callVir ? "" : "v")}", method = method, callVir = callVir }); - _methodProxys.Add(key, proxyInfo); - } - return new ProxyCallMethodData(proxyInfo.proxyMethod, proxyInfo.encryptedOps, proxyInfo.salt, proxyInfo.encryptedIndex, proxyInfo.index); - } - - public override void Done() - { - if (_done) - { - throw new Exception("Already done"); - } - _done = true; - if (_proxyTypeDef == null) - { - return; - } - - // for stable order, we sort methods by name - var methodWithNamePairList = _proxyTypeDef.Methods.Select(m => (m, m.ToString())).ToList(); - methodWithNamePairList.Sort((a, b) => a.Item2.CompareTo(b.Item2)); - _proxyTypeDef.Methods.Clear(); - foreach (var methodPair in methodWithNamePairList) - { - methodPair.Item1.DeclaringType = _proxyTypeDef; - } - - foreach (DispatchMethodInfo dispatchMethod in _dispatchMethods.Values.SelectMany(ms => ms)) - { - var methodDef = dispatchMethod.methodDef; - var methodSig = methodDef.MethodSig; - - - var body = new CilBody(); - methodDef.Body = body; - var ins = body.Instructions; - - foreach (Parameter param in methodDef.Parameters) - { - ins.Add(Instruction.Create(OpCodes.Ldarg, param)); - } - - var switchCases = new List(); - var switchInst = Instruction.Create(OpCodes.Switch, switchCases); - ins.Add(switchInst); - var ret = Instruction.Create(OpCodes.Ret); - - // sort methods by signature to ensure stable order - //dispatchMethod.methods.Sort((a, b) => a.id.CompareTo(b.id)); - foreach (CallInfo ci in dispatchMethod.methods) - { - var callTargetMethod = Instruction.Create(ci.callVir ? OpCodes.Callvirt : OpCodes.Call, ci.method); - switchCases.Add(callTargetMethod); - ins.Add(callTargetMethod); - ins.Add(Instruction.Create(OpCodes.Br, ret)); - } - ins.Add(ret); - } - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/DispatchProxyAllocator.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/DispatchProxyAllocator.cs.meta deleted file mode 100644 index a6a06f88..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/DispatchProxyAllocator.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 16b960455f093854d927c2dbd47a4826 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/DispatchProxyObfuscator.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/DispatchProxyObfuscator.cs deleted file mode 100644 index bc54a774..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/DispatchProxyObfuscator.cs +++ /dev/null @@ -1,53 +0,0 @@ -using dnlib.DotNet; -using dnlib.DotNet.Emit; -using Obfuz.Data; -using Obfuz.Emit; -using Obfuz.Settings; -using Obfuz.Utils; -using System.Collections.Generic; - -namespace Obfuz.ObfusPasses.CallObfus -{ - - public class DispatchProxyObfuscator : ObfuscatorBase - { - private readonly GroupByModuleEntityManager _moduleEntityManager; - - public DispatchProxyObfuscator(GroupByModuleEntityManager moduleEntityManager) - { - _moduleEntityManager = moduleEntityManager; - } - - public override void Done() - { - _moduleEntityManager.Done(); - } - - public override bool Obfuscate(MethodDef callerMethod, IMethod calledMethod, bool callVir, List obfuscatedInstructions) - { - ModuleDispatchProxyAllocator proxyCallAllocator = _moduleEntityManager.GetEntity(callerMethod.Module); - MethodSig sharedMethodSig = MetaUtil.ToSharedMethodSig(calledMethod.Module.CorLibTypes, MetaUtil.GetInflatedMethodSig(calledMethod, null)); - ProxyCallMethodData proxyCallMethodData = proxyCallAllocator.Allocate(calledMethod, callVir); - DefaultMetadataImporter importer = proxyCallAllocator.GetDefaultModuleMetadataImporter(); - - //if (needCacheCall) - //{ - // FieldDef cacheField = _constFieldAllocator.Allocate(callerMethod.Module, proxyCallMethodData.index); - // obfuscatedInstructions.Add(Instruction.Create(OpCodes.Ldsfld, cacheField)); - //} - //else - //{ - // obfuscatedInstructions.Add(Instruction.CreateLdcI4(proxyCallMethodData.encryptedIndex)); - // obfuscatedInstructions.Add(Instruction.CreateLdcI4(proxyCallMethodData.encryptOps)); - // obfuscatedInstructions.Add(Instruction.CreateLdcI4(proxyCallMethodData.salt)); - // obfuscatedInstructions.Add(Instruction.Create(OpCodes.Call, importer.DecryptInt)); - //} - - ConstFieldAllocator constFieldAllocator = proxyCallAllocator.GetEntity(); - FieldDef cacheField = constFieldAllocator.Allocate(proxyCallMethodData.index); - obfuscatedInstructions.Add(Instruction.Create(OpCodes.Ldsfld, cacheField)); - obfuscatedInstructions.Add(Instruction.Create(OpCodes.Call, proxyCallMethodData.proxyMethod)); - return true; - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/DispatchProxyObfuscator.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/DispatchProxyObfuscator.cs.meta deleted file mode 100644 index 78ae2a27..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/DispatchProxyObfuscator.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: e13ba01b03439e049af0e09367825cde -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/IObfuscationPolicy.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/IObfuscationPolicy.cs deleted file mode 100644 index 941291ba..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/IObfuscationPolicy.cs +++ /dev/null @@ -1,19 +0,0 @@ -using dnlib.DotNet; - -namespace Obfuz.ObfusPasses.CallObfus -{ - - public interface IObfuscationPolicy - { - bool NeedObfuscateCallInMethod(MethodDef method); - - bool NeedObfuscateCalledMethod(MethodDef callerMethod, IMethod calledMethod, bool callVir); - } - - public abstract class ObfuscationPolicyBase : IObfuscationPolicy - { - public abstract bool NeedObfuscateCallInMethod(MethodDef method); - - public abstract bool NeedObfuscateCalledMethod(MethodDef callerMethod, IMethod calledMethod, bool callVir); - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/IObfuscationPolicy.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/IObfuscationPolicy.cs.meta deleted file mode 100644 index 96009d14..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/IObfuscationPolicy.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 6af3cd881fdefd14d9a55b77088dd5a4 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/IObfuscator.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/IObfuscator.cs deleted file mode 100644 index bd26274e..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/IObfuscator.cs +++ /dev/null @@ -1,20 +0,0 @@ -using dnlib.DotNet; -using dnlib.DotNet.Emit; -using System.Collections.Generic; - -namespace Obfuz.ObfusPasses.CallObfus -{ - public interface IObfuscator - { - bool Obfuscate(MethodDef callingMethod, IMethod calledMethod, bool callVir, List obfuscatedInstructions); - - void Done(); - } - - public abstract class ObfuscatorBase : IObfuscator - { - public abstract bool Obfuscate(MethodDef callingMethod, IMethod calledMethod, bool callVir, List obfuscatedInstructions); - - public abstract void Done(); - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/IObfuscator.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/IObfuscator.cs.meta deleted file mode 100644 index c75fd401..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/IObfuscator.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 4156317478f8b1d438ef6d5a280d409f -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/MethodKey.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/MethodKey.cs deleted file mode 100644 index 99275581..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/MethodKey.cs +++ /dev/null @@ -1,30 +0,0 @@ -using dnlib.DotNet; -using Obfuz.Utils; -using System; - -namespace Obfuz.ObfusPasses.CallObfus -{ - class MethodKey : IEquatable - { - public readonly IMethod _method; - public readonly bool _callVir; - private readonly int _hashCode; - - public MethodKey(IMethod method, bool callVir) - { - _method = method; - _callVir = callVir; - _hashCode = HashUtil.CombineHash(MethodEqualityComparer.CompareDeclaringTypes.GetHashCode(method), callVir ? 1 : 0); - } - - public override int GetHashCode() - { - return _hashCode; - } - - public bool Equals(MethodKey other) - { - return MethodEqualityComparer.CompareDeclaringTypes.Equals(_method, other._method) && _callVir == other._callVir; - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/MethodKey.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/MethodKey.cs.meta deleted file mode 100644 index f7a1a2a8..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/MethodKey.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 1193647b317b56f4b83aa080d0a17f7a -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/SpecialWhiteListMethodCalculator.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/SpecialWhiteListMethodCalculator.cs deleted file mode 100644 index 5f52792b..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/SpecialWhiteListMethodCalculator.cs +++ /dev/null @@ -1,122 +0,0 @@ -using dnlib.DotNet; -using Obfuz.Utils; -using System.Collections.Generic; - -namespace Obfuz.ObfusPasses.CallObfus -{ - class SpecialWhiteListMethodCalculator - { - private readonly bool _obfuscateCallToMethodInMscorlib; - private readonly CachedDictionary _specialWhiteListMethodCache; - - public SpecialWhiteListMethodCalculator(bool obfuscateCallToMethodInMscorlib) - { - _obfuscateCallToMethodInMscorlib = obfuscateCallToMethodInMscorlib; - _specialWhiteListMethodCache = new CachedDictionary(MethodEqualityComparer.CompareDeclaringTypes, this.ComputeIsInWhiteList); - } - - public bool IsInWhiteList(IMethod calledMethod) - { - return _specialWhiteListMethodCache.GetValue(calledMethod); - } - - private static readonly HashSet _specialTypeFullNames = new HashSet - { - "System.Enum", - "System.Delegate", - "System.MulticastDelegate", - "Obfuz.EncryptionService`1", - }; - - private static readonly HashSet _specialMethodNames = new HashSet - { - "GetEnumerator", // List.Enumerator.GetEnumerator() - ".ctor", // constructor - }; - - private static readonly HashSet _specialMethodFullNames = new HashSet - { - "System.Reflection.MethodBase.GetCurrentMethod", - "System.Reflection.Assembly.GetCallingAssembly", - "System.Reflection.Assembly.GetExecutingAssembly", - "System.Reflection.Assembly.GetEntryAssembly", - }; - - private bool ComputeIsInWhiteList(IMethod calledMethod) - { - MethodDef calledMethodDef = calledMethod.ResolveMethodDef(); - // mono has more strict access control, calls non-public method will raise exception. - if (PlatformUtil.IsMonoBackend()) - { - if (calledMethodDef != null && (!calledMethodDef.IsPublic || !IsTypeSelfAndParentPublic(calledMethodDef.DeclaringType))) - { - return true; - } - } - - ITypeDefOrRef declaringType = calledMethod.DeclaringType; - TypeSig declaringTypeSig = calledMethod.DeclaringType.ToTypeSig(); - declaringTypeSig = declaringTypeSig.RemovePinnedAndModifiers(); - switch (declaringTypeSig.ElementType) - { - case ElementType.ValueType: - case ElementType.Class: - { - break; - } - case ElementType.GenericInst: - { - if (MetaUtil.ContainsContainsGenericParameter(calledMethod)) - { - return true; - } - break; - } - default: return true; - } - - TypeDef typeDef = declaringType.ResolveTypeDef(); - - if (!_obfuscateCallToMethodInMscorlib && typeDef.Module.IsCoreLibraryModule == true) - { - return true; - } - - if (typeDef.IsDelegate || typeDef.IsEnum) - return true; - - string fullName = typeDef.FullName; - if (_specialTypeFullNames.Contains(fullName)) - { - return true; - } - //if (fullName.StartsWith("System.Runtime.CompilerServices.")) - //{ - // return true; - //} - - string methodName = calledMethod.Name; - if (_specialMethodNames.Contains(methodName)) - { - return true; - } - - string methodFullName = $"{fullName}.{methodName}"; - if (_specialMethodFullNames.Contains(methodFullName)) - { - return true; - } - return false; - } - - private bool IsTypeSelfAndParentPublic(TypeDef type) - { - if (type.DeclaringType != null && !IsTypeSelfAndParentPublic(type.DeclaringType)) - { - return false; - } - - return type.IsPublic; - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/SpecialWhiteListMethodCalculator.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/SpecialWhiteListMethodCalculator.cs.meta deleted file mode 100644 index b1228ec4..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CallObfus/SpecialWhiteListMethodCalculator.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 904e80c4b98911c40b6a9173ca24f3ee -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CleanUp.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CleanUp.meta deleted file mode 100644 index 37096d79..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CleanUp.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 2764442d8fc2b914dbc39dcfa2699698 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CleanUp/CleanUpInstructionPass.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CleanUp/CleanUpInstructionPass.cs deleted file mode 100644 index c95854d0..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CleanUp/CleanUpInstructionPass.cs +++ /dev/null @@ -1,41 +0,0 @@ -using dnlib.DotNet; -using dnlib.DotNet.Emit; - -namespace Obfuz.ObfusPasses.CleanUp -{ - public class CleanUpInstructionPass : ObfuscationPassBase - { - public override ObfuscationPassType Type => ObfuscationPassType.None; - - public override void Start() - { - } - - public override void Stop() - { - - } - - public override void Process() - { - var ctx = ObfuscationPassContext.Current; - foreach (ModuleDef mod in ctx.modulesToObfuscate) - { - foreach (TypeDef type in mod.GetTypes()) - { - foreach (MethodDef method in type.Methods) - { - if (method.HasBody) - { - CilBody body = method.Body; - body.SimplifyBranches(); - body.OptimizeMacros(); - body.OptimizeBranches(); - // TODO remove dup - } - } - } - } - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CleanUp/CleanUpInstructionPass.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CleanUp/CleanUpInstructionPass.cs.meta deleted file mode 100644 index cc974323..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CleanUp/CleanUpInstructionPass.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 78cc056cd929d70409a0f0737b571a6d -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CleanUp/RemoveObfuzAttributesPass.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CleanUp/RemoveObfuzAttributesPass.cs deleted file mode 100644 index 6b1ac2bb..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CleanUp/RemoveObfuzAttributesPass.cs +++ /dev/null @@ -1,67 +0,0 @@ -using dnlib.DotNet; -using Obfuz.Editor; -using System.Collections.Generic; - -namespace Obfuz.ObfusPasses.CleanUp -{ - public class RemoveObfuzAttributesPass : ObfuscationPassBase - { - public override ObfuscationPassType Type => ObfuscationPassType.None; - - public override void Start() - { - } - - public override void Stop() - { - - } - - - private void RemoveObfuzAttributes(IHasCustomAttribute provider) - { - CustomAttributeCollection customAttributes = provider.CustomAttributes; - if (customAttributes.Count == 0) - return; - var toRemove = new List(); - customAttributes.RemoveAll(ConstValues.ObfuzIgnoreAttributeFullName); - customAttributes.RemoveAll(ConstValues.EncryptFieldAttributeFullName); - } - - public override void Process() - { - var ctx = ObfuscationPassContext.Current; - foreach (ModuleDef mod in ctx.modulesToObfuscate) - { - RemoveObfuzAttributes(mod); - foreach (TypeDef type in mod.GetTypes()) - { - RemoveObfuzAttributes(type); - foreach (FieldDef field in type.Fields) - { - RemoveObfuzAttributes(field); - } - foreach (MethodDef method in type.Methods) - { - RemoveObfuzAttributes(method); - foreach (Parameter param in method.Parameters) - { - if (param.ParamDef != null) - { - RemoveObfuzAttributes(param.ParamDef); - } - } - } - foreach (PropertyDef property in type.Properties) - { - RemoveObfuzAttributes(property); - } - foreach (EventDef eventDef in type.Events) - { - RemoveObfuzAttributes(eventDef); - } - } - } - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CleanUp/RemoveObfuzAttributesPass.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CleanUp/RemoveObfuzAttributesPass.cs.meta deleted file mode 100644 index ff6039ec..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/CleanUp/RemoveObfuzAttributesPass.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 6b475010a7656a0439ca8664a3d2dbc0 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ConstEncrypt.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ConstEncrypt.meta deleted file mode 100644 index 1fdfee0b..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ConstEncrypt.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 18104d0c3c665ea489e566eec67f2aea -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ConstEncrypt/ConfigurableEncryptPolicy.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ConstEncrypt/ConfigurableEncryptPolicy.cs deleted file mode 100644 index 2b775b56..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ConstEncrypt/ConfigurableEncryptPolicy.cs +++ /dev/null @@ -1,490 +0,0 @@ -using dnlib.DotNet; -using Obfuz.Conf; -using Obfuz.Utils; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Xml; - -namespace Obfuz.ObfusPasses.ConstEncrypt -{ - - public class ConfigurableEncryptPolicy : EncryptPolicyBase - { - class ObfuscationRule : IRule - { - public bool? disableEncrypt; - public bool? encryptInt; - public bool? encryptLong; - public bool? encryptFloat; - public bool? encryptDouble; - public bool? encryptArray; - public bool? encryptString; - - public bool? encryptConstInLoop; - public bool? encryptStringInLoop; - - public bool? cacheConstInLoop; - public bool? cacheConstNotInLoop; - public bool? cacheStringInLoop; - public bool? cacheStringNotInLoop; - - public void InheritParent(ObfuscationRule parentRule) - { - if (disableEncrypt == null) - disableEncrypt = parentRule.disableEncrypt; - if (encryptInt == null) - encryptInt = parentRule.encryptInt; - if (encryptLong == null) - encryptLong = parentRule.encryptLong; - if (encryptFloat == null) - encryptFloat = parentRule.encryptFloat; - if (encryptDouble == null) - encryptDouble = parentRule.encryptDouble; - if (encryptArray == null) - encryptArray = parentRule.encryptArray; - if (encryptString == null) - encryptString = parentRule.encryptString; - - if (encryptConstInLoop == null) - encryptConstInLoop = parentRule.encryptConstInLoop; - if (encryptStringInLoop == null) - encryptStringInLoop = parentRule.encryptStringInLoop; - - if (cacheConstInLoop == null) - cacheConstInLoop = parentRule.cacheConstInLoop; - if (cacheConstNotInLoop == null) - cacheConstNotInLoop = parentRule.cacheConstNotInLoop; - if (cacheStringInLoop == null) - cacheStringInLoop = parentRule.cacheStringInLoop; - if (cacheStringNotInLoop == null) - cacheStringNotInLoop = parentRule.cacheStringNotInLoop; - } - } - - class MethodSpec : MethodRuleBase - { - } - - class TypeSpec : TypeRuleBase - { - } - - class AssemblySpec : AssemblyRuleBase - { - } - - private static readonly ObfuscationRule s_default = new ObfuscationRule() - { - disableEncrypt = false, - encryptInt = true, - encryptLong = true, - encryptFloat = true, - encryptDouble = true, - encryptArray = true, - encryptString = true, - encryptConstInLoop = true, - encryptStringInLoop = true, - cacheConstInLoop = true, - cacheConstNotInLoop = false, - cacheStringInLoop = true, - cacheStringNotInLoop = true, - }; - - private ObfuscationRule _global; - - public HashSet notEncryptInts = new HashSet(); - public HashSet notEncryptLongs = new HashSet(); - public HashSet notEncryptStrings = new HashSet(); - public List> notEncryptIntRanges = new List>(); - public List> notEncryptLongRanges = new List>(); - public List> notEncryptFloatRanges = new List>(); - public List> notEncryptDoubleRanges = new List>(); - public List> notEncryptArrayLengthRanges = new List>(); - public List> notEncryptStringLengthRanges = new List>(); - - private readonly XmlAssemblyTypeMethodRuleParser _xmlParser; - - private readonly Dictionary _assemblySpecs = new Dictionary(); - private readonly Dictionary _methodRuleCache = new Dictionary(); - - public ConfigurableEncryptPolicy(List toObfuscatedAssemblyNames, List xmlConfigFiles) - { - _xmlParser = new XmlAssemblyTypeMethodRuleParser( - toObfuscatedAssemblyNames, ParseObfuscationRule, ParseGlobalElement); - LoadConfigs(xmlConfigFiles); - } - - private void LoadConfigs(List configFiles) - { - _xmlParser.LoadConfigs(configFiles); - if (_global == null) - { - _global = s_default; - } - else - { - _global.InheritParent(s_default); - } - _xmlParser.InheritParentRules(_global); - } - - private void ParseGlobalElement(string configFile, XmlElement ele) - { - switch (ele.Name) - { - case "global": _global = ParseObfuscationRule(configFile, ele); break; - case "whitelist": ParseWhitelist(configFile, ele); break; - default: throw new Exception($"Invalid xml file {configFile}, unknown node {ele.Name}"); - } - } - - private ObfuscationRule ParseObfuscationRule(string configFile, XmlElement ele) - { - var rule = new ObfuscationRule(); - if (ele.HasAttribute("disableEncrypt")) - { - rule.disableEncrypt = ConfigUtil.ParseBool(ele.GetAttribute("disableEncrypt")); - } - if (ele.HasAttribute("encryptInt")) - { - rule.encryptInt = ConfigUtil.ParseBool(ele.GetAttribute("encryptInt")); - } - if (ele.HasAttribute("encryptLong")) - { - rule.encryptLong = ConfigUtil.ParseBool(ele.GetAttribute("encryptLong")); - } - if (ele.HasAttribute("encryptFloat")) - { - rule.encryptFloat = ConfigUtil.ParseBool(ele.GetAttribute("encryptFloat")); - } - if (ele.HasAttribute("encryptDouble")) - { - rule.encryptDouble = ConfigUtil.ParseBool(ele.GetAttribute("encryptDouble")); - } - if (ele.HasAttribute("encryptBytes")) - { - rule.encryptArray = ConfigUtil.ParseBool(ele.GetAttribute("encryptArray")); - } - if (ele.HasAttribute("encryptString")) - { - rule.encryptString = ConfigUtil.ParseBool(ele.GetAttribute("encryptString")); - } - - if (ele.HasAttribute("encryptConstInLoop")) - { - rule.encryptConstInLoop = ConfigUtil.ParseBool(ele.GetAttribute("encryptConstInLoop")); - } - if (ele.HasAttribute("encryptStringInLoop")) - { - rule.encryptStringInLoop = ConfigUtil.ParseBool(ele.GetAttribute("encryptStringInLoop")); - } - if (ele.HasAttribute("cacheConstInLoop")) - { - rule.cacheConstInLoop = ConfigUtil.ParseBool(ele.GetAttribute("cacheConstInLoop")); - } - if (ele.HasAttribute("cacheConstNotInLoop")) - { - rule.cacheConstNotInLoop = ConfigUtil.ParseBool(ele.GetAttribute("cacheConstNotInLoop")); - } - if (ele.HasAttribute("cacheStringInLoop")) - { - rule.cacheStringInLoop = ConfigUtil.ParseBool(ele.GetAttribute("cacheStringInLoop")); - } - if (ele.HasAttribute("cacheStringNotInLoop")) - { - rule.cacheStringNotInLoop = ConfigUtil.ParseBool(ele.GetAttribute("cacheStringNotInLoop")); - } - return rule; - } - - private void ParseWhitelist(string configFile, XmlElement childEle) - { - string type = childEle.GetAttribute("type"); - if (string.IsNullOrEmpty(type)) - { - throw new Exception($"Invalid xml file, whitelist type is empty"); - } - string value = childEle.InnerText; - switch (type) - { - case "int": - { - notEncryptInts.AddRange(value.Split(',').Select(s => int.Parse(s.Trim()))); - break; - } - case "long": - { - notEncryptLongs.AddRange(value.Split(',').Select(s => long.Parse(s.Trim()))); - break; - } - case "string": - { - notEncryptStrings.AddRange(value.Split(',').Select(s => s.Trim())); - break; - } - case "int-range": - { - var parts = value.Split(','); - if (parts.Length != 2) - { - throw new Exception($"Invalid xml file, int-range {value} is invalid"); - } - notEncryptIntRanges.Add(new NumberRange(ConfigUtil.ParseNullableInt(parts[0]), ConfigUtil.ParseNullableInt(parts[1]))); - break; - } - case "long-range": - { - var parts = value.Split(','); - if (parts.Length != 2) - { - throw new Exception($"Invalid xml file, long-range {value} is invalid"); - } - notEncryptLongRanges.Add(new NumberRange(ConfigUtil.ParseNullableLong(parts[0]), ConfigUtil.ParseNullableLong(parts[1]))); - break; - } - case "float-range": - { - var parts = value.Split(','); - if (parts.Length != 2) - { - throw new Exception($"Invalid xml file, float-range {value} is invalid"); - } - notEncryptFloatRanges.Add(new NumberRange(ConfigUtil.ParseNullableFloat(parts[0]), ConfigUtil.ParseNullableFloat(parts[1]))); - break; - } - case "double-range": - { - var parts = value.Split(','); - if (parts.Length != 2) - { - throw new Exception($"Invalid xml file, double-range {value} is invalid"); - } - notEncryptDoubleRanges.Add(new NumberRange(ConfigUtil.ParseNullableDouble(parts[0]), ConfigUtil.ParseNullableDouble(parts[1]))); - break; - } - case "string-length-range": - { - var parts = value.Split(','); - if (parts.Length != 2) - { - throw new Exception($"Invalid xml file, string-length-range {value} is invalid"); - } - notEncryptStringLengthRanges.Add(new NumberRange(ConfigUtil.ParseNullableInt(parts[0]), ConfigUtil.ParseNullableInt(parts[1]))); - break; - } - case "array-length-range": - { - var parts = value.Split(','); - if (parts.Length != 2) - { - throw new Exception($"Invalid xml file, array-length-range {value} is invalid"); - } - notEncryptArrayLengthRanges.Add(new NumberRange(ConfigUtil.ParseNullableInt(parts[0]), ConfigUtil.ParseNullableInt(parts[1]))); - break; - } - default: throw new Exception($"Invalid xml file, unknown whitelist type {type} in {childEle.Name} node"); - } - } - - private ObfuscationRule GetMethodObfuscationRule(MethodDef method) - { - if (!_methodRuleCache.TryGetValue(method, out var rule)) - { - rule = _xmlParser.GetMethodRule(method, _global); - _methodRuleCache[method] = rule; - } - return rule; - } - - public override bool NeedObfuscateMethod(MethodDef method) - { - ObfuscationRule rule = GetMethodObfuscationRule(method); - return rule.disableEncrypt != true; - } - - public override ConstCachePolicy GetMethodConstCachePolicy(MethodDef method) - { - ObfuscationRule rule = GetMethodObfuscationRule(method); - return new ConstCachePolicy - { - cacheConstInLoop = rule.cacheConstInLoop.Value, - cacheConstNotInLoop = rule.cacheConstNotInLoop.Value, - cacheStringInLoop = rule.cacheStringInLoop.Value, - cacheStringNotInLoop = rule.cacheStringNotInLoop.Value, - }; - } - - public override bool NeedObfuscateInt(MethodDef method, bool currentInLoop, int value) - { - ObfuscationRule rule = GetMethodObfuscationRule(method); - if (rule.encryptInt == false) - { - return false; - } - if (currentInLoop && rule.encryptConstInLoop == false) - { - return false; - } - if (notEncryptInts.Contains(value)) - { - return false; - } - foreach (var range in notEncryptIntRanges) - { - if (range.min != null && value < range.min) - { - continue; - } - if (range.max != null && value > range.max) - { - continue; - } - return false; - } - return true; - } - - public override bool NeedObfuscateLong(MethodDef method, bool currentInLoop, long value) - { - ObfuscationRule rule = GetMethodObfuscationRule(method); - if (rule.encryptLong == false) - { - return false; - } - if (currentInLoop && rule.encryptConstInLoop == false) - { - return false; - } - if (notEncryptLongs.Contains(value)) - { - return false; - } - foreach (var range in notEncryptLongRanges) - { - if (range.min != null && value < range.min) - { - continue; - } - if (range.max != null && value > range.max) - { - continue; - } - return false; - } - return true; - } - - public override bool NeedObfuscateFloat(MethodDef method, bool currentInLoop, float value) - { - ObfuscationRule rule = GetMethodObfuscationRule(method); - if (rule.encryptFloat == false) - { - return false; - } - if (currentInLoop && rule.encryptConstInLoop == false) - { - return false; - } - foreach (var range in notEncryptFloatRanges) - { - if (range.min != null && value < range.min) - { - continue; - } - if (range.max != null && value > range.max) - { - continue; - } - return false; - } - return true; - } - - public override bool NeedObfuscateDouble(MethodDef method, bool currentInLoop, double value) - { - ObfuscationRule rule = GetMethodObfuscationRule(method); - if (rule.encryptDouble == false) - { - return false; - } - if (currentInLoop && rule.encryptConstInLoop == false) - { - return false; - } - foreach (var range in notEncryptDoubleRanges) - { - if (range.min != null && value < range.min) - { - continue; - } - if (range.max != null && value > range.max) - { - continue; - } - return false; - } - return true; - } - - public override bool NeedObfuscateString(MethodDef method, bool currentInLoop, string value) - { - if (string.IsNullOrEmpty(value)) - { - return false; - } - ObfuscationRule rule = GetMethodObfuscationRule(method); - if (rule.encryptString == false) - { - return false; - } - if (currentInLoop && rule.encryptConstInLoop == false) - { - return false; - } - if (notEncryptStrings.Contains(value)) - { - return false; - } - foreach (var range in notEncryptStringLengthRanges) - { - if (range.min != null && value.Length < range.min) - { - continue; - } - if (range.max != null && value.Length > range.max) - { - continue; - } - return false; - } - return true; - } - - public override bool NeedObfuscateArray(MethodDef method, bool currentInLoop, byte[] array) - { - ObfuscationRule rule = GetMethodObfuscationRule(method); - if (rule.encryptArray == false) - { - return false; - } - if (currentInLoop && rule.encryptConstInLoop == false) - { - return false; - } - foreach (var range in notEncryptArrayLengthRanges) - { - if (range.min != null && array.Length < range.min) - { - continue; - } - if (range.max != null && array.Length > range.max) - { - continue; - } - return false; - } - return true; - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ConstEncrypt/ConfigurableEncryptPolicy.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ConstEncrypt/ConfigurableEncryptPolicy.cs.meta deleted file mode 100644 index 73c07be9..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ConstEncrypt/ConfigurableEncryptPolicy.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: da25453bc1fda394097c052af7733260 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ConstEncrypt/ConstEncryptPass.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ConstEncrypt/ConstEncryptPass.cs deleted file mode 100644 index 896e08a7..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ConstEncrypt/ConstEncryptPass.cs +++ /dev/null @@ -1,137 +0,0 @@ -using dnlib.DotNet; -using dnlib.DotNet.Emit; -using Obfuz.Emit; -using Obfuz.Settings; -using System.Collections.Generic; - -namespace Obfuz.ObfusPasses.ConstEncrypt -{ - - public class ConstEncryptPass : BasicBlockObfuscationPassBase - { - private readonly ConstEncryptionSettingsFacade _settings; - private IEncryptPolicy _dataObfuscatorPolicy; - private IConstEncryptor _dataObfuscator; - public override ObfuscationPassType Type => ObfuscationPassType.ConstEncrypt; - - public ConstEncryptPass(ConstEncryptionSettingsFacade settings) - { - _settings = settings; - } - - public override void Start() - { - var ctx = ObfuscationPassContext.Current; - _dataObfuscatorPolicy = new ConfigurableEncryptPolicy(ctx.coreSettings.assembliesToObfuscate, _settings.ruleFiles); - _dataObfuscator = new DefaultConstEncryptor(ctx.moduleEntityManager, _settings); - } - - public override void Stop() - { - - } - - protected override bool NeedObfuscateMethod(MethodDef method) - { - return _dataObfuscatorPolicy.NeedObfuscateMethod(method); - } - - protected override bool TryObfuscateInstruction(MethodDef method, Instruction inst, BasicBlock block, int instructionIndex, IList globalInstructions, - List outputInstructions, List totalFinalInstructions) - { - bool currentInLoop = block.inLoop; - ConstCachePolicy constCachePolicy = _dataObfuscatorPolicy.GetMethodConstCachePolicy(method); - bool needCache = currentInLoop ? constCachePolicy.cacheConstInLoop : constCachePolicy.cacheConstNotInLoop; - switch (inst.OpCode.Code) - { - case Code.Ldc_I4: - case Code.Ldc_I4_S: - case Code.Ldc_I4_0: - case Code.Ldc_I4_1: - case Code.Ldc_I4_2: - case Code.Ldc_I4_3: - case Code.Ldc_I4_4: - case Code.Ldc_I4_5: - case Code.Ldc_I4_6: - case Code.Ldc_I4_7: - case Code.Ldc_I4_8: - case Code.Ldc_I4_M1: - { - int value = inst.GetLdcI4Value(); - if (_dataObfuscatorPolicy.NeedObfuscateInt(method, currentInLoop, value)) - { - _dataObfuscator.ObfuscateInt(method, needCache, value, outputInstructions); - return true; - } - return false; - } - case Code.Ldc_I8: - { - long value = (long)inst.Operand; - if (_dataObfuscatorPolicy.NeedObfuscateLong(method, currentInLoop, value)) - { - _dataObfuscator.ObfuscateLong(method, needCache, value, outputInstructions); - return true; - } - return false; - } - case Code.Ldc_R4: - { - float value = (float)inst.Operand; - if (_dataObfuscatorPolicy.NeedObfuscateFloat(method, currentInLoop, value)) - { - _dataObfuscator.ObfuscateFloat(method, needCache, value, outputInstructions); - return true; - } - return false; - } - case Code.Ldc_R8: - { - double value = (double)inst.Operand; - if (_dataObfuscatorPolicy.NeedObfuscateDouble(method, currentInLoop, value)) - { - _dataObfuscator.ObfuscateDouble(method, needCache, value, outputInstructions); - return true; - } - return false; - } - case Code.Ldstr: - { - string value = (string)inst.Operand; - if (_dataObfuscatorPolicy.NeedObfuscateString(method, currentInLoop, value)) - { - _dataObfuscator.ObfuscateString(method, needCache, value, outputInstructions); - return true; - } - return false; - } - case Code.Call: - { - if (((IMethod)inst.Operand).FullName == "System.Void System.Runtime.CompilerServices.RuntimeHelpers::InitializeArray(System.Array,System.RuntimeFieldHandle)") - { - Instruction prevInst = globalInstructions[instructionIndex - 1]; - if (prevInst.OpCode.Code == Code.Ldtoken) - { - IField rvaField = (IField)prevInst.Operand; - FieldDef ravFieldDef = rvaField.ResolveFieldDefThrow(); - if (ravFieldDef.Module != method.Module) - { - return false; - } - byte[] data = ravFieldDef.InitialValue; - if (data != null && data.Length > 0 && _dataObfuscatorPolicy.NeedObfuscateArray(method, currentInLoop, data)) - { - // don't need cache for byte array obfuscation - needCache = false; - _dataObfuscator.ObfuscateBytes(method, needCache, ravFieldDef, data, outputInstructions); - return true; - } - } - } - return false; - } - default: return false; - } - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ConstEncrypt/ConstEncryptPass.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ConstEncrypt/ConstEncryptPass.cs.meta deleted file mode 100644 index da7fdfbf..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ConstEncrypt/ConstEncryptPass.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: aa0e9191126d4e24c92546b6af2c52cf -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ConstEncrypt/DefaultConstEncryptor.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ConstEncrypt/DefaultConstEncryptor.cs deleted file mode 100644 index 24b3cb93..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ConstEncrypt/DefaultConstEncryptor.cs +++ /dev/null @@ -1,337 +0,0 @@ -using dnlib.DotNet; -using dnlib.DotNet.Emit; -using Obfuz.Data; -using Obfuz.Emit; -using Obfuz.Settings; -using Obfuz.Utils; -using System.Collections.Generic; -using System.Text; -using UnityEngine.Assertions; - -namespace Obfuz.ObfusPasses.ConstEncrypt -{ - public class DefaultConstEncryptor : IConstEncryptor - { - private readonly GroupByModuleEntityManager _moduleEntityManager; - private readonly ConstEncryptionSettingsFacade _settings; - - public DefaultConstEncryptor(GroupByModuleEntityManager moduleEntityManager, ConstEncryptionSettingsFacade settings) - { - _moduleEntityManager = moduleEntityManager; - _settings = settings; - } - - private IRandom CreateRandomForValue(EncryptionScopeInfo encryptionScope, int value) - { - return encryptionScope.localRandomCreator(value); - } - - private int GenerateEncryptionOperations(EncryptionScopeInfo encryptionScope, IRandom random) - { - return EncryptionUtil.GenerateEncryptionOpCodes(random, encryptionScope.encryptor, _settings.encryptionLevel); - } - - public int GenerateSalt(IRandom random) - { - return random.NextInt(); - } - - private DefaultMetadataImporter GetModuleMetadataImporter(MethodDef method) - { - return _moduleEntityManager.GetEntity(method.Module); - } - - public void ObfuscateInt(MethodDef method, bool needCacheValue, int value, List obfuscatedInstructions) - { - EncryptionScopeInfo encryptionScope = _moduleEntityManager.EncryptionScopeProvider.GetScope(method.Module); - IRandom random = CreateRandomForValue(encryptionScope, value.GetHashCode()); - ConstFieldAllocator constFieldAllocator = _moduleEntityManager.GetEntity(method.Module); - RvaDataAllocator rvaDataAllocator = _moduleEntityManager.GetEntity(method.Module); - DefaultMetadataImporter importer = GetModuleMetadataImporter(method); - - switch (random.NextInt(5)) - { - case 0: - { - // = c = encrypted static field - FieldDef cacheField = constFieldAllocator.Allocate(value); - obfuscatedInstructions.Add(Instruction.Create(OpCodes.Ldsfld, cacheField)); - break; - } - case 1: - { - // c = a + b - int a = random.NextInt(); - int b = value - a; - float constProbability = 0.5f; - ConstObfusUtil.LoadConstTwoInt(a, b, random, constProbability, constFieldAllocator, obfuscatedInstructions); - obfuscatedInstructions.Add(Instruction.Create(OpCodes.Add)); - break; - } - case 2: - { - // c = a * b - int a = random.NextInt() | 0x1; - int ra = MathUtil.ModInverse32(a); - int b = ra * value; - float constProbability = 0.5f; - ConstObfusUtil.LoadConstTwoInt(a, b, random, constProbability, constFieldAllocator, obfuscatedInstructions); - obfuscatedInstructions.Add(Instruction.Create(OpCodes.Mul)); - break; - } - case 3: - { - // c = a ^ b - int a = random.NextInt(); - int b = a ^ value; - float constProbability = 0.5f; - ConstObfusUtil.LoadConstTwoInt(a, b, random, constProbability, constFieldAllocator, obfuscatedInstructions); - obfuscatedInstructions.Add(Instruction.Create(OpCodes.Xor)); - break; - } - default: - { - if (needCacheValue) - { - FieldDef cacheField = constFieldAllocator.Allocate(value); - obfuscatedInstructions.Add(Instruction.Create(OpCodes.Ldsfld, cacheField)); - return; - } - int ops = GenerateEncryptionOperations(encryptionScope, random); - int salt = GenerateSalt(random); - int encryptedValue = encryptionScope.encryptor.Encrypt(value, ops, salt); - RvaData rvaData = rvaDataAllocator.Allocate(encryptedValue); - obfuscatedInstructions.Add(Instruction.Create(OpCodes.Ldsfld, rvaData.field)); - obfuscatedInstructions.Add(Instruction.CreateLdcI4(rvaData.offset)); - obfuscatedInstructions.Add(Instruction.CreateLdcI4(ops)); - obfuscatedInstructions.Add(Instruction.CreateLdcI4(salt)); - obfuscatedInstructions.Add(Instruction.Create(OpCodes.Call, importer.DecryptFromRvaInt)); - break; - } - } - - - } - - public void ObfuscateLong(MethodDef method, bool needCacheValue, long value, List obfuscatedInstructions) - { - EncryptionScopeInfo encryptionScope = _moduleEntityManager.EncryptionScopeProvider.GetScope(method.Module); - IRandom random = CreateRandomForValue(encryptionScope, value.GetHashCode()); - ConstFieldAllocator constFieldAllocator = _moduleEntityManager.GetEntity(method.Module); - RvaDataAllocator rvaDataAllocator = _moduleEntityManager.GetEntity(method.Module); - DefaultMetadataImporter importer = GetModuleMetadataImporter(method); - - switch (random.NextInt(5)) - { - case 0: - { - // c = encrypted static field - FieldDef cacheField = constFieldAllocator.Allocate(value); - obfuscatedInstructions.Add(Instruction.Create(OpCodes.Ldsfld, cacheField)); - break; - } - case 1: - { - // c = a + b - long a = random.NextLong(); - long b = value - a; - float constProbability = 0.5f; - ConstObfusUtil.LoadConstTwoLong(a, b, random, constProbability, constFieldAllocator, obfuscatedInstructions); - obfuscatedInstructions.Add(Instruction.Create(OpCodes.Add)); - break; - } - case 2: - { - // c = a * b - long a = random.NextLong() | 0x1; - long ra = MathUtil.ModInverse64(a); - long b = ra * value; - float constProbability = 0.5f; - ConstObfusUtil.LoadConstTwoLong(a, b, random, constProbability, constFieldAllocator, obfuscatedInstructions); - obfuscatedInstructions.Add(Instruction.Create(OpCodes.Mul)); - break; - } - case 3: - { - // c = a ^ b - long a = random.NextLong(); - long b = a ^ value; - float constProbability = 0.5f; - ConstObfusUtil.LoadConstTwoLong(a, b, random, constProbability, constFieldAllocator, obfuscatedInstructions); - obfuscatedInstructions.Add(Instruction.Create(OpCodes.Xor)); - break; - } - default: - { - if (needCacheValue) - { - FieldDef cacheField = constFieldAllocator.Allocate(value); - obfuscatedInstructions.Add(Instruction.Create(OpCodes.Ldsfld, cacheField)); - return; - } - - int ops = GenerateEncryptionOperations(encryptionScope, random); - int salt = GenerateSalt(random); - long encryptedValue = encryptionScope.encryptor.Encrypt(value, ops, salt); - RvaData rvaData = rvaDataAllocator.Allocate(encryptedValue); - - obfuscatedInstructions.Add(Instruction.Create(OpCodes.Ldsfld, rvaData.field)); - obfuscatedInstructions.Add(Instruction.CreateLdcI4(rvaData.offset)); - obfuscatedInstructions.Add(Instruction.CreateLdcI4(ops)); - obfuscatedInstructions.Add(Instruction.CreateLdcI4(salt)); - obfuscatedInstructions.Add(Instruction.Create(OpCodes.Call, importer.DecryptFromRvaLong)); - break; - } - } - - - } - - public void ObfuscateFloat(MethodDef method, bool needCacheValue, float value, List obfuscatedInstructions) - { - EncryptionScopeInfo encryptionScope = _moduleEntityManager.EncryptionScopeProvider.GetScope(method.Module); - IRandom random = CreateRandomForValue(encryptionScope, value.GetHashCode()); - ConstFieldAllocator constFieldAllocator = _moduleEntityManager.GetEntity(method.Module); - RvaDataAllocator rvaDataAllocator = _moduleEntityManager.GetEntity(method.Module); - DefaultMetadataImporter importer = GetModuleMetadataImporter(method); - - if (needCacheValue) - { - FieldDef cacheField = constFieldAllocator.Allocate(value); - obfuscatedInstructions.Add(Instruction.Create(OpCodes.Ldsfld, cacheField)); - return; - } - - - int ops = GenerateEncryptionOperations(encryptionScope, random); - int salt = GenerateSalt(random); - float encryptedValue = encryptionScope.encryptor.Encrypt(value, ops, salt); - RvaData rvaData = rvaDataAllocator.Allocate(encryptedValue); - - obfuscatedInstructions.Add(Instruction.Create(OpCodes.Ldsfld, rvaData.field)); - obfuscatedInstructions.Add(Instruction.CreateLdcI4(rvaData.offset)); - obfuscatedInstructions.Add(Instruction.CreateLdcI4(ops)); - obfuscatedInstructions.Add(Instruction.CreateLdcI4(salt)); - obfuscatedInstructions.Add(Instruction.Create(OpCodes.Call, importer.DecryptFromRvaFloat)); - } - - public void ObfuscateDouble(MethodDef method, bool needCacheValue, double value, List obfuscatedInstructions) - { - EncryptionScopeInfo encryptionScope = _moduleEntityManager.EncryptionScopeProvider.GetScope(method.Module); - IRandom random = CreateRandomForValue(encryptionScope, value.GetHashCode()); - ConstFieldAllocator constFieldAllocator = _moduleEntityManager.GetEntity(method.Module); - RvaDataAllocator rvaDataAllocator = _moduleEntityManager.GetEntity(method.Module); - DefaultMetadataImporter importer = GetModuleMetadataImporter(method); - - if (needCacheValue) - { - FieldDef cacheField = constFieldAllocator.Allocate(value); - obfuscatedInstructions.Add(Instruction.Create(OpCodes.Ldsfld, cacheField)); - return; - } - - - int ops = GenerateEncryptionOperations(encryptionScope, random); - int salt = GenerateSalt(random); - double encryptedValue = encryptionScope.encryptor.Encrypt(value, ops, salt); - RvaData rvaData = rvaDataAllocator.Allocate(encryptedValue); - - obfuscatedInstructions.Add(Instruction.Create(OpCodes.Ldsfld, rvaData.field)); - obfuscatedInstructions.Add(Instruction.CreateLdcI4(rvaData.offset)); - obfuscatedInstructions.Add(Instruction.CreateLdcI4(ops)); - obfuscatedInstructions.Add(Instruction.CreateLdcI4(salt)); - obfuscatedInstructions.Add(Instruction.Create(OpCodes.Call, importer.DecryptFromRvaDouble)); - } - - - class EncryptedRvaDataInfo - { - public readonly FieldDef fieldDef; - public readonly byte[] originalBytes; - public readonly byte[] encryptedBytes; - public readonly int opts; - public readonly int salt; - - public EncryptedRvaDataInfo(FieldDef fieldDef, byte[] originalBytes, byte[] encryptedBytes, int opts, int salt) - { - this.fieldDef = fieldDef; - this.originalBytes = originalBytes; - this.encryptedBytes = encryptedBytes; - this.opts = opts; - this.salt = salt; - } - } - - private readonly Dictionary _encryptedRvaFields = new Dictionary(); - - private EncryptedRvaDataInfo GetEncryptedRvaData(FieldDef fieldDef) - { - if (!_encryptedRvaFields.TryGetValue(fieldDef, out var encryptedRvaData)) - { - EncryptionScopeInfo encryptionScope = _moduleEntityManager.EncryptionScopeProvider.GetScope(fieldDef.Module); - IRandom random = CreateRandomForValue(encryptionScope, FieldEqualityComparer.CompareDeclaringTypes.GetHashCode(fieldDef)); - int ops = GenerateEncryptionOperations(encryptionScope, random); - int salt = GenerateSalt(random); - byte[] originalBytes = fieldDef.InitialValue; - byte[] encryptedBytes = (byte[])originalBytes.Clone(); - encryptionScope.encryptor.EncryptBlock(encryptedBytes, ops, salt); - Assert.AreNotEqual(originalBytes, encryptedBytes, "Original bytes should not be the same as encrypted bytes."); - encryptedRvaData = new EncryptedRvaDataInfo(fieldDef, originalBytes, encryptedBytes, ops, salt); - _encryptedRvaFields.Add(fieldDef, encryptedRvaData); - fieldDef.InitialValue = encryptedBytes; - byte[] decryptedBytes = (byte[])encryptedBytes.Clone(); - encryptionScope.encryptor.DecryptBlock(decryptedBytes, ops, salt); - AssertUtil.AreArrayEqual(originalBytes, decryptedBytes, "Decrypted bytes should match the original bytes after encryption and decryption."); - } - return encryptedRvaData; - } - - - public void ObfuscateBytes(MethodDef method, bool needCacheValue, FieldDef field, byte[] value, List obfuscatedInstructions) - { - EncryptedRvaDataInfo encryptedData = GetEncryptedRvaData(field); - Assert.AreEqual(value.Length, encryptedData.encryptedBytes.Length); - - DefaultMetadataImporter importer = GetModuleMetadataImporter(method); - obfuscatedInstructions.Add(Instruction.CreateLdcI4(encryptedData.encryptedBytes.Length)); - obfuscatedInstructions.Add(Instruction.CreateLdcI4(encryptedData.opts)); - obfuscatedInstructions.Add(Instruction.CreateLdcI4(encryptedData.salt)); - obfuscatedInstructions.Add(Instruction.Create(OpCodes.Call, importer.DecryptInitializeArray)); - } - - public void ObfuscateString(MethodDef method, bool needCacheValue, string value, List obfuscatedInstructions) - { - EncryptionScopeInfo encryptionScope = _moduleEntityManager.EncryptionScopeProvider.GetScope(method.Module); - IRandom random = CreateRandomForValue(encryptionScope, value.GetHashCode()); - ConstFieldAllocator constFieldAllocator = _moduleEntityManager.GetEntity(method.Module); - RvaDataAllocator rvaDataAllocator = _moduleEntityManager.GetEntity(method.Module); - DefaultMetadataImporter importer = GetModuleMetadataImporter(method); - - if (needCacheValue) - { - FieldDef cacheField = constFieldAllocator.Allocate(value); - obfuscatedInstructions.Add(Instruction.Create(OpCodes.Ldsfld, cacheField)); - return; - } - - int ops = GenerateEncryptionOperations(encryptionScope, random); - int salt = GenerateSalt(random); - int stringByteLength = Encoding.UTF8.GetByteCount(value); - byte[] encryptedValue = encryptionScope.encryptor.Encrypt(value, ops, salt); - Assert.AreEqual(stringByteLength, encryptedValue.Length); - RvaData rvaData = rvaDataAllocator.Allocate(encryptedValue); - - obfuscatedInstructions.Add(Instruction.Create(OpCodes.Ldsfld, rvaData.field)); - obfuscatedInstructions.Add(Instruction.CreateLdcI4(rvaData.offset)); - // should use stringByteLength, can't use rvaData.size, because rvaData.size is align to 4, it's not the actual length. - obfuscatedInstructions.Add(Instruction.CreateLdcI4(stringByteLength)); - obfuscatedInstructions.Add(Instruction.CreateLdcI4(ops)); - obfuscatedInstructions.Add(Instruction.CreateLdcI4(salt)); - obfuscatedInstructions.Add(Instruction.Create(OpCodes.Call, importer.DecryptFromRvaString)); - } - - public void Done() - { - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ConstEncrypt/DefaultConstEncryptor.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ConstEncrypt/DefaultConstEncryptor.cs.meta deleted file mode 100644 index 1e0977a2..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ConstEncrypt/DefaultConstEncryptor.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 4c6a0ecde97527e4694731e4d4de129a -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ConstEncrypt/IConstEncryptor.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ConstEncrypt/IConstEncryptor.cs deleted file mode 100644 index 0b2c087c..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ConstEncrypt/IConstEncryptor.cs +++ /dev/null @@ -1,32 +0,0 @@ -using dnlib.DotNet; -using dnlib.DotNet.Emit; -using System.Collections.Generic; - -namespace Obfuz.ObfusPasses.ConstEncrypt -{ - public interface IConstEncryptor - { - void ObfuscateInt(MethodDef method, bool needCacheValue, int value, List obfuscatedInstructions); - - void ObfuscateLong(MethodDef method, bool needCacheValue, long value, List obfuscatedInstructions); - - void ObfuscateFloat(MethodDef method, bool needCacheValue, float value, List obfuscatedInstructions); - - void ObfuscateDouble(MethodDef method, bool needCacheValue, double value, List obfuscatedInstructions); - - void ObfuscateString(MethodDef method, bool needCacheValue, string value, List obfuscatedInstructions); - - void ObfuscateBytes(MethodDef method, bool needCacheValue, FieldDef field, byte[] value, List obfuscatedInstructions); - } - - public abstract class ConstEncryptorBase : IConstEncryptor - { - public abstract void ObfuscateBytes(MethodDef method, bool needCacheValue, byte[] value, List obfuscatedInstructions); - public abstract void ObfuscateDouble(MethodDef method, bool needCacheValue, double value, List obfuscatedInstructions); - public abstract void ObfuscateFloat(MethodDef method, bool needCacheValue, float value, List obfuscatedInstructions); - public abstract void ObfuscateInt(MethodDef method, bool needCacheValue, int value, List obfuscatedInstructions); - public abstract void ObfuscateLong(MethodDef method, bool needCacheValue, long value, List obfuscatedInstructions); - public abstract void ObfuscateString(MethodDef method, bool needCacheValue, string value, List obfuscatedInstructions); - public abstract void ObfuscateBytes(MethodDef method, bool needCacheValue, FieldDef field, byte[] value, List obfuscatedInstructions); - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ConstEncrypt/IConstEncryptor.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ConstEncrypt/IConstEncryptor.cs.meta deleted file mode 100644 index 7f8d5871..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ConstEncrypt/IConstEncryptor.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 0ccbcdadf1913b6498eaee53abac5d0b -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ConstEncrypt/IEncryptPolicy.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ConstEncrypt/IEncryptPolicy.cs deleted file mode 100644 index 0067cc0f..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ConstEncrypt/IEncryptPolicy.cs +++ /dev/null @@ -1,43 +0,0 @@ -using dnlib.DotNet; - -namespace Obfuz.ObfusPasses.ConstEncrypt -{ - public struct ConstCachePolicy - { - public bool cacheConstInLoop; - public bool cacheConstNotInLoop; - public bool cacheStringInLoop; - public bool cacheStringNotInLoop; - } - - public interface IEncryptPolicy - { - bool NeedObfuscateMethod(MethodDef method); - - ConstCachePolicy GetMethodConstCachePolicy(MethodDef method); - - bool NeedObfuscateInt(MethodDef method, bool currentInLoop, int value); - - bool NeedObfuscateLong(MethodDef method, bool currentInLoop, long value); - - bool NeedObfuscateFloat(MethodDef method, bool currentInLoop, float value); - - bool NeedObfuscateDouble(MethodDef method, bool currentInLoop, double value); - - bool NeedObfuscateString(MethodDef method, bool currentInLoop, string value); - - bool NeedObfuscateArray(MethodDef method, bool currentInLoop, byte[] array); - } - - public abstract class EncryptPolicyBase : IEncryptPolicy - { - public abstract bool NeedObfuscateMethod(MethodDef method); - public abstract ConstCachePolicy GetMethodConstCachePolicy(MethodDef method); - public abstract bool NeedObfuscateDouble(MethodDef method, bool currentInLoop, double value); - public abstract bool NeedObfuscateFloat(MethodDef method, bool currentInLoop, float value); - public abstract bool NeedObfuscateInt(MethodDef method, bool currentInLoop, int value); - public abstract bool NeedObfuscateLong(MethodDef method, bool currentInLoop, long value); - public abstract bool NeedObfuscateString(MethodDef method, bool currentInLoop, string value); - public abstract bool NeedObfuscateArray(MethodDef method, bool currentInLoop, byte[] array); - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ConstEncrypt/IEncryptPolicy.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ConstEncrypt/IEncryptPolicy.cs.meta deleted file mode 100644 index 0a44790d..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ConstEncrypt/IEncryptPolicy.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 18e57864070430a44ac561bdd7d00b2e -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ControlFlowObfus.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ControlFlowObfus.meta deleted file mode 100644 index 9013ba54..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ControlFlowObfus.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 02fb097cf61874c41923b3ef23fee199 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ControlFlowObfus/ConfigurableObfuscationPolicy.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ControlFlowObfus/ConfigurableObfuscationPolicy.cs deleted file mode 100644 index b86b1e7c..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ControlFlowObfus/ConfigurableObfuscationPolicy.cs +++ /dev/null @@ -1,133 +0,0 @@ -using dnlib.DotNet; -using Obfuz.Conf; -using Obfuz.Settings; -using Obfuz.Utils; -using System; -using System.Collections.Generic; -using System.Xml; - -namespace Obfuz.ObfusPasses.ControlFlowObfus -{ - struct ObfuscationRuleData - { - public readonly ObfuscationLevel obfuscationLevel; - public ObfuscationRuleData(ObfuscationLevel level) - { - obfuscationLevel = level; - } - } - - interface IObfuscationPolicy - { - bool NeedObfuscate(MethodDef method); - - ObfuscationRuleData GetObfuscationRuleData(MethodDef method); - } - - abstract class ObfuscationPolicyBase : IObfuscationPolicy - { - public abstract bool NeedObfuscate(MethodDef method); - - public abstract ObfuscationRuleData GetObfuscationRuleData(MethodDef method); - } - - class ConfigurableObfuscationPolicy : ObfuscationPolicyBase - { - class ObfuscationRule : IRule - { - public ObfuscationLevel? obfuscationLevel; - - public void InheritParent(ObfuscationRule parentRule) - { - if (obfuscationLevel == null) - obfuscationLevel = parentRule.obfuscationLevel; - } - } - - class MethodSpec : MethodRuleBase - { - } - - class TypeSpec : TypeRuleBase - { - } - - class AssemblySpec : AssemblyRuleBase - { - } - - private static readonly ObfuscationRule s_default = new ObfuscationRule() - { - obfuscationLevel = ObfuscationLevel.Basic, - }; - - private ObfuscationRule _global; - - private readonly XmlAssemblyTypeMethodRuleParser _xmlParser; - - private readonly Dictionary _methodRuleCache = new Dictionary(); - - public ConfigurableObfuscationPolicy(List toObfuscatedAssemblyNames, List xmlConfigFiles) - { - _xmlParser = new XmlAssemblyTypeMethodRuleParser( - toObfuscatedAssemblyNames, ParseObfuscationRule, ParseGlobal); - LoadConfigs(xmlConfigFiles); - } - - private void LoadConfigs(List configFiles) - { - _xmlParser.LoadConfigs(configFiles); - - if (_global == null) - { - _global = s_default; - } - else - { - _global.InheritParent(s_default); - } - _xmlParser.InheritParentRules(_global); - } - - private void ParseGlobal(string configFile, XmlElement ele) - { - switch (ele.Name) - { - case "global": _global = ParseObfuscationRule(configFile, ele); break; - default: throw new Exception($"Invalid xml file {configFile}, unknown node {ele.Name}"); - } - } - - private ObfuscationRule ParseObfuscationRule(string configFile, XmlElement ele) - { - var rule = new ObfuscationRule(); - if (ele.HasAttribute("obfuscationLevel")) - { - rule.obfuscationLevel = ConfigUtil.ParseObfuscationLevel(ele.GetAttribute("obfuscationLevel")); - } - return rule; - } - - private ObfuscationRule GetMethodObfuscationRule(MethodDef method) - { - if (!_methodRuleCache.TryGetValue(method, out var rule)) - { - rule = _xmlParser.GetMethodRule(method, _global); - _methodRuleCache[method] = rule; - } - return rule; - } - - public override bool NeedObfuscate(MethodDef method) - { - ObfuscationRule rule = GetMethodObfuscationRule(method); - return rule.obfuscationLevel.Value > ObfuscationLevel.None; - } - - public override ObfuscationRuleData GetObfuscationRuleData(MethodDef method) - { - var rule = GetMethodObfuscationRule(method); - return new ObfuscationRuleData(rule.obfuscationLevel.Value); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ControlFlowObfus/ConfigurableObfuscationPolicy.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ControlFlowObfus/ConfigurableObfuscationPolicy.cs.meta deleted file mode 100644 index 1203f4b8..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ControlFlowObfus/ConfigurableObfuscationPolicy.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: f6983877d8859df4882c30f75be7a70e -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ControlFlowObfus/ControlFlowObfusPass.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ControlFlowObfus/ControlFlowObfusPass.cs deleted file mode 100644 index bcb04e05..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ControlFlowObfus/ControlFlowObfusPass.cs +++ /dev/null @@ -1,80 +0,0 @@ -using dnlib.DotNet; -using Obfuz.Data; -using Obfuz.Emit; -using Obfuz.Settings; -using Obfuz.Utils; - -namespace Obfuz.ObfusPasses.ControlFlowObfus -{ - class ObfusMethodContext - { - public MethodDef method; - public LocalVariableAllocator localVariableAllocator; - public IRandom localRandom; - public EncryptionScopeInfo encryptionScope; - public DefaultMetadataImporter importer; - public ConstFieldAllocator constFieldAllocator; - public int minInstructionCountOfBasicBlockToObfuscate; - - public IRandom CreateRandom() - { - return encryptionScope.localRandomCreator(MethodEqualityComparer.CompareDeclaringTypes.GetHashCode(method)); - } - } - - internal class ControlFlowObfusPass : ObfuscationMethodPassBase - { - private readonly ControlFlowObfuscationSettingsFacade _settings; - - private IObfuscationPolicy _obfuscationPolicy; - private IObfuscator _obfuscator; - - public ControlFlowObfusPass(ControlFlowObfuscationSettingsFacade settings) - { - _settings = settings; - _obfuscator = new DefaultObfuscator(); - } - - public override ObfuscationPassType Type => ObfuscationPassType.ControlFlowObfus; - - public override void Start() - { - ObfuscationPassContext ctx = ObfuscationPassContext.Current; - _obfuscationPolicy = new ConfigurableObfuscationPolicy( - ctx.coreSettings.assembliesToObfuscate, - _settings.ruleFiles); - } - - public override void Stop() - { - - } - - protected override bool NeedObfuscateMethod(MethodDef method) - { - return _obfuscationPolicy.NeedObfuscate(method); - } - - protected override void ObfuscateData(MethodDef method) - { - //Debug.Log($"Obfuscating method: {method.FullName} with EvalStackObfusPass"); - - ObfuscationPassContext ctx = ObfuscationPassContext.Current; - GroupByModuleEntityManager moduleEntityManager = ctx.moduleEntityManager; - var encryptionScope = moduleEntityManager.EncryptionScopeProvider.GetScope(method.Module); - var ruleData = _obfuscationPolicy.GetObfuscationRuleData(method); - var localRandom = encryptionScope.localRandomCreator(MethodEqualityComparer.CompareDeclaringTypes.GetHashCode(method)); - var obfusMethodCtx = new ObfusMethodContext - { - method = method, - localVariableAllocator = new LocalVariableAllocator(method), - encryptionScope = encryptionScope, - constFieldAllocator = moduleEntityManager.GetEntity(method.Module), - localRandom = localRandom, - importer = moduleEntityManager.GetEntity(method.Module), - minInstructionCountOfBasicBlockToObfuscate = _settings.minInstructionCountOfBasicBlockToObfuscate, - }; - _obfuscator.Obfuscate(method, obfusMethodCtx); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ControlFlowObfus/ControlFlowObfusPass.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ControlFlowObfus/ControlFlowObfusPass.cs.meta deleted file mode 100644 index ad62fd65..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ControlFlowObfus/ControlFlowObfusPass.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: cf62db4d3137e6447bd5cb2a65f101d3 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ControlFlowObfus/DefaultObfuscator.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ControlFlowObfus/DefaultObfuscator.cs deleted file mode 100644 index 9bd216aa..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ControlFlowObfus/DefaultObfuscator.cs +++ /dev/null @@ -1,20 +0,0 @@ -using dnlib.DotNet; -using UnityEngine; - -namespace Obfuz.ObfusPasses.ControlFlowObfus -{ - class DefaultObfuscator : ObfuscatorBase - { - public override bool Obfuscate(MethodDef method, ObfusMethodContext ctx) - { - //Debug.Log($"Obfuscating method: {method.FullName} with ControlFlowObfusPass"); - var mcfc = new MethodControlFlowCalculator(method, ctx.CreateRandom(), ctx.constFieldAllocator, ctx.minInstructionCountOfBasicBlockToObfuscate); - if (!mcfc.TryObfus()) - { - //Debug.LogWarning($"not obfuscate method: {method.FullName}"); - return false; - } - return true; - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ControlFlowObfus/DefaultObfuscator.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ControlFlowObfus/DefaultObfuscator.cs.meta deleted file mode 100644 index 25926093..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ControlFlowObfus/DefaultObfuscator.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 8aa2a2e43fa066541b982dbb63452458 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ControlFlowObfus/IObfuscator.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ControlFlowObfus/IObfuscator.cs deleted file mode 100644 index 7909bf2c..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ControlFlowObfus/IObfuscator.cs +++ /dev/null @@ -1,15 +0,0 @@ -using dnlib.DotNet; -using Obfuz.Emit; - -namespace Obfuz.ObfusPasses.ControlFlowObfus -{ - interface IObfuscator - { - bool Obfuscate(MethodDef method, ObfusMethodContext ctx); - } - - abstract class ObfuscatorBase : IObfuscator - { - public abstract bool Obfuscate(MethodDef method, ObfusMethodContext ctx); - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ControlFlowObfus/IObfuscator.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ControlFlowObfus/IObfuscator.cs.meta deleted file mode 100644 index e909f237..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ControlFlowObfus/IObfuscator.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 4ada5f6005768f745a18dc8b968e1684 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ControlFlowObfus/MethodControlFlowCalculator.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ControlFlowObfus/MethodControlFlowCalculator.cs deleted file mode 100644 index 06488c0d..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ControlFlowObfus/MethodControlFlowCalculator.cs +++ /dev/null @@ -1,894 +0,0 @@ -using dnlib.DotNet; -using dnlib.DotNet.Emit; -using Obfuz.Data; -using Obfuz.Emit; -using Obfuz.Utils; -using System; -using System.Collections.Generic; -using System.Linq; -using UnityEngine; -using UnityEngine.Assertions; - -namespace Obfuz.ObfusPasses.ControlFlowObfus -{ - class MethodControlFlowCalculator - { - class BasicBlockInputOutputArguments - { - public readonly List locals = new List(); - - public BasicBlockInputOutputArguments() - { - } - - public BasicBlockInputOutputArguments(MethodDef method, List inputStackDatas) - { - ICorLibTypes corLibTypes = method.Module.CorLibTypes; - foreach (var data in inputStackDatas) - { - Local local = new Local(GetLocalTypeSig(corLibTypes, data)); - locals.Add(local); - method.Body.Variables.Add(local); - } - } - - private TypeSig GetLocalTypeSig(ICorLibTypes corLibTypes, EvalDataTypeWithSig type) - { - switch (type.type) - { - case EvalDataType.Int32: return corLibTypes.Int32; - case EvalDataType.Int64: return corLibTypes.Int64; - case EvalDataType.Float: return corLibTypes.Single; - case EvalDataType.Double: return corLibTypes.Double; - case EvalDataType.I: return corLibTypes.IntPtr; - case EvalDataType.Ref: Assert.IsNotNull(type.typeSig); return type.typeSig; - case EvalDataType.ValueType: Assert.IsNotNull(type.typeSig); return type.typeSig; - case EvalDataType.Token: throw new System.NotSupportedException("Token type is not supported in BasicBlockInputOutputArguments"); - default: throw new System.NotSupportedException("not supported EvalDataType"); - } - } - } - - class BasicBlockInfo - { - public BlockGroup group; - - //public int order; - public bool isSaveStackBlock; - public BasicBlockInfo prev; - public BasicBlockInfo next; - - public List instructions; - public List inputStackDatas; - public List outputStackDatas; - - public List inBasicBlocks = new List(); - public List outBasicBlocks = new List(); - - public BasicBlockInputOutputArguments inputArgs; - public BasicBlockInputOutputArguments outputArgs; - - public Instruction FirstInstruction => instructions[0]; - - public Instruction LastInstruction => instructions[instructions.Count - 1]; - - public Instruction GroupFirstInstruction => group.basicBlocks[0].FirstInstruction; - - - //public void InsertNext(BasicBlockInfo nextBb) - //{ - // if (next != null) - // { - // next.prev = nextBb; - // nextBb.next = next; - // } - // nextBb.prev = this; - // next = nextBb; - //} - - public void InsertBefore(BasicBlockInfo prevBb) - { - prev.next = prevBb; - prevBb.prev = prev; - prevBb.next = this; - this.prev = prevBb; - } - - public void AddOutBasicBlock(BasicBlockInfo outBb) - { - if (!outBasicBlocks.Contains(outBb)) - { - outBasicBlocks.Add(outBb); - outBb.inBasicBlocks.Add(this); - } - } - - public void ClearInBasicBlocks() - { - foreach (var inBb in inBasicBlocks) - { - inBb.outBasicBlocks.Remove(this); - } - inBasicBlocks.Clear(); - } - - public void RetargetInBasicBlocksTo(BasicBlockInfo prevBb, Dictionary inst2bb) - { - var oldInBlocks = new List(inBasicBlocks); - ClearInBasicBlocks(); - foreach (var oldInBb in oldInBlocks) - { - oldInBb.AddOutBasicBlock(prevBb); - } - // inBB => saveBb => cur - foreach (BasicBlockInfo inBb in prevBb.inBasicBlocks) - { - if (inBb.instructions.Count == 0) - { - // empty block, no need to retarget - continue; - } - Instruction lastInst = inBb.instructions.Last(); - if (lastInst.Operand is Instruction targetInst) - { - if (inst2bb.TryGetValue(targetInst, out BasicBlockInfo targetBb) && targetBb == this) - { - // retarget to prevBb - lastInst.Operand = prevBb.FirstInstruction; - } - } - else if (lastInst.Operand is Instruction[] targetInsts) - { - for (int i = 0; i < targetInsts.Length; i++) - { - targetInst = targetInsts[i]; - if (inst2bb.TryGetValue(targetInst, out BasicBlockInfo targetBb) && targetBb == this) - { - targetInsts[i] = prevBb.FirstInstruction; - } - } - } - } - } - } - - private readonly MethodDef _method; - private readonly IRandom _random; - private readonly ConstFieldAllocator _constFieldAllocator; - private readonly int _minInstructionCountOfBasicBlockToObfuscate; - private readonly BasicBlockInfo _bbHead; - - public MethodControlFlowCalculator(MethodDef method, IRandom random, ConstFieldAllocator constFieldAllocator, int minInstructionCountOfBasicBlockToObfuscate) - { - _method = method; - _random = random; - _constFieldAllocator = constFieldAllocator; - _minInstructionCountOfBasicBlockToObfuscate = minInstructionCountOfBasicBlockToObfuscate; - - _bbHead = new BasicBlockInfo() - { - instructions = new List(), - inputStackDatas = new List(), - outputStackDatas = new List(), - }; - } - - private void BuildBasicBlockLink(EvalStackCalculator evc) - { - BasicBlockInfo prev = _bbHead; - var bb2bb = new Dictionary(); - foreach (BasicBlock bb in evc.BasicBlockCollection.Blocks) - { - EvalStackState ess = evc.GetEvalStackState(bb); - var newBB = new BasicBlockInfo - { - prev = prev, - next = null, - instructions = bb.instructions, - inputStackDatas = ess.inputStackDatas, - outputStackDatas = ess.runStackDatas, - }; - prev.next = newBB; - prev = newBB; - bb2bb.Add(bb, newBB); - } - foreach (BasicBlock bb in evc.BasicBlockCollection.Blocks) - { - BasicBlockInfo bbi = bb2bb[bb]; - foreach (var inBb in bb.inBlocks) - { - bbi.inBasicBlocks.Add(bb2bb[inBb]); - } - foreach (var outBb in bb.outBlocks) - { - bbi.outBasicBlocks.Add(bb2bb[outBb]); - } - } - - // let _bbHead point to the first basic block - //_bbHead.instructions.Add(Instruction.Create(OpCodes.Br, _bbHead.next.FirstInstruction)); - _bbHead.next.inBasicBlocks.Add(_bbHead); - _bbHead.outBasicBlocks.Add(_bbHead.next); - } - - private bool CheckNotContainsNotSupportedEvalStackData() - { - for (BasicBlockInfo cur = _bbHead; cur != null; cur = cur.next) - { - foreach (var data in cur.inputStackDatas) - { - if (data.type == EvalDataType.Unknown || data.type == EvalDataType.Token) - { - Debug.LogError($"NotSupported EvalStackData found in method: {_method.FullName}, type: {data.type}"); - return false; - } - } - } - return true; - } - - - private void WalkInputArgumentGroup(BasicBlockInfo cur, BasicBlockInputOutputArguments inputArgs) - { - if (cur.inputArgs != null) - { - Assert.AreEqual(cur.inputArgs, inputArgs, "input arguments not match"); - return; - } - cur.inputArgs = inputArgs; - foreach (BasicBlockInfo inputBB in cur.inBasicBlocks) - { - if (inputBB.outputArgs != null) - { - Assert.AreEqual(inputBB.outputArgs, inputArgs, $"Input BB {inputBB} outputArgs does not match in method: {_method.FullName}"); - continue; - } - inputBB.outputArgs = cur.inputArgs; - foreach (var outBB in inputBB.outBasicBlocks) - { - WalkInputArgumentGroup(outBB, inputArgs); - } - } - } - - private readonly BasicBlockInputOutputArguments emptyEvalStackArgs = new BasicBlockInputOutputArguments(); - - private void ComputeInputOutputArguments() - { - for (BasicBlockInfo cur = _bbHead; cur != null; cur = cur.next) - { - if (cur.inputArgs == null) - { - if (cur.inputStackDatas.Count == 0) - { - cur.inputArgs = emptyEvalStackArgs; - } - else - { - var inputArgs = new BasicBlockInputOutputArguments(_method, cur.inputStackDatas); - WalkInputArgumentGroup(cur, inputArgs); - } - } - if (cur.outputArgs == null && cur.outputStackDatas.Count == 0) - { - cur.outputArgs = emptyEvalStackArgs; - } - } - for (BasicBlockInfo cur = _bbHead; cur != null; cur = cur.next) - { - if (cur.inputArgs == null) - { - throw new System.Exception($"Input arguments for BasicBlock {cur} in method {_method.FullName} is null"); - } - if (cur.outputArgs == null) - { - if (cur.instructions.Count > 0) - { - Code lastInstCode = cur.LastInstruction.OpCode.Code; - Assert.IsTrue(lastInstCode == Code.Throw || lastInstCode == Code.Rethrow); - cur.outputStackDatas = new List(); - } - cur.outputArgs = emptyEvalStackArgs; - } - } - } - - - private BasicBlockInfo CreateSaveStackBasicBlock(BasicBlockInfo to) - { - if (to.group == null) - { - throw new Exception($"BasicBlock {to} in method {_method.FullName} does not belong to any group. This should not happen."); - } - - var saveLocalBasicBlock = new BasicBlockInfo - { - group = to.group, - isSaveStackBlock = true, - inputStackDatas = to.inputStackDatas, - inputArgs = to.inputArgs, - outputStackDatas = new List(), - outputArgs = emptyEvalStackArgs, - instructions = new List(), - }; - - var locals = to.inputArgs.locals; - if (locals.Count > 0) - { - to.instructions.InsertRange(0, locals.Select(l => Instruction.Create(OpCodes.Ldloc, l))); - - } - for (int i = locals.Count - 1; i >= 0; i--) - { - saveLocalBasicBlock.instructions.Add(Instruction.Create(OpCodes.Stloc, locals[i])); - } - - to.inputArgs = emptyEvalStackArgs; - to.inputStackDatas = new List(); - - BlockGroup group = to.group; - group.basicBlocks.Insert(group.basicBlocks.IndexOf(to), saveLocalBasicBlock); - group.switchMachineCases.Add(new SwitchMachineCase { index = -1, prepareBlock = saveLocalBasicBlock, targetBlock = to}); - saveLocalBasicBlock.instructions.Add(Instruction.Create(OpCodes.Ldsfld, (FieldDef)null)); - saveLocalBasicBlock.instructions.Add(Instruction.Create(OpCodes.Br, group.switchMachineInst)); - - - return saveLocalBasicBlock; - } - - private void AdjustInputOutputEvalStack() - { - Dictionary inst2bb = BuildInstructionToBasicBlockInfoDic(); - for (BasicBlockInfo cur = _bbHead.next; cur != null; cur = cur.next) - { - if (cur.inputArgs.locals.Count == 0 && cur.instructions.Count < _minInstructionCountOfBasicBlockToObfuscate) - { - // small block, no need to save stack - continue; - } - - BasicBlockInfo saveBb = CreateSaveStackBasicBlock(cur); - cur.InsertBefore(saveBb); - cur.RetargetInBasicBlocksTo(saveBb, inst2bb); - //saveBb.AddOutBasicBlock(cur); - } - } - - private void InsertSwitchMachineBasicBlockForGroups(BlockGroup rootGroup) - { - Dictionary inst2bb = BuildInstructionToBasicBlockInfoDic(); - - InsertSwitchMachineBasicBlockForGroup(rootGroup, inst2bb); - } - - //private void ShuffleBasicBlocks0(List bbs) - //{ - // int n = bbs.Count; - // if (n <= 1) - // { - // return; - // } - - // var firstSection = new List() { bbs[0] }; - // var sectionsExcludeFirstLast = new List>(); - // List currentSection = firstSection; - // for (int i = 1; i < n; i++) - // { - // BasicBlockInfo cur = bbs[i]; - // if (cur.inputArgs.locals.Count == 0) - // { - // currentSection = new List() { cur }; - // sectionsExcludeFirstLast.Add(currentSection); - // } - // else - // { - // currentSection.Add(cur); - // } - // } - // if (sectionsExcludeFirstLast.Count <= 1) - // { - // return; - // } - // var lastSection = sectionsExcludeFirstLast.Last(); - // sectionsExcludeFirstLast.RemoveAt(sectionsExcludeFirstLast.Count - 1); - - - // RandomUtil.ShuffleList(sectionsExcludeFirstLast, _random); - - // bbs.Clear(); - // bbs.AddRange(firstSection); - // bbs.AddRange(sectionsExcludeFirstLast.SelectMany(section => section)); - // bbs.AddRange(lastSection); - // Assert.AreEqual(n, bbs.Count, "Shuffled basic blocks count should be the same as original count"); - //} - - private void ShuffleBasicBlocks(List bbs) - { - // TODO - - //int n = bbs.Count; - //BasicBlockInfo groupPrev = bbs[0].prev; - //BasicBlockInfo groupNext = bbs[n - 1].next; - ////RandomUtil.ShuffleList(bbs, _random); - //ShuffleBasicBlocks0(bbs); - //BasicBlockInfo prev = groupPrev; - //for (int i = 0; i < n; i++) - //{ - // BasicBlockInfo cur = bbs[i]; - // cur.prev = prev; - // prev.next = cur; - // prev = cur; - //} - //prev.next = groupNext; - //if (groupNext != null) - //{ - // groupNext.prev = prev; - //} - } - - private void InsertSwitchMachineBasicBlockForGroup(BlockGroup group, Dictionary inst2bb) - { - if (group.subGroups != null && group.subGroups.Count > 0) - { - foreach (var subGroup in group.subGroups) - { - InsertSwitchMachineBasicBlockForGroup(subGroup, inst2bb); - } - } - else if (group.switchMachineCases.Count > 0) - { - Assert.IsTrue(group.basicBlocks.Count > 0, "Group should contain at least one basic block"); - - BasicBlockInfo firstBlock = group.basicBlocks[0]; - var firstCase = group.switchMachineCases[0]; - //Assert.AreEqual(firstCase.prepareBlock, firstBlock, "First case prepare block should be the first basic block in group"); - - Assert.IsTrue(firstCase.targetBlock.inputArgs.locals.Count == 0); - Assert.IsTrue(firstCase.targetBlock.inputStackDatas.Count == 0); - - var instructions = new List() - { - Instruction.Create(OpCodes.Ldsfld, (FieldDef)null), - group.switchMachineInst, - Instruction.Create(OpCodes.Br, firstCase.targetBlock.FirstInstruction), - }; - if (firstCase.prepareBlock != firstBlock || firstBlock.inputStackDatas.Count != 0) - { - instructions.Insert(0, Instruction.Create(OpCodes.Br, firstBlock.FirstInstruction)); - } - - var switchMachineBb = new BasicBlockInfo() - { - group = group, - inputArgs = firstBlock.inputArgs, - outputArgs = emptyEvalStackArgs, - inputStackDatas = firstBlock.inputStackDatas, - outputStackDatas = new List(), - instructions = instructions, - }; - firstBlock.InsertBefore(switchMachineBb); - group.basicBlocks.Insert(0, switchMachineBb); - ShuffleBasicBlocks(group.basicBlocks); - - List switchTargets = (List)group.switchMachineInst.Operand; - - RandomUtil.ShuffleList(group.switchMachineCases, _random); - - for (int i = 0, n = group.switchMachineCases.Count; i < n; i++) - { - SwitchMachineCase switchMachineCase = group.switchMachineCases[i]; - switchMachineCase.index = i; - List prepareBlockInstructions = switchMachineCase.prepareBlock.instructions; - - Instruction setBranchIndexInst = prepareBlockInstructions[prepareBlockInstructions.Count - 2]; - Assert.AreEqual(setBranchIndexInst.OpCode, OpCodes.Ldsfld, "first instruction of prepareBlock should be Ldsfld"); - //setBranchIndexInst.Operand = i; - var indexField = _constFieldAllocator.Allocate(i); - setBranchIndexInst.Operand = indexField; - switchTargets.Add(switchMachineCase.targetBlock.FirstInstruction); - } - - // after shuffle - Assert.IsTrue(instructions.Count == 3 || instructions.Count == 4, "Switch machine basic block should contain 3 or 4 instructions"); - Assert.AreEqual(Code.Ldsfld, instructions[instructions.Count - 3].OpCode.Code, "First instruction should be Ldsfld"); - instructions[instructions.Count - 3].Operand = _constFieldAllocator.Allocate(firstCase.index); - } - } - - private bool IsPrevBasicBlockControlFlowNextToThis(BasicBlockInfo cur) - { - Instruction lastInst = cur.prev.LastInstruction; - switch (lastInst.OpCode.FlowControl) - { - case FlowControl.Cond_Branch: - case FlowControl.Call: - case FlowControl.Next: - case FlowControl.Break: - { - return true; - } - default: return false; - } - } - - private void InsertBrInstructionForConjoinedBasicBlocks() - { - for (BasicBlockInfo cur = _bbHead.next.next; cur != null; cur = cur.next) - { - if (cur.group == cur.prev.group && IsPrevBasicBlockControlFlowNextToThis(cur)) - { - cur.prev.instructions.Add(Instruction.Create(OpCodes.Br, cur.FirstInstruction)); - } - } - } - - private Dictionary BuildInstructionToBasicBlockInfoDic() - { - var inst2bb = new Dictionary(); - for (BasicBlockInfo cur = _bbHead.next; cur != null; cur = cur.next) - { - foreach (var inst in cur.instructions) - { - inst2bb[inst] = cur; - } - } - return inst2bb; - } - - - private class SwitchMachineCase - { - public int index; - public BasicBlockInfo prepareBlock; - public BasicBlockInfo targetBlock; - } - - private class BlockGroup - { - public BlockGroup parent; - - public List instructions; - - public List subGroups; - - public List basicBlocks; - - public Instruction switchMachineInst; - public List switchMachineCases; - - public BlockGroup(List instructions, Dictionary inst2group) - { - this.instructions = instructions; - UpdateInstructionGroup(inst2group); - } - - public BlockGroup(BlockGroup parent, List instructions, Dictionary inst2group) - { - this.instructions = instructions; - UpdateInstructionGroup(parent, inst2group); - } - - public BlockGroup RootParent => parent == null ? this : parent.RootParent; - - public void SetParent(BlockGroup newParent) - { - if (parent != null) - { - Assert.IsTrue(parent != newParent, "Parent group should not be the same as new parent"); - Assert.IsTrue(parent.subGroups.Contains(this), "Parent group should already contain this group"); - parent.subGroups.Remove(this); - } - parent = newParent; - if (newParent.subGroups == null) - { - newParent.subGroups = new List(); - } - Assert.IsFalse(newParent.subGroups.Contains(this), "New parent group should not already contain this group"); - newParent.subGroups.Add(this); - } - - private void UpdateInstructionGroup(Dictionary inst2group) - { - foreach (var inst in instructions) - { - if (inst2group.TryGetValue(inst, out BlockGroup existGroup)) - { - if (this != existGroup) - { - BlockGroup rootParent = existGroup.RootParent; - if (rootParent != this) - { - rootParent.SetParent(this); - } - } - } - else - { - inst2group[inst] = this; - } - } - } - - private void UpdateInstructionGroup(BlockGroup parentGroup, Dictionary inst2group) - { - foreach (var inst in instructions) - { - BlockGroup existGroup = inst2group[inst]; - Assert.AreEqual(parentGroup, existGroup, "Instruction group parent should be the same as parent group"); - inst2group[inst] = this; - } - SetParent(parentGroup); - } - - public void SplitInstructionsNotInAnySubGroupsToIndividualGroups(Dictionary inst2group) - { - if (subGroups == null || subGroups.Count == 0 || instructions.Count == 0) - { - return; - } - - foreach (var subGroup in subGroups) - { - subGroup.SplitInstructionsNotInAnySubGroupsToIndividualGroups(inst2group); - } - - var finalGroupList = new List(); - var curGroupInstructions = new List(); - - var firstInst2SubGroup = subGroups.ToDictionary(g => g.instructions[0]); - foreach (var inst in instructions) - { - BlockGroup group = inst2group[inst]; - if (group == this) - { - curGroupInstructions.Add(inst); - } - else - { - if (curGroupInstructions.Count > 0) - { - finalGroupList.Add(new BlockGroup(this, curGroupInstructions, inst2group)); - curGroupInstructions = new List(); - } - if (firstInst2SubGroup.TryGetValue(inst, out var subGroup)) - { - finalGroupList.Add(subGroup); - } - } - } - if (curGroupInstructions.Count > 0) - { - finalGroupList.Add(new BlockGroup(this, curGroupInstructions, inst2group)); - } - this.subGroups = finalGroupList; - } - - public void ComputeBasicBlocks(Dictionary inst2bb) - { - if (subGroups == null || subGroups.Count == 0) - { - basicBlocks = new List(); - foreach (var inst in instructions) - { - BasicBlockInfo block = inst2bb[inst]; - if (block.group != null) - { - if (block.group != this) - { - throw new Exception("BasicBlockInfo group should be the same as this BlockGroup"); - } - } - else - { - block.group = this; - basicBlocks.Add(block); - } - } - switchMachineInst = Instruction.Create(OpCodes.Switch, new List()); - switchMachineCases = new List(); - return; - } - foreach (var subGroup in subGroups) - { - subGroup.ComputeBasicBlocks(inst2bb); - } - } - } - - private class TryBlockGroup : BlockGroup - { - public TryBlockGroup(List instructions, Dictionary inst2group) : base(instructions, inst2group) - { - } - } - - private class ExceptionHandlerGroup : BlockGroup - { - public readonly ExceptionHandler exceptionHandler; - - public ExceptionHandlerGroup(ExceptionHandler exceptionHandler, List instructions, Dictionary inst2group) : base(instructions, inst2group) - { - this.exceptionHandler = exceptionHandler; - } - } - - private class ExceptionFilterGroup : BlockGroup - { - public readonly ExceptionHandler exceptionHandler; - - public ExceptionFilterGroup(ExceptionHandler exceptionHandler, List instructions, Dictionary inst2group) : base(instructions, inst2group) - { - this.exceptionHandler = exceptionHandler; - } - } - - private class ExceptionHandlerWithFilterGroup : BlockGroup - { - public readonly ExceptionHandler exceptionHandler; - //public readonly ExceptionFilterGroup filterGroup; - //public readonly ExceptionHandlerGroup handlerGroup; - public ExceptionHandlerWithFilterGroup(ExceptionHandler exceptionHandler, List filterInstructions, List handlerInstructions, List allInstructions, Dictionary inst2group) : base(allInstructions, inst2group) - { - this.exceptionHandler = exceptionHandler; - var filterGroup = new ExceptionFilterGroup(exceptionHandler, filterInstructions, inst2group); - var handlerGroup = new ExceptionHandlerGroup(exceptionHandler, handlerInstructions, inst2group); - } - } - - class TryBlockInfo - { - public Instruction tryStart; - public Instruction tryEnd; - public TryBlockGroup blockGroup; - } - - private Dictionary BuildInstruction2Index() - { - IList instructions = _method.Body.Instructions; - var inst2Index = new Dictionary(instructions.Count); - for (int i = 0; i < instructions.Count; i++) - { - Instruction inst = instructions[i]; - inst2Index.Add(inst, i); - } - return inst2Index; - } - - private BlockGroup SplitBasicBlockGroup() - { - Dictionary inst2Index = BuildInstruction2Index(); - var inst2blockGroup = new Dictionary(); - - List instructions = (List)_method.Body.Instructions; - - var tryBlocks = new List(); - foreach (var ex in _method.Body.ExceptionHandlers) - { - TryBlockInfo tryBlock = tryBlocks.Find(tryBlocks => tryBlocks.tryStart == ex.TryStart && tryBlocks.tryEnd == ex.TryEnd); - if (tryBlock == null) - { - int startIndex = inst2Index[ex.TryStart]; - int endIndex = ex.TryEnd != null ? inst2Index[ex.TryEnd] : inst2Index.Count; - TryBlockGroup blockGroup = new TryBlockGroup(instructions.GetRange(startIndex, endIndex - startIndex), inst2blockGroup); - tryBlock = new TryBlockInfo - { - tryStart = ex.TryStart, - tryEnd = ex.TryEnd, - blockGroup = blockGroup, - }; - tryBlocks.Add(tryBlock); - } - if (ex.FilterStart != null) - { - int filterStartIndex = inst2Index[ex.FilterStart]; - int filterEndIndex = ex.HandlerStart != null ? inst2Index[ex.HandlerStart] : inst2Index.Count; - int handlerStartIndex = filterEndIndex; - int handlerEndIndex = ex.HandlerEnd != null ? inst2Index[ex.HandlerEnd] : inst2Index.Count; - var filterHandlerGroup = new ExceptionHandlerWithFilterGroup(ex, - instructions.GetRange(filterStartIndex, filterEndIndex - filterStartIndex), - instructions.GetRange(handlerStartIndex, handlerEndIndex - handlerStartIndex), - instructions.GetRange(filterStartIndex, handlerEndIndex - filterStartIndex), inst2blockGroup); - } - else - { - int handlerStartIndex = inst2Index[ex.HandlerStart]; - int handlerEndIndex = ex.HandlerEnd != null ? inst2Index[ex.HandlerEnd] : inst2Index.Count; - ExceptionHandlerGroup handlerGroup = new ExceptionHandlerGroup(ex, instructions.GetRange(handlerStartIndex, handlerEndIndex - handlerStartIndex), inst2blockGroup); - } - } - var rootGroup = new BlockGroup(new List(instructions), inst2blockGroup); - rootGroup.SplitInstructionsNotInAnySubGroupsToIndividualGroups(inst2blockGroup); - - rootGroup.ComputeBasicBlocks(BuildInstructionToBasicBlockInfoDic()); - return rootGroup; - } - - private void FixInstructionTargets() - { - var inst2bb = BuildInstructionToBasicBlockInfoDic(); - foreach (var ex in _method.Body.ExceptionHandlers) - { - if (ex.TryStart != null) - { - ex.TryStart = inst2bb[ex.TryStart].GroupFirstInstruction; - } - if (ex.TryEnd != null) - { - ex.TryEnd = inst2bb[ex.TryEnd].GroupFirstInstruction; - } - if (ex.HandlerStart != null) - { - ex.HandlerStart = inst2bb[ex.HandlerStart].GroupFirstInstruction; - } - if (ex.HandlerEnd != null) - { - ex.HandlerEnd = inst2bb[ex.HandlerEnd].GroupFirstInstruction; - } - if (ex.FilterStart != null) - { - ex.FilterStart = inst2bb[ex.FilterStart].GroupFirstInstruction; - } - } - //foreach (var inst in inst2bb.Keys) - //{ - // if (inst.Operand is Instruction targetInst) - // { - // inst.Operand = inst2bb[targetInst].FirstInstruction; - // } - // else if (inst.Operand is Instruction[] targetInsts) - // { - // for (int i = 0; i < targetInsts.Length; i++) - // { - // targetInsts[i] = inst2bb[targetInsts[i]].FirstInstruction; - // } - // } - //} - } - - private void BuildInstructions() - { - IList methodInstructions = _method.Body.Instructions; - methodInstructions.Clear(); - for (BasicBlockInfo cur = _bbHead.next; cur != null; cur = cur.next) - { - foreach (Instruction inst in cur.instructions) - { - methodInstructions.Add(inst); - } - } - _method.Body.InitLocals = true; - //_method.Body.MaxStack = Math.Max(_method.Body.MaxStack , (ushort)1); // TODO: set to a reasonable value - //_method.Body.KeepOldMaxStack = true; - //_method.Body.UpdateInstructionOffsets(); - } - - public bool TryObfus() - { - // TODO: TEMP - //if (_method.Body.HasExceptionHandlers) - //{ - // return false; - //} - var evc = new EvalStackCalculator(_method); - BuildBasicBlockLink(evc); - if (!CheckNotContainsNotSupportedEvalStackData()) - { - Debug.LogError($"Method {_method.FullName} contains unsupported EvalStackData, obfuscation skipped."); - return false; - } - BlockGroup rootGroup = SplitBasicBlockGroup(); - if (rootGroup.basicBlocks != null && rootGroup.basicBlocks.Count == 1) - { - return false; - } - ComputeInputOutputArguments(); - AdjustInputOutputEvalStack(); - InsertBrInstructionForConjoinedBasicBlocks(); - InsertSwitchMachineBasicBlockForGroups(rootGroup); - - FixInstructionTargets(); - BuildInstructions(); - return true; - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ControlFlowObfus/MethodControlFlowCalculator.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ControlFlowObfus/MethodControlFlowCalculator.cs.meta deleted file mode 100644 index 059febf0..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ControlFlowObfus/MethodControlFlowCalculator.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 144b6474de40382498899f8b1c7f92a3 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/EvalStackObfus.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/EvalStackObfus.meta deleted file mode 100644 index a52d43d3..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/EvalStackObfus.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 4e82ef0b94e10314cbba0daabfdefe32 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/EvalStackObfus/ConfigurableObfuscationPolicy.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/EvalStackObfus/ConfigurableObfuscationPolicy.cs deleted file mode 100644 index 2284324f..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/EvalStackObfus/ConfigurableObfuscationPolicy.cs +++ /dev/null @@ -1,147 +0,0 @@ -using dnlib.DotNet; -using Obfuz.Conf; -using Obfuz.Settings; -using Obfuz.Utils; -using System; -using System.Collections.Generic; -using System.Xml; - -namespace Obfuz.ObfusPasses.EvalStackObfus -{ - struct ObfuscationRuleData - { - public readonly ObfuscationLevel obfuscationLevel; - public readonly float obfuscationPercentage; - public ObfuscationRuleData(ObfuscationLevel level, float percentage) - { - obfuscationLevel = level; - obfuscationPercentage = percentage; - } - } - - interface IObfuscationPolicy - { - bool NeedObfuscate(MethodDef method); - - ObfuscationRuleData GetObfuscationRuleData(MethodDef method); - } - - abstract class ObfuscationPolicyBase : IObfuscationPolicy - { - public abstract bool NeedObfuscate(MethodDef method); - - public abstract ObfuscationRuleData GetObfuscationRuleData(MethodDef method); - } - - class ConfigurableObfuscationPolicy : ObfuscationPolicyBase - { - class ObfuscationRule : IRule - { - public ObfuscationLevel? obfuscationLevel; - public float? obfuscationPercentage; - - public void InheritParent(ObfuscationRule parentRule) - { - if (obfuscationLevel == null) - obfuscationLevel = parentRule.obfuscationLevel; - if (obfuscationPercentage == null) - obfuscationPercentage = parentRule.obfuscationPercentage; - } - } - - class MethodSpec : MethodRuleBase - { - } - - class TypeSpec : TypeRuleBase - { - } - - class AssemblySpec : AssemblyRuleBase - { - } - - private static readonly ObfuscationRule s_default = new ObfuscationRule() - { - obfuscationLevel = ObfuscationLevel.Basic, - obfuscationPercentage = 0.05f, - }; - - private ObfuscationRule _global; - - private readonly XmlAssemblyTypeMethodRuleParser _xmlParser; - - private readonly Dictionary _methodRuleCache = new Dictionary(); - - public ConfigurableObfuscationPolicy(List toObfuscatedAssemblyNames, List xmlConfigFiles) - { - _xmlParser = new XmlAssemblyTypeMethodRuleParser( - toObfuscatedAssemblyNames, ParseObfuscationRule, ParseGlobal); - LoadConfigs(xmlConfigFiles); - } - - private void LoadConfigs(List configFiles) - { - _xmlParser.LoadConfigs(configFiles); - - if (_global == null) - { - _global = s_default; - } - else - { - _global.InheritParent(s_default); - } - if (_global.obfuscationPercentage.Value > 0.1f) - { - UnityEngine.Debug.LogWarning($"EvalStackObfus significantly increases the size of the obfuscated hot-update DLL. It is recommended to keep the obfuscationPercentage ≤ 0.1 (currently set to {_global.obfuscationPercentage.Value})."); - } - _xmlParser.InheritParentRules(_global); - } - - private void ParseGlobal(string configFile, XmlElement ele) - { - switch (ele.Name) - { - case "global": _global = ParseObfuscationRule(configFile, ele); break; - default: throw new Exception($"Invalid xml file {configFile}, unknown node {ele.Name}"); - } - } - - private ObfuscationRule ParseObfuscationRule(string configFile, XmlElement ele) - { - var rule = new ObfuscationRule(); - if (ele.HasAttribute("obfuscationLevel")) - { - rule.obfuscationLevel = ConfigUtil.ParseObfuscationLevel(ele.GetAttribute("obfuscationLevel")); - } - if (ele.HasAttribute("obfuscationPercentage")) - { - rule.obfuscationPercentage = float.Parse(ele.GetAttribute("obfuscationPercentage")); - } - return rule; - } - - private ObfuscationRule GetMethodObfuscationRule(MethodDef method) - { - if (!_methodRuleCache.TryGetValue(method, out var rule)) - { - rule = _xmlParser.GetMethodRule(method, _global); - _methodRuleCache[method] = rule; - } - return rule; - } - - public override bool NeedObfuscate(MethodDef method) - { - ObfuscationRule rule = GetMethodObfuscationRule(method); - return rule.obfuscationLevel.Value > ObfuscationLevel.None; - } - - public override ObfuscationRuleData GetObfuscationRuleData(MethodDef method) - { - var rule = GetMethodObfuscationRule(method); - return new ObfuscationRuleData(rule.obfuscationLevel.Value, rule.obfuscationPercentage.Value); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/EvalStackObfus/ConfigurableObfuscationPolicy.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/EvalStackObfus/ConfigurableObfuscationPolicy.cs.meta deleted file mode 100644 index e9520c4e..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/EvalStackObfus/ConfigurableObfuscationPolicy.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 8a2603d51f31a134d90599d33664f6c7 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/EvalStackObfus/DefaultObfuscator.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/EvalStackObfus/DefaultObfuscator.cs deleted file mode 100644 index d9b91838..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/EvalStackObfus/DefaultObfuscator.cs +++ /dev/null @@ -1,225 +0,0 @@ -using dnlib.DotNet.Emit; -using Obfuz.Utils; -using System.Collections.Generic; - -namespace Obfuz.ObfusPasses.EvalStackObfus -{ - class DefaultObfuscator : ObfuscatorBase - { - public override bool ObfuscateInt(Instruction inst, List outputInsts, ObfusMethodContext ctx) - { - IRandom random = ctx.localRandom; - switch (random.NextInt(4)) - { - case 0: - { - // x = x + a - int a = 0; - float constProbability = 0f; - ConstObfusUtil.LoadConstInt(a, random, constProbability, ctx.constFieldAllocator, outputInsts); - outputInsts.Add(Instruction.Create(OpCodes.Add)); - return true; - } - case 1: - { - // x = x * a * ra - int a = random.NextInt() | 0x1; // Ensure a is not zero - int ra = MathUtil.ModInverse32(a); - float constProbability = 0.5f; - ConstObfusUtil.LoadConstInt(a, random, constProbability, ctx.constFieldAllocator, outputInsts); - outputInsts.Add(Instruction.Create(OpCodes.Mul)); - ConstObfusUtil.LoadConstInt(ra, random, constProbability, ctx.constFieldAllocator, outputInsts); - outputInsts.Add(Instruction.Create(OpCodes.Mul)); - return true; - } - case 2: - { - // x = (x * a + b) * ra - (b * ra) - int a = random.NextInt() | 0x1; // Ensure a is not zero - int ra = MathUtil.ModInverse32(a); - int b = random.NextInt(); - int b_ra = -b * ra; - float constProbability = 0.5f; - ConstObfusUtil.LoadConstInt(a, random, constProbability, ctx.constFieldAllocator, outputInsts); - outputInsts.Add(Instruction.Create(OpCodes.Mul)); - ConstObfusUtil.LoadConstInt(b, random, constProbability, ctx.constFieldAllocator, outputInsts); - outputInsts.Add(Instruction.Create(OpCodes.Add)); - ConstObfusUtil.LoadConstInt(ra, random, constProbability, ctx.constFieldAllocator, outputInsts); - outputInsts.Add(Instruction.Create(OpCodes.Mul)); - ConstObfusUtil.LoadConstInt(b_ra, random, constProbability, ctx.constFieldAllocator, outputInsts); - outputInsts.Add(Instruction.Create(OpCodes.Add)); - return true; - } - case 3: - { - // x = ((x + a) * b + c) * rb - (a*b + c) * rb - int a = random.NextInt(); - int b = random.NextInt() | 0x1; // Ensure b is not zero - int rb = MathUtil.ModInverse32(b); - int c = random.NextInt(); - int r = -(a * b + c) * rb; - float constProbability = 0.5f; - ConstObfusUtil.LoadConstInt(a, random, constProbability, ctx.constFieldAllocator, outputInsts); - outputInsts.Add(Instruction.Create(OpCodes.Add)); - ConstObfusUtil.LoadConstInt(b, random, constProbability, ctx.constFieldAllocator, outputInsts); - outputInsts.Add(Instruction.Create(OpCodes.Mul)); - ConstObfusUtil.LoadConstInt(c, random, constProbability, ctx.constFieldAllocator, outputInsts); - outputInsts.Add(Instruction.Create(OpCodes.Add)); - ConstObfusUtil.LoadConstInt(rb, random, constProbability, ctx.constFieldAllocator, outputInsts); - outputInsts.Add(Instruction.Create(OpCodes.Mul)); - ConstObfusUtil.LoadConstInt(r, random, constProbability, ctx.constFieldAllocator, outputInsts); - outputInsts.Add(Instruction.Create(OpCodes.Add)); - return true; - } - default: return false; - } - } - - public override bool ObfuscateLong(Instruction inst, List outputInsts, ObfusMethodContext ctx) - { - IRandom random = ctx.localRandom; - switch (random.NextInt(4)) - { - case 0: - { - // x = x + a - long a = 0; - float constProbability = 0f; - ConstObfusUtil.LoadConstLong(a, random, constProbability, ctx.constFieldAllocator, outputInsts); - outputInsts.Add(Instruction.Create(OpCodes.Add)); - return true; - } - case 1: - { - // x = x * a * ra - long a = random.NextLong() | 0x1L; // Ensure a is not zero - long ra = MathUtil.ModInverse64(a); - float constProbability = 0.5f; - ConstObfusUtil.LoadConstLong(a, random, constProbability, ctx.constFieldAllocator, outputInsts); - outputInsts.Add(Instruction.Create(OpCodes.Mul)); - ConstObfusUtil.LoadConstLong(ra, random, constProbability, ctx.constFieldAllocator, outputInsts); - outputInsts.Add(Instruction.Create(OpCodes.Mul)); - return true; - } - case 2: - { - // x = (x * a + b) * ra - (b * ra) - long a = random.NextLong() | 0x1L; // Ensure a is not zero - long ra = MathUtil.ModInverse64(a); - long b = random.NextLong(); - long b_ra = -b * ra; - float constProbability = 0.5f; - ConstObfusUtil.LoadConstLong(a, random, constProbability, ctx.constFieldAllocator, outputInsts); - outputInsts.Add(Instruction.Create(OpCodes.Mul)); - ConstObfusUtil.LoadConstLong(b, random, constProbability, ctx.constFieldAllocator, outputInsts); - outputInsts.Add(Instruction.Create(OpCodes.Add)); - ConstObfusUtil.LoadConstLong(ra, random, constProbability, ctx.constFieldAllocator, outputInsts); - outputInsts.Add(Instruction.Create(OpCodes.Mul)); - ConstObfusUtil.LoadConstLong(b_ra, random, constProbability, ctx.constFieldAllocator, outputInsts); - outputInsts.Add(Instruction.Create(OpCodes.Add)); - return true; - } - case 3: - { - // x = ((x + a) * b + c) * rb - (a*b + c) * rb - long a = random.NextLong(); - long b = random.NextLong() | 0x1L; // Ensure b is not zero - long rb = MathUtil.ModInverse64(b); - long c = random.NextLong(); - long r = -(a * b + c) * rb; - float constProbability = 0.5f; - ConstObfusUtil.LoadConstLong(a, random, constProbability, ctx.constFieldAllocator, outputInsts); - outputInsts.Add(Instruction.Create(OpCodes.Add)); - ConstObfusUtil.LoadConstLong(b, random, constProbability, ctx.constFieldAllocator, outputInsts); - outputInsts.Add(Instruction.Create(OpCodes.Mul)); - ConstObfusUtil.LoadConstLong(c, random, constProbability, ctx.constFieldAllocator, outputInsts); - outputInsts.Add(Instruction.Create(OpCodes.Add)); - ConstObfusUtil.LoadConstLong(rb, random, constProbability, ctx.constFieldAllocator, outputInsts); - outputInsts.Add(Instruction.Create(OpCodes.Mul)); - ConstObfusUtil.LoadConstLong(r, random, constProbability, ctx.constFieldAllocator, outputInsts); - outputInsts.Add(Instruction.Create(OpCodes.Add)); - return true; - } - default: return false; - } - } - - public override bool ObfuscateFloat(Instruction inst, List outputInsts, ObfusMethodContext ctx) - { - IRandom random = ctx.localRandom; - switch (random.NextInt(3)) - { - case 0: - { - // x = x + 0f - float a = 0.0f; - float constProbability = 0f; - ConstObfusUtil.LoadConstFloat(a, random, constProbability, ctx.constFieldAllocator, outputInsts); - outputInsts.Add(Instruction.Create(OpCodes.Add)); - return true; - } - case 1: - { - // x = x * 1f; - float a = 1.0f; - float constProbability = 0f; - ConstObfusUtil.LoadConstFloat(a, random, constProbability, ctx.constFieldAllocator, outputInsts); - outputInsts.Add(Instruction.Create(OpCodes.Mul)); - return true; - } - case 2: - { - // x = (x + a) * b; a = 0.0f, b = 1.0f - float a = 0.0f; - float b = 1.0f; - float constProbability = 0f; - ConstObfusUtil.LoadConstFloat(a, random, constProbability, ctx.constFieldAllocator, outputInsts); - outputInsts.Add(Instruction.Create(OpCodes.Add)); - ConstObfusUtil.LoadConstFloat(b, random, constProbability, ctx.constFieldAllocator, outputInsts); - outputInsts.Add(Instruction.Create(OpCodes.Mul)); - return true; - } - default: return false; - } - } - - public override bool ObfuscateDouble(Instruction inst, List outputInsts, ObfusMethodContext ctx) - { - IRandom random = ctx.localRandom; - switch (random.NextInt(3)) - { - case 0: - { - // x = x + 0.0 - double a = 0.0; - float constProbability = 0f; - ConstObfusUtil.LoadConstDouble(a, random, constProbability, ctx.constFieldAllocator, outputInsts); - outputInsts.Add(Instruction.Create(OpCodes.Add)); - return true; - } - case 1: - { - // x = x * 1.0; - double a = 1.0; - float constProbability = 0f; - ConstObfusUtil.LoadConstDouble(a, random, constProbability, ctx.constFieldAllocator, outputInsts); - outputInsts.Add(Instruction.Create(OpCodes.Mul)); - return true; - } - case 2: - { - // x = (x + a) * b; a = 0.0, b = 1.0 - double a = 0.0; - double b = 1.0; - float constProbability = 0f; - ConstObfusUtil.LoadConstDouble(a, random, constProbability, ctx.constFieldAllocator, outputInsts); - outputInsts.Add(Instruction.Create(OpCodes.Add)); - ConstObfusUtil.LoadConstDouble(b, random, constProbability, ctx.constFieldAllocator, outputInsts); - outputInsts.Add(Instruction.Create(OpCodes.Mul)); - return true; - } - default: return false; - } - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/EvalStackObfus/DefaultObfuscator.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/EvalStackObfus/DefaultObfuscator.cs.meta deleted file mode 100644 index d6a01e4e..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/EvalStackObfus/DefaultObfuscator.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 5200244f403139c40b578b2e845508f2 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/EvalStackObfus/EvalStackObfusPass.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/EvalStackObfus/EvalStackObfusPass.cs deleted file mode 100644 index 27697ad7..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/EvalStackObfus/EvalStackObfusPass.cs +++ /dev/null @@ -1,114 +0,0 @@ -using dnlib.DotNet; -using dnlib.DotNet.Emit; -using Obfuz.Data; -using Obfuz.Emit; -using Obfuz.Settings; -using Obfuz.Utils; -using System.Collections.Generic; - -namespace Obfuz.ObfusPasses.EvalStackObfus -{ - class ObfusMethodContext - { - public MethodDef method; - public EvalStackCalculator evalStackCalculator; - public LocalVariableAllocator localVariableAllocator; - public IRandom localRandom; - public EncryptionScopeInfo encryptionScope; - public DefaultMetadataImporter importer; - public ConstFieldAllocator constFieldAllocator; - public float obfuscationPercentage; - } - - internal class EvalStackObfusPass : ObfuscationMethodPassBase - { - private readonly EvalStackObfuscationSettingsFacade _settings; - - private IObfuscationPolicy _obfuscationPolicy; - private IObfuscator _obfuscator; - - public EvalStackObfusPass(EvalStackObfuscationSettingsFacade settings) - { - _settings = settings; - _obfuscator = new DefaultObfuscator(); - } - - public override ObfuscationPassType Type => ObfuscationPassType.EvalStackObfus; - - public override void Start() - { - ObfuscationPassContext ctx = ObfuscationPassContext.Current; - _obfuscationPolicy = new ConfigurableObfuscationPolicy( - ctx.coreSettings.assembliesToObfuscate, - _settings.ruleFiles); - } - - public override void Stop() - { - - } - - protected override bool NeedObfuscateMethod(MethodDef method) - { - return _obfuscationPolicy.NeedObfuscate(method); - } - - protected bool TryObfuscateInstruction(Instruction inst, EvalDataType dataType, List outputInstructions, ObfusMethodContext ctx) - { - switch (dataType) - { - case EvalDataType.Int32: return _obfuscator.ObfuscateInt(inst, outputInstructions, ctx); - case EvalDataType.Int64: return _obfuscator.ObfuscateLong(inst, outputInstructions, ctx); - case EvalDataType.Float: return _obfuscator.ObfuscateFloat(inst, outputInstructions, ctx); - case EvalDataType.Double: return _obfuscator.ObfuscateDouble(inst, outputInstructions, ctx); - default: return false; - } - } - - protected override void ObfuscateData(MethodDef method) - { - //Debug.Log($"Obfuscating method: {method.FullName} with EvalStackObfusPass"); - IList instructions = method.Body.Instructions; - var outputInstructions = new List(); - var totalFinalInstructions = new List(); - - ObfuscationPassContext ctx = ObfuscationPassContext.Current; - var calc = new EvalStackCalculator(method); - - GroupByModuleEntityManager moduleEntityManager = ctx.moduleEntityManager; - var encryptionScope = moduleEntityManager.EncryptionScopeProvider.GetScope(method.Module); - var ruleData = _obfuscationPolicy.GetObfuscationRuleData(method); - var localRandom = encryptionScope.localRandomCreator(MethodEqualityComparer.CompareDeclaringTypes.GetHashCode(method)); - var obfusMethodCtx = new ObfusMethodContext - { - method = method, - evalStackCalculator = calc, - localVariableAllocator = new LocalVariableAllocator(method), - encryptionScope = encryptionScope, - constFieldAllocator = moduleEntityManager.GetEntity(method.Module), - localRandom = localRandom, - importer = moduleEntityManager.GetEntity(method.Module), - obfuscationPercentage = ruleData.obfuscationPercentage, - }; - for (int i = 0; i < instructions.Count; i++) - { - Instruction inst = instructions[i]; - totalFinalInstructions.Add(inst); - if (calc.TryGetPushResult(inst, out EvalDataType dataType) && localRandom.NextInPercentage(ruleData.obfuscationPercentage)) - { - outputInstructions.Clear(); - if (TryObfuscateInstruction(inst, dataType, outputInstructions, obfusMethodCtx)) - { - totalFinalInstructions.AddRange(outputInstructions); - } - } - } - - instructions.Clear(); - foreach (var obInst in totalFinalInstructions) - { - instructions.Add(obInst); - } - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/EvalStackObfus/EvalStackObfusPass.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/EvalStackObfus/EvalStackObfusPass.cs.meta deleted file mode 100644 index 63a3a0c5..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/EvalStackObfus/EvalStackObfusPass.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 9fa7d3313f260794da2cc36dadaf4fb4 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/EvalStackObfus/IObfuscator.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/EvalStackObfus/IObfuscator.cs deleted file mode 100644 index 79f8ff09..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/EvalStackObfus/IObfuscator.cs +++ /dev/null @@ -1,24 +0,0 @@ -using dnlib.DotNet.Emit; -using System.Collections.Generic; - -namespace Obfuz.ObfusPasses.EvalStackObfus -{ - interface IObfuscator - { - bool ObfuscateInt(Instruction inst, List outputInsts, ObfusMethodContext ctx); - - bool ObfuscateLong(Instruction inst, List outputInsts, ObfusMethodContext ctx); - - bool ObfuscateFloat(Instruction inst, List outputInsts, ObfusMethodContext ctx); - - bool ObfuscateDouble(Instruction inst, List outputInsts, ObfusMethodContext ctx); - } - - abstract class ObfuscatorBase : IObfuscator - { - public abstract bool ObfuscateInt(Instruction inst, List outputInsts, ObfusMethodContext ctx); - public abstract bool ObfuscateLong(Instruction inst, List outputInsts, ObfusMethodContext ctx); - public abstract bool ObfuscateFloat(Instruction inst, List outputInsts, ObfusMethodContext ctx); - public abstract bool ObfuscateDouble(Instruction inst, List outputInsts, ObfusMethodContext ctx); - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/EvalStackObfus/IObfuscator.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/EvalStackObfus/IObfuscator.cs.meta deleted file mode 100644 index a782f110..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/EvalStackObfus/IObfuscator.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 17a9f3181d9711f4ca1d0cfb9e813bb0 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ExprObfus.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ExprObfus.meta deleted file mode 100644 index 24080ec4..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ExprObfus.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 9fdb2c243b1ea0f489e67233fda287c9 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ExprObfus/ConfigurableObfuscationPolicy.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ExprObfus/ConfigurableObfuscationPolicy.cs deleted file mode 100644 index 73929f1e..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ExprObfus/ConfigurableObfuscationPolicy.cs +++ /dev/null @@ -1,143 +0,0 @@ -using dnlib.DotNet; -using Obfuz.Conf; -using Obfuz.Settings; -using Obfuz.Utils; -using System; -using System.Collections.Generic; -using System.Xml; - -namespace Obfuz.ObfusPasses.ExprObfus -{ - struct ObfuscationRuleData - { - public readonly ObfuscationLevel obfuscationLevel; - public readonly float obfuscationPercentage; - public ObfuscationRuleData(ObfuscationLevel level, float percentage) - { - obfuscationLevel = level; - obfuscationPercentage = percentage; - } - } - - interface IObfuscationPolicy - { - bool NeedObfuscate(MethodDef method); - - ObfuscationRuleData GetObfuscationRuleData(MethodDef method); - } - - abstract class ObfuscationPolicyBase : IObfuscationPolicy - { - public abstract bool NeedObfuscate(MethodDef method); - - public abstract ObfuscationRuleData GetObfuscationRuleData(MethodDef method); - } - - class ConfigurableObfuscationPolicy : ObfuscationPolicyBase - { - class ObfuscationRule : IRule - { - public ObfuscationLevel? obfuscationLevel; - public float? obfuscationPercentage; - - public void InheritParent(ObfuscationRule parentRule) - { - if (obfuscationLevel == null) - obfuscationLevel = parentRule.obfuscationLevel; - if (obfuscationPercentage == null) - obfuscationPercentage = parentRule.obfuscationPercentage; - } - } - - class MethodSpec : MethodRuleBase - { - } - - class TypeSpec : TypeRuleBase - { - } - - class AssemblySpec : AssemblyRuleBase - { - } - - private static readonly ObfuscationRule s_default = new ObfuscationRule() - { - obfuscationLevel = ObfuscationLevel.Basic, - obfuscationPercentage = 0.3f, - }; - - private ObfuscationRule _global; - - private readonly XmlAssemblyTypeMethodRuleParser _xmlParser; - - private readonly Dictionary _methodRuleCache = new Dictionary(); - - public ConfigurableObfuscationPolicy(List toObfuscatedAssemblyNames, List xmlConfigFiles) - { - _xmlParser = new XmlAssemblyTypeMethodRuleParser( - toObfuscatedAssemblyNames, ParseObfuscationRule, ParseGlobal); - LoadConfigs(xmlConfigFiles); - } - - private void LoadConfigs(List configFiles) - { - _xmlParser.LoadConfigs(configFiles); - - if (_global == null) - { - _global = s_default; - } - else - { - _global.InheritParent(s_default); - } - _xmlParser.InheritParentRules(_global); - } - - private void ParseGlobal(string configFile, XmlElement ele) - { - switch (ele.Name) - { - case "global": _global = ParseObfuscationRule(configFile, ele); break; - default: throw new Exception($"Invalid xml file {configFile}, unknown node {ele.Name}"); - } - } - - private ObfuscationRule ParseObfuscationRule(string configFile, XmlElement ele) - { - var rule = new ObfuscationRule(); - if (ele.HasAttribute("obfuscationLevel")) - { - rule.obfuscationLevel = ConfigUtil.ParseObfuscationLevel(ele.GetAttribute("obfuscationLevel")); - } - if (ele.HasAttribute("obfuscationPercentage")) - { - rule.obfuscationPercentage = float.Parse(ele.GetAttribute("obfuscationPercentage")); - } - return rule; - } - - private ObfuscationRule GetMethodObfuscationRule(MethodDef method) - { - if (!_methodRuleCache.TryGetValue(method, out var rule)) - { - rule = _xmlParser.GetMethodRule(method, _global); - _methodRuleCache[method] = rule; - } - return rule; - } - - public override bool NeedObfuscate(MethodDef method) - { - ObfuscationRule rule = GetMethodObfuscationRule(method); - return rule.obfuscationLevel.Value > ObfuscationLevel.None; - } - - public override ObfuscationRuleData GetObfuscationRuleData(MethodDef method) - { - var rule = GetMethodObfuscationRule(method); - return new ObfuscationRuleData(rule.obfuscationLevel.Value, rule.obfuscationPercentage.Value); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ExprObfus/ConfigurableObfuscationPolicy.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ExprObfus/ConfigurableObfuscationPolicy.cs.meta deleted file mode 100644 index 2e67a4f5..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ExprObfus/ConfigurableObfuscationPolicy.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 5f820a225c981b8499016958e6c69747 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ExprObfus/ExprObfusPass.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ExprObfus/ExprObfusPass.cs deleted file mode 100644 index 1a540e64..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ExprObfus/ExprObfusPass.cs +++ /dev/null @@ -1,173 +0,0 @@ -using dnlib.DotNet; -using dnlib.DotNet.Emit; -using Obfuz.Data; -using Obfuz.Emit; -using Obfuz.ObfusPasses.ExprObfus.Obfuscators; -using Obfuz.Settings; -using Obfuz.Utils; -using System.Collections.Generic; - -namespace Obfuz.ObfusPasses.ExprObfus -{ - class ObfusMethodContext - { - public MethodDef method; - public EvalStackCalculator evalStackCalculator; - public LocalVariableAllocator localVariableAllocator; - public IRandom localRandom; - public EncryptionScopeInfo encryptionScope; - public DefaultMetadataImporter importer; - public ConstFieldAllocator constFieldAllocator; - public float obfuscationPercentage; - } - - class ExprObfusPass : ObfuscationMethodPassBase - { - private readonly ExprObfuscationSettingsFacade _settings; - private readonly IObfuscator _basicObfuscator; - private readonly IObfuscator _advancedObfuscator; - private readonly IObfuscator _mostAdvancedObfuscator; - - private IObfuscationPolicy _obfuscationPolicy; - - public ExprObfusPass(ExprObfuscationSettingsFacade settings) - { - _settings = settings; - _basicObfuscator = new BasicObfuscator(); - _advancedObfuscator = new AdvancedObfuscator(); - _mostAdvancedObfuscator = new MostAdvancedObfuscator(); - } - - public override ObfuscationPassType Type => ObfuscationPassType.ExprObfus; - - public override void Start() - { - ObfuscationPassContext ctx = ObfuscationPassContext.Current; - _obfuscationPolicy = new ConfigurableObfuscationPolicy( - ctx.coreSettings.assembliesToObfuscate, - _settings.ruleFiles); - } - - private IObfuscator GetObfuscator(ObfuscationLevel level) - { - switch (level) - { - case ObfuscationLevel.None: return null; - case ObfuscationLevel.Basic: return _basicObfuscator; - case ObfuscationLevel.Advanced: return _advancedObfuscator; - case ObfuscationLevel.MostAdvanced: return _mostAdvancedObfuscator; - default: throw new System.ArgumentOutOfRangeException(nameof(level), level, "Unknown obfuscation level"); - } - } - - public override void Stop() - { - - } - - protected override bool NeedObfuscateMethod(MethodDef method) - { - return _obfuscationPolicy.NeedObfuscate(method); - } - - protected bool TryObfuscateInstruction(IObfuscator obfuscator, InstructionParameterInfo pi, Instruction inst, List outputInstructions, ObfusMethodContext ctx) - { - //Debug.Log($"Obfuscating instruction: {inst} in method: {ctx.method.FullName}"); - IRandom localRandom = ctx.localRandom; - float obfuscationPercentage = ctx.obfuscationPercentage; - switch (inst.OpCode.Code) - { - case Code.Neg: - { - return localRandom.NextInPercentage(obfuscationPercentage) && obfuscator.ObfuscateBasicUnaryOp(inst, pi.op1, pi.retType, outputInstructions, ctx); - } - case Code.Add: - case Code.Sub: - case Code.Mul: - case Code.Div: - case Code.Div_Un: - case Code.Rem: - case Code.Rem_Un: - { - return localRandom.NextInPercentage(obfuscationPercentage) && obfuscator.ObfuscateBasicBinOp(inst, pi.op1, pi.op2, pi.retType, outputInstructions, ctx); - } - case Code.And: - case Code.Or: - case Code.Xor: - { - return localRandom.NextInPercentage(obfuscationPercentage) && obfuscator.ObfuscateBinBitwiseOp(inst, pi.op1, pi.op2, pi.retType, outputInstructions, ctx); - } - case Code.Not: - { - return localRandom.NextInPercentage(obfuscationPercentage) && obfuscator.ObfuscateUnaryBitwiseOp(inst, pi.op1, pi.retType, outputInstructions, ctx); - } - case Code.Shl: - case Code.Shr: - case Code.Shr_Un: - { - return localRandom.NextInPercentage(obfuscationPercentage) && obfuscator.ObfuscateBitShiftOp(inst, pi.op1, pi.op2, pi.retType, outputInstructions, ctx); - } - } - return false; - } - - protected override void ObfuscateData(MethodDef method) - { - //Debug.Log($"Obfuscating method: {method.FullName} with ExprObfusPass"); - IList instructions = method.Body.Instructions; - var outputInstructions = new List(); - var totalFinalInstructions = new List(); - - ObfuscationPassContext ctx = ObfuscationPassContext.Current; - var calc = new EvalStackCalculator(method); - - GroupByModuleEntityManager moduleEntityManager = ctx.moduleEntityManager; - var encryptionScope = moduleEntityManager.EncryptionScopeProvider.GetScope(method.Module); - var ruleData = _obfuscationPolicy.GetObfuscationRuleData(method); - var obfuscator = GetObfuscator(ruleData.obfuscationLevel); - var obfusMethodCtx = new ObfusMethodContext - { - method = method, - evalStackCalculator = calc, - localVariableAllocator = new LocalVariableAllocator(method), - encryptionScope = encryptionScope, - constFieldAllocator = moduleEntityManager.GetEntity(method.Module), - localRandom = encryptionScope.localRandomCreator(MethodEqualityComparer.CompareDeclaringTypes.GetHashCode(method)), - importer = moduleEntityManager.GetEntity(method.Module), - obfuscationPercentage = ruleData.obfuscationPercentage, - }; - for (int i = 0; i < instructions.Count; i++) - { - Instruction inst = instructions[i]; - bool add = false; - if (calc.TryGetParameterInfo(inst, out InstructionParameterInfo pi)) - { - outputInstructions.Clear(); - if (TryObfuscateInstruction(obfuscator, pi, inst, outputInstructions, obfusMethodCtx)) - { - // current instruction may be the target of control flow instruction, so we can't remove it directly. - // we replace it with nop now, then remove it in CleanUpInstructionPass - inst.OpCode = outputInstructions[0].OpCode; - inst.Operand = outputInstructions[0].Operand; - totalFinalInstructions.Add(inst); - for (int k = 1; k < outputInstructions.Count; k++) - { - totalFinalInstructions.Add(outputInstructions[k]); - } - add = true; - } - } - if (!add) - { - totalFinalInstructions.Add(inst); - } - } - - instructions.Clear(); - foreach (var obInst in totalFinalInstructions) - { - instructions.Add(obInst); - } - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ExprObfus/ExprObfusPass.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ExprObfus/ExprObfusPass.cs.meta deleted file mode 100644 index f108ce32..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ExprObfus/ExprObfusPass.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 477e081ffc0072e4fa1a06100269e4a3 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ExprObfus/IObfuscator.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ExprObfus/IObfuscator.cs deleted file mode 100644 index 605f6438..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ExprObfus/IObfuscator.cs +++ /dev/null @@ -1,28 +0,0 @@ -using dnlib.DotNet.Emit; -using Obfuz.Emit; -using System.Collections.Generic; - -namespace Obfuz.ObfusPasses.ExprObfus -{ - interface IObfuscator - { - bool ObfuscateBasicUnaryOp(Instruction inst, EvalDataType op, EvalDataType ret, List outputInsts, ObfusMethodContext ctx); - - bool ObfuscateBasicBinOp(Instruction inst, EvalDataType op1, EvalDataType op2, EvalDataType ret, List outputInsts, ObfusMethodContext ctx); - - bool ObfuscateUnaryBitwiseOp(Instruction inst, EvalDataType op, EvalDataType ret, List outputInsts, ObfusMethodContext ctx); - - bool ObfuscateBinBitwiseOp(Instruction inst, EvalDataType op1, EvalDataType op2, EvalDataType ret, List outputInsts, ObfusMethodContext ctx); - - bool ObfuscateBitShiftOp(Instruction inst, EvalDataType op1, EvalDataType op2, EvalDataType ret, List outputInsts, ObfusMethodContext ctx); - } - - abstract class ObfuscatorBase : IObfuscator - { - public abstract bool ObfuscateBasicUnaryOp(Instruction inst, EvalDataType op, EvalDataType ret, List outputInsts, ObfusMethodContext ctx); - public abstract bool ObfuscateBasicBinOp(Instruction inst, EvalDataType op1, EvalDataType op2, EvalDataType ret, List outputInsts, ObfusMethodContext ctx); - public abstract bool ObfuscateUnaryBitwiseOp(Instruction inst, EvalDataType op, EvalDataType ret, List outputInsts, ObfusMethodContext ctx); - public abstract bool ObfuscateBinBitwiseOp(Instruction inst, EvalDataType op1, EvalDataType op2, EvalDataType ret, List outputInsts, ObfusMethodContext ctx); - public abstract bool ObfuscateBitShiftOp(Instruction inst, EvalDataType op1, EvalDataType op2, EvalDataType ret, List outputInsts, ObfusMethodContext ctx); - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ExprObfus/IObfuscator.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ExprObfus/IObfuscator.cs.meta deleted file mode 100644 index a72c8645..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ExprObfus/IObfuscator.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: a88981a87bcd9e84b883e39c81cfbf44 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ExprObfus/Obfuscators.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ExprObfus/Obfuscators.meta deleted file mode 100644 index dde5f438..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ExprObfus/Obfuscators.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 4c5dc8736831c9f4b934c69f7894a412 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ExprObfus/Obfuscators/AdvancedObfuscator.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ExprObfus/Obfuscators/AdvancedObfuscator.cs deleted file mode 100644 index f055962a..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ExprObfus/Obfuscators/AdvancedObfuscator.cs +++ /dev/null @@ -1,110 +0,0 @@ -using dnlib.DotNet.Emit; -using Obfuz.Data; -using Obfuz.Emit; -using Obfuz.Utils; -using System.Collections.Generic; - -namespace Obfuz.ObfusPasses.ExprObfus.Obfuscators -{ - class AdvancedObfuscator : BasicObfuscator - { - protected bool GenerateIdentityTransformForArgument(Instruction inst, EvalDataType op, List outputInsts, ObfusMethodContext ctx) - { - IRandom random = ctx.localRandom; - ConstFieldAllocator constFieldAllocator = ctx.constFieldAllocator; - switch (op) - { - case EvalDataType.Int32: - { - // = x + y = x + (y * a + b) * ra + (-b * ra) - int a = random.NextInt() | 0x1; - int ra = MathUtil.ModInverse32(a); - int b = random.NextInt(); - int b_ra = -b * ra; - float constProbability = 0.5f; - ConstObfusUtil.LoadConstInt(a, random, constProbability, constFieldAllocator, outputInsts); - outputInsts.Add(Instruction.Create(OpCodes.Mul)); - ConstObfusUtil.LoadConstInt(b, random, constProbability, constFieldAllocator, outputInsts); - outputInsts.Add(Instruction.Create(OpCodes.Add)); - ConstObfusUtil.LoadConstInt(ra, random, constProbability, constFieldAllocator, outputInsts); - outputInsts.Add(Instruction.Create(OpCodes.Mul)); - ConstObfusUtil.LoadConstInt(b_ra, random, constProbability, constFieldAllocator, outputInsts); - outputInsts.Add(Instruction.Create(OpCodes.Add)); - outputInsts.Add(inst.Clone()); - return true; - } - case EvalDataType.Int64: - { - // = x + y = x + (y * a + b) * ra + (-b * ra) - long a = random.NextLong() | 0x1L; - long ra = MathUtil.ModInverse64(a); - long b = random.NextLong(); - long b_ra = -b * ra; - float constProbability = 0.5f; - ConstObfusUtil.LoadConstLong(a, random, constProbability, constFieldAllocator, outputInsts); - outputInsts.Add(Instruction.Create(OpCodes.Mul)); - ConstObfusUtil.LoadConstLong(b, random, constProbability, constFieldAllocator, outputInsts); - outputInsts.Add(Instruction.Create(OpCodes.Add)); - ConstObfusUtil.LoadConstLong(ra, random, constProbability, constFieldAllocator, outputInsts); - outputInsts.Add(Instruction.Create(OpCodes.Mul)); - ConstObfusUtil.LoadConstLong(b_ra, random, constProbability, constFieldAllocator, outputInsts); - outputInsts.Add(Instruction.Create(OpCodes.Add)); - outputInsts.Add(inst.Clone()); - return true; - } - case EvalDataType.Float: - { - // = x + y = x + (y + a) * b; a = 0.0f, b = 1.0f - float a = 0.0f; - float b = 1.0f; - float constProbability = 0f; - ConstObfusUtil.LoadConstFloat(a, random, constProbability, constFieldAllocator, outputInsts); - outputInsts.Add(Instruction.Create(OpCodes.Add)); - ConstObfusUtil.LoadConstFloat(b, random, constProbability, constFieldAllocator, outputInsts); - outputInsts.Add(Instruction.Create(OpCodes.Mul)); - outputInsts.Add(inst.Clone()); - return true; - } - case EvalDataType.Double: - { - // = x + y = x + (y + a) * b; a = 0.0, b = 1.0 - double a = 0.0; - double b = 1.0; - float constProbability = 0f; - ConstObfusUtil.LoadConstDouble(a, random, constProbability, constFieldAllocator, outputInsts); - outputInsts.Add(Instruction.Create(OpCodes.Add)); - ConstObfusUtil.LoadConstDouble(b, random, constProbability, constFieldAllocator, outputInsts); - outputInsts.Add(Instruction.Create(OpCodes.Mul)); - outputInsts.Add(inst.Clone()); - return true; - } - default: return false; - } - } - - public override bool ObfuscateBasicUnaryOp(Instruction inst, EvalDataType op, EvalDataType ret, List outputInsts, ObfusMethodContext ctx) - { - return GenerateIdentityTransformForArgument(inst, op, outputInsts, ctx) || base.ObfuscateBasicUnaryOp(inst, op, ret, outputInsts, ctx); - } - - public override bool ObfuscateBasicBinOp(Instruction inst, EvalDataType op1, EvalDataType op2, EvalDataType ret, List outputInsts, ObfusMethodContext ctx) - { - return GenerateIdentityTransformForArgument(inst, op2, outputInsts, ctx) || base.ObfuscateBasicBinOp(inst, op1, op2, ret, outputInsts, ctx); - } - - public override bool ObfuscateUnaryBitwiseOp(Instruction inst, EvalDataType op, EvalDataType ret, List outputInsts, ObfusMethodContext ctx) - { - return GenerateIdentityTransformForArgument(inst, op, outputInsts, ctx) || base.ObfuscateUnaryBitwiseOp(inst, op, ret, outputInsts, ctx); - } - - public override bool ObfuscateBinBitwiseOp(Instruction inst, EvalDataType op1, EvalDataType op2, EvalDataType ret, List outputInsts, ObfusMethodContext ctx) - { - return GenerateIdentityTransformForArgument(inst, op2, outputInsts, ctx) || base.ObfuscateBinBitwiseOp(inst, op1, op2, ret, outputInsts, ctx); - } - - public override bool ObfuscateBitShiftOp(Instruction inst, EvalDataType op1, EvalDataType op2, EvalDataType ret, List outputInsts, ObfusMethodContext ctx) - { - return GenerateIdentityTransformForArgument(inst, op2, outputInsts, ctx) || base.ObfuscateBitShiftOp(inst, op1, op2, ret, outputInsts, ctx); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ExprObfus/Obfuscators/AdvancedObfuscator.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ExprObfus/Obfuscators/AdvancedObfuscator.cs.meta deleted file mode 100644 index 06cf2c52..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ExprObfus/Obfuscators/AdvancedObfuscator.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ef717515402ca2f41a52db7ea1300f32 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ExprObfus/Obfuscators/BasicObfuscator.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ExprObfus/Obfuscators/BasicObfuscator.cs deleted file mode 100644 index 56e110e4..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ExprObfus/Obfuscators/BasicObfuscator.cs +++ /dev/null @@ -1,282 +0,0 @@ -using dnlib.DotNet; -using dnlib.DotNet.Emit; -using Obfuz.Emit; -using System.Collections.Generic; -using UnityEngine; - -namespace Obfuz.ObfusPasses.ExprObfus.Obfuscators -{ - - class BasicObfuscator : ObfuscatorBase - { - private IMethod GetUnaryOpMethod(DefaultMetadataImporter importer, Code code, EvalDataType op1) - { - switch (code) - { - case Code.Neg: - { - switch (op1) - { - case EvalDataType.Int32: return importer.NegInt; - case EvalDataType.Int64: return importer.NegLong; - case EvalDataType.Float: return importer.NegFloat; - case EvalDataType.Double: return importer.NegDouble; - default: return null; - } - } - case Code.Not: - { - switch (op1) - { - case EvalDataType.Int32: return importer.NotInt; - case EvalDataType.Int64: return importer.NotLong; - default: return null; - } - } - default: return null; - } - } - - private IMethod GetBinaryOpMethod(DefaultMetadataImporter importer, Code code, EvalDataType op1, EvalDataType op2) - { - switch (code) - { - case Code.Add: - { - switch (op1) - { - case EvalDataType.Int32: return op2 == op1 ? importer.AddInt : null; - case EvalDataType.Int64: return op2 == op1 ? importer.AddLong : null; - case EvalDataType.Float: return op2 == op1 ? importer.AddFloat : null; - case EvalDataType.Double: return op2 == op1 ? importer.AddDouble : null; - case EvalDataType.I: - { - switch (op2) - { - case EvalDataType.I: return importer.AddIntPtr; - case EvalDataType.Int32: return importer.AddIntPtrInt; - default: return null; - } - } - default: return null; - } - } - case Code.Sub: - { - switch (op1) - { - case EvalDataType.Int32: return op2 == op1 ? importer.SubtractInt : null; - case EvalDataType.Int64: return op2 == op1 ? importer.SubtractLong : null; - case EvalDataType.Float: return op2 == op1 ? importer.SubtractFloat : null; - case EvalDataType.Double: return op2 == op1 ? importer.SubtractDouble : null; - case EvalDataType.I: - { - switch (op2) - { - case EvalDataType.I: return importer.SubtractIntPtr; - case EvalDataType.Int32: return importer.SubtractIntPtrInt; - default: return null; - } - } - default: return null; - } - } - case Code.Mul: - { - switch (op1) - { - case EvalDataType.Int32: return op2 == op1 ? importer.MultiplyInt : null; - case EvalDataType.Int64: return op2 == op1 ? importer.MultiplyLong : null; - case EvalDataType.Float: return op2 == op1 ? importer.MultiplyFloat : null; - case EvalDataType.Double: return op2 == op1 ? importer.MultiplyDouble : null; - case EvalDataType.I: - { - switch (op2) - { - case EvalDataType.I: return importer.MultiplyIntPtr; - case EvalDataType.Int32: return importer.MultiplyIntPtrInt; - default: return null; - } - } - default: return null; - } - } - case Code.Div: - { - switch (op1) - { - case EvalDataType.Int32: return importer.DivideInt; - case EvalDataType.Int64: return importer.DivideLong; - case EvalDataType.Float: return importer.DivideFloat; - case EvalDataType.Double: return importer.DivideDouble; - default: return null; - } - } - case Code.Div_Un: - { - switch (op1) - { - case EvalDataType.Int32: return importer.DivideUnInt; - case EvalDataType.Int64: return importer.DivideUnLong; - default: return null; - } - } - case Code.Rem: - { - switch (op1) - { - case EvalDataType.Int32: return importer.RemInt; - case EvalDataType.Int64: return importer.RemLong; - case EvalDataType.Float: return importer.RemFloat; - case EvalDataType.Double: return importer.RemDouble; - default: return null; - } - } - case Code.Rem_Un: - { - switch (op1) - { - case EvalDataType.Int32: return importer.RemUnInt; - case EvalDataType.Int64: return importer.RemUnLong; - default: return null; - } - } - case Code.Neg: - { - switch (op1) - { - case EvalDataType.Int32: return importer.NegInt; - case EvalDataType.Int64: return importer.NegLong; - case EvalDataType.Float: return importer.NegFloat; - case EvalDataType.Double: return importer.NegDouble; - default: return null; - } - } - case Code.And: - { - switch (op1) - { - case EvalDataType.Int32: return importer.AndInt; - case EvalDataType.Int64: return importer.AndLong; - default: return null; - } - } - case Code.Or: - { - switch (op1) - { - case EvalDataType.Int32: return importer.OrInt; - case EvalDataType.Int64: return importer.OrLong; - default: return null; - } - } - case Code.Xor: - { - switch (op1) - { - case EvalDataType.Int32: return importer.XorInt; - case EvalDataType.Int64: return importer.XorLong; - default: return null; - } - } - case Code.Not: - { - switch (op1) - { - case EvalDataType.Int32: return importer.NotInt; - case EvalDataType.Int64: return importer.NotLong; - default: return null; - } - } - case Code.Shl: - { - switch (op1) - { - case EvalDataType.Int32: return importer.ShlInt; - case EvalDataType.Int64: return importer.ShlLong; - default: return null; - } - } - case Code.Shr: - { - switch (op1) - { - case EvalDataType.Int32: return importer.ShrInt; - case EvalDataType.Int64: return importer.ShrLong; - default: return null; - } - } - case Code.Shr_Un: - { - switch (op1) - { - case EvalDataType.Int32: return importer.ShrUnInt; - case EvalDataType.Int64: return importer.ShrUnLong; - default: return null; - } - } - default: return null; - } - } - - public override bool ObfuscateBasicUnaryOp(Instruction inst, EvalDataType op, EvalDataType ret, List outputInsts, ObfusMethodContext ctx) - { - IMethod opMethod = GetUnaryOpMethod(ctx.importer, inst.OpCode.Code, op); - if (opMethod == null) - { - Debug.LogWarning($"BasicObfuscator: Cannot obfuscate unary operation {inst.OpCode.Code} with different operand types: op={op}. This is a limitation of the BasicObfuscator."); - return false; - } - outputInsts.Add(Instruction.Create(OpCodes.Call, opMethod)); - return true; - } - - public override bool ObfuscateBasicBinOp(Instruction inst, EvalDataType op1, EvalDataType op2, EvalDataType ret, List outputInsts, ObfusMethodContext ctx) - { - IMethod opMethod = GetBinaryOpMethod(ctx.importer, inst.OpCode.Code, op1, op2); - if (opMethod == null) - { - Debug.LogWarning($"BasicObfuscator: Cannot obfuscate binary operation {inst.OpCode.Code} with different operand types: op1={op1}, op2={op2}, ret={ret}. This is a limitation of the BasicObfuscator."); - return false; - } - outputInsts.Add(Instruction.Create(OpCodes.Call, opMethod)); - return true; - } - - public override bool ObfuscateUnaryBitwiseOp(Instruction inst, EvalDataType op, EvalDataType ret, List outputInsts, ObfusMethodContext ctx) - { - IMethod opMethod = GetUnaryOpMethod(ctx.importer, inst.OpCode.Code, op); - if (opMethod == null) - { - Debug.LogWarning($"BasicObfuscator: Cannot obfuscate unary operation {inst.OpCode.Code} with different operand types: op={op}. This is a limitation of the BasicObfuscator."); - return false; - } - outputInsts.Add(Instruction.Create(OpCodes.Call, opMethod)); - return true; - } - - public override bool ObfuscateBinBitwiseOp(Instruction inst, EvalDataType op1, EvalDataType op2, EvalDataType ret, List outputInsts, ObfusMethodContext ctx) - { - IMethod opMethod = GetBinaryOpMethod(ctx.importer, inst.OpCode.Code, op1, op2); - if (opMethod == null) - { - Debug.LogWarning($"BasicObfuscator: Cannot obfuscate binary operation {inst.OpCode.Code} with different operand types: op1={op1}, op2={op2}, ret={ret}. This is a limitation of the BasicObfuscator."); - return false; - } - outputInsts.Add(Instruction.Create(OpCodes.Call, opMethod)); - return true; - } - - public override bool ObfuscateBitShiftOp(Instruction inst, EvalDataType op1, EvalDataType op2, EvalDataType ret, List outputInsts, ObfusMethodContext ctx) - { - IMethod opMethod = GetBinaryOpMethod(ctx.importer, inst.OpCode.Code, op1, op2); - if (opMethod == null) - { - Debug.LogWarning($"BasicObfuscator: Cannot obfuscate binary operation {inst.OpCode.Code} with operand type {op2}. This is a limitation of the BasicObfuscator."); - return false; - } - outputInsts.Add(Instruction.Create(OpCodes.Call, opMethod)); - return true; - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ExprObfus/Obfuscators/BasicObfuscator.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ExprObfus/Obfuscators/BasicObfuscator.cs.meta deleted file mode 100644 index dd49d805..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ExprObfus/Obfuscators/BasicObfuscator.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 578caeae17526b54c9ff1979d897feb7 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ExprObfus/Obfuscators/MostAdvancedObfuscator.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ExprObfus/Obfuscators/MostAdvancedObfuscator.cs deleted file mode 100644 index 1ff1a70b..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ExprObfus/Obfuscators/MostAdvancedObfuscator.cs +++ /dev/null @@ -1,83 +0,0 @@ -using dnlib.DotNet.Emit; -using Obfuz.Emit; -using System.Collections.Generic; -using System.Linq; - -namespace Obfuz.ObfusPasses.ExprObfus.Obfuscators -{ - class MostAdvancedObfuscator : AdvancedObfuscator - { - private readonly BasicObfuscator _basicObfuscator = new BasicObfuscator(); - - public override bool ObfuscateBasicUnaryOp(Instruction inst, EvalDataType op, EvalDataType ret, List outputInsts, ObfusMethodContext ctx) - { - if (!base.ObfuscateBasicUnaryOp(inst, op, ret, outputInsts, ctx)) - { - return false; - } - if (outputInsts.Last().OpCode.Code != inst.OpCode.Code) - { - return false; - } - outputInsts.RemoveAt(outputInsts.Count - 1); - return _basicObfuscator.ObfuscateBasicUnaryOp(inst, op, ret, outputInsts, ctx); - } - - public override bool ObfuscateBasicBinOp(Instruction inst, EvalDataType op1, EvalDataType op2, EvalDataType ret, List outputInsts, ObfusMethodContext ctx) - { - if (!base.ObfuscateBasicBinOp(inst, op1, op2, ret, outputInsts, ctx)) - { - return false; - } - if (outputInsts.Last().OpCode.Code != inst.OpCode.Code) - { - return false; - } - outputInsts.RemoveAt(outputInsts.Count - 1); - return _basicObfuscator.ObfuscateBasicBinOp(inst, op1, op2, ret, outputInsts, ctx); - } - - public override bool ObfuscateUnaryBitwiseOp(Instruction inst, EvalDataType op, EvalDataType ret, List outputInsts, ObfusMethodContext ctx) - { - if (!base.ObfuscateUnaryBitwiseOp(inst, op, ret, outputInsts, ctx)) - { - return false; - } - - if (outputInsts.Last().OpCode.Code != inst.OpCode.Code) - { - return false; - } - outputInsts.RemoveAt(outputInsts.Count - 1); - return _basicObfuscator.ObfuscateUnaryBitwiseOp(inst, op, ret, outputInsts, ctx); - } - - public override bool ObfuscateBinBitwiseOp(Instruction inst, EvalDataType op1, EvalDataType op2, EvalDataType ret, List outputInsts, ObfusMethodContext ctx) - { - if (!base.ObfuscateBinBitwiseOp(inst, op1, op2, ret, outputInsts, ctx)) - { - return false; - } - if (outputInsts.Last().OpCode.Code != inst.OpCode.Code) - { - return false; - } - outputInsts.RemoveAt(outputInsts.Count - 1); - return _basicObfuscator.ObfuscateBinBitwiseOp(inst, op1, op2, ret, outputInsts, ctx); - } - - public override bool ObfuscateBitShiftOp(Instruction inst, EvalDataType op1, EvalDataType op2, EvalDataType ret, List outputInsts, ObfusMethodContext ctx) - { - if (!base.ObfuscateBitShiftOp(inst, op1, op2, ret, outputInsts, ctx)) - { - return false; - } - if (outputInsts.Last().OpCode.Code != inst.OpCode.Code) - { - return false; - } - outputInsts.RemoveAt(outputInsts.Count - 1); - return _basicObfuscator.ObfuscateBitShiftOp(inst, op1, op2, ret, outputInsts, ctx); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ExprObfus/Obfuscators/MostAdvancedObfuscator.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ExprObfus/Obfuscators/MostAdvancedObfuscator.cs.meta deleted file mode 100644 index fb1660a3..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ExprObfus/Obfuscators/MostAdvancedObfuscator.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: af5946ac6cb0a8b4fa75321439785133 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/FieldEncrypt.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/FieldEncrypt.meta deleted file mode 100644 index 24c7b1d7..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/FieldEncrypt.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 0b789725c4848bd4fb4b3ce1f2e2a9c9 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/FieldEncrypt/ConfigurableEncryptPolicy.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/FieldEncrypt/ConfigurableEncryptPolicy.cs deleted file mode 100644 index 31d977e7..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/FieldEncrypt/ConfigurableEncryptPolicy.cs +++ /dev/null @@ -1,45 +0,0 @@ -using dnlib.DotNet; -using Obfuz.Conf; -using Obfuz.Utils; -using System.Collections.Generic; -using System.Xml; - -namespace Obfuz.ObfusPasses.FieldEncrypt -{ - public class ConfigurableEncryptPolicy : EncryptPolicyBase - { - class ObfuscationRule - { - - } - - private readonly XmlFieldRuleParser _configParser; - private readonly ObfuzIgnoreScopeComputeCache _obfuzIgnoreScopeComputeCache; - - public ConfigurableEncryptPolicy(ObfuzIgnoreScopeComputeCache obfuzIgnoreScopeComputeCache, List toObfuscatedAssemblyNames, List configFiles) - { - _obfuzIgnoreScopeComputeCache = obfuzIgnoreScopeComputeCache; - _configParser = new XmlFieldRuleParser(toObfuscatedAssemblyNames, ParseRule, null); - _configParser.LoadConfigs(configFiles); - } - - private ObfuscationRule ParseRule(string configFile, XmlElement ele) - { - return new ObfuscationRule(); - } - - public override bool NeedEncrypt(FieldDef field) - { - if (MetaUtil.HasEncryptFieldAttribute(field)) - { - return true; - } - if (_obfuzIgnoreScopeComputeCache.HasSelfOrDeclaringOrEnclosingOrInheritObfuzIgnoreScope(field, field.DeclaringType, ObfuzScope.Field)) - { - return false; - } - var rule = _configParser.GetFieldRule(field); - return rule != null; - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/FieldEncrypt/ConfigurableEncryptPolicy.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/FieldEncrypt/ConfigurableEncryptPolicy.cs.meta deleted file mode 100644 index bcc4d60c..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/FieldEncrypt/ConfigurableEncryptPolicy.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 6b17fa09ce58526459f2b9e375c31cad -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/FieldEncrypt/DefaultFieldEncryptor.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/FieldEncrypt/DefaultFieldEncryptor.cs deleted file mode 100644 index bc8bbe9a..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/FieldEncrypt/DefaultFieldEncryptor.cs +++ /dev/null @@ -1,201 +0,0 @@ -using dnlib.DotNet; -using dnlib.DotNet.Emit; -using Obfuz.Emit; -using Obfuz.Settings; -using Obfuz.Utils; -using System; -using System.Collections.Generic; -using UnityEngine.Assertions; - -namespace Obfuz.ObfusPasses.FieldEncrypt -{ - public class DefaultFieldEncryptor : FieldEncryptorBase - { - private readonly GroupByModuleEntityManager _moduleEntityManager; - private readonly FieldEncryptionSettingsFacade _settings; - - public DefaultFieldEncryptor(GroupByModuleEntityManager moduleEntityManager, FieldEncryptionSettingsFacade settings) - { - _moduleEntityManager = moduleEntityManager; - _settings = settings; - } - - class FieldEncryptInfo - { - public int encryptOps; - public int salt; - public ElementType fieldType; - public long xorValueForZero; - } - - private readonly Dictionary _fieldEncryptInfoCache = new Dictionary(); - - - private long CalcXorValueForZero(IEncryptor encryptor, ElementType type, int encryptOps, int salt) - { - switch (type) - { - case ElementType.I4: - case ElementType.U4: - case ElementType.R4: - return encryptor.Encrypt(0, encryptOps, salt); - case ElementType.I8: - case ElementType.U8: - case ElementType.R8: - return encryptor.Encrypt(0L, encryptOps, salt); - default: - throw new NotSupportedException($"Unsupported field type: {type} for encryption"); - } - } - - - private IRandom CreateRandomForField(RandomCreator randomCreator, FieldDef field) - { - return randomCreator(FieldEqualityComparer.CompareDeclaringTypes.GetHashCode(field)); - } - - private int GenerateEncryptionOperations(IRandom random, IEncryptor encryptor) - { - return EncryptionUtil.GenerateEncryptionOpCodes(random, encryptor, _settings.encryptionLevel); - } - - public int GenerateSalt(IRandom random) - { - return random.NextInt(); - } - - private FieldEncryptInfo GetFieldEncryptInfo(FieldDef field) - { - if (_fieldEncryptInfoCache.TryGetValue(field, out var info)) - { - return info; - } - EncryptionScopeInfo encryptionScope = _moduleEntityManager.EncryptionScopeProvider.GetScope(field.Module); - - IRandom random = CreateRandomForField(encryptionScope.localRandomCreator, field); - IEncryptor encryptor = encryptionScope.encryptor; - int encryptOps = GenerateEncryptionOperations(random, encryptor); - int salt = GenerateSalt(random); - ElementType fieldType = field.FieldSig.Type.RemovePinnedAndModifiers().ElementType; - long xorValueForZero = CalcXorValueForZero(encryptor, fieldType, encryptOps, salt); - - info = new FieldEncryptInfo - { - encryptOps = encryptOps, - salt = salt, - fieldType = fieldType, - xorValueForZero = xorValueForZero, - }; - _fieldEncryptInfoCache[field] = info; - return info; - } - - public override void Encrypt(MethodDef method, FieldDef field, List outputInstructions, Instruction currentInstruction) - { - DefaultMetadataImporter importer = _moduleEntityManager.GetEntity(method.Module); - EncryptionServiceMetadataImporter encryptionServiceMetadataImporter = importer.GetEncryptionServiceMetadataImporterOfModule(field.Module); - FieldEncryptInfo fei = GetFieldEncryptInfo(field); - if (fei.fieldType == ElementType.I4 || fei.fieldType == ElementType.U4 || fei.fieldType == ElementType.R4) - { - // value has been put on stack - - if (fei.fieldType == ElementType.R4) - { - outputInstructions.Add(Instruction.Create(OpCodes.Call, importer.CastFloatAsInt)); - } - // encrypt - outputInstructions.Add(Instruction.CreateLdcI4(fei.encryptOps)); - outputInstructions.Add(Instruction.CreateLdcI4(fei.salt)); - outputInstructions.Add(Instruction.Create(OpCodes.Call, encryptionServiceMetadataImporter.EncryptInt)); - // xor - outputInstructions.Add(Instruction.CreateLdcI4((int)fei.xorValueForZero)); - outputInstructions.Add(Instruction.Create(OpCodes.Xor)); - - if (fei.fieldType == ElementType.R4) - { - outputInstructions.Add(Instruction.Create(OpCodes.Call, importer.CastIntAsFloat)); - } - } - else if (fei.fieldType == ElementType.I8 || fei.fieldType == ElementType.U8 || fei.fieldType == ElementType.R8) - { - // value has been put on stack - if (fei.fieldType == ElementType.R8) - { - outputInstructions.Add(Instruction.Create(OpCodes.Call, importer.CastDoubleAsLong)); - } - - // encrypt - outputInstructions.Add(Instruction.CreateLdcI4(fei.encryptOps)); - outputInstructions.Add(Instruction.CreateLdcI4(fei.salt)); - outputInstructions.Add(Instruction.Create(OpCodes.Call, encryptionServiceMetadataImporter.EncryptLong)); - // xor - outputInstructions.Add(Instruction.Create(OpCodes.Ldc_I8, fei.xorValueForZero)); - outputInstructions.Add(Instruction.Create(OpCodes.Xor)); - if (fei.fieldType == ElementType.R8) - { - outputInstructions.Add(Instruction.Create(OpCodes.Call, importer.CastLongAsDouble)); - } - } - else - { - Assert.IsTrue(false, $"Unsupported field type: {fei.fieldType} for encryption"); - } - - outputInstructions.Add(currentInstruction.Clone()); - } - - public override void Decrypt(MethodDef method, FieldDef field, List outputInstructions, Instruction currentInstruction) - { - outputInstructions.Add(currentInstruction.Clone()); - DefaultMetadataImporter importer = _moduleEntityManager.GetEntity(method.Module); - EncryptionServiceMetadataImporter encryptionServiceMetadataImporter = importer.GetEncryptionServiceMetadataImporterOfModule(field.Module); - FieldEncryptInfo fei = GetFieldEncryptInfo(field); - if (fei.fieldType == ElementType.I4 || fei.fieldType == ElementType.U4 || fei.fieldType == ElementType.R4) - { - // value has been put on stack - // xor - if (fei.fieldType == ElementType.R4) - { - outputInstructions.Add(Instruction.Create(OpCodes.Call, importer.CastFloatAsInt)); - } - outputInstructions.Add(Instruction.CreateLdcI4((int)fei.xorValueForZero)); - outputInstructions.Add(Instruction.Create(OpCodes.Xor)); - - // decrypt - outputInstructions.Add(Instruction.CreateLdcI4(fei.encryptOps)); - outputInstructions.Add(Instruction.CreateLdcI4(fei.salt)); - outputInstructions.Add(Instruction.Create(OpCodes.Call, encryptionServiceMetadataImporter.DecryptInt)); - - if (fei.fieldType == ElementType.R4) - { - outputInstructions.Add(Instruction.Create(OpCodes.Call, importer.CastIntAsFloat)); - } - } - else if (fei.fieldType == ElementType.I8 || fei.fieldType == ElementType.U8 || fei.fieldType == ElementType.R8) - { - // value has been put on stack - // xor - if (fei.fieldType == ElementType.R8) - { - outputInstructions.Add(Instruction.Create(OpCodes.Call, importer.CastDoubleAsLong)); - } - outputInstructions.Add(Instruction.Create(OpCodes.Ldc_I8, fei.xorValueForZero)); - outputInstructions.Add(Instruction.Create(OpCodes.Xor)); - - // decrypt - outputInstructions.Add(Instruction.CreateLdcI4(fei.encryptOps)); - outputInstructions.Add(Instruction.CreateLdcI4(fei.salt)); - outputInstructions.Add(Instruction.Create(OpCodes.Call, encryptionServiceMetadataImporter.DecryptLong)); - - if (fei.fieldType == ElementType.R8) - { - outputInstructions.Add(Instruction.Create(OpCodes.Call, importer.CastLongAsDouble)); - } - } - else - { - Assert.IsTrue(false, $"Unsupported field type: {fei.fieldType} for decryption"); - } - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/FieldEncrypt/DefaultFieldEncryptor.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/FieldEncrypt/DefaultFieldEncryptor.cs.meta deleted file mode 100644 index 905f446b..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/FieldEncrypt/DefaultFieldEncryptor.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: b6707a66ae63e2c498d55088c6e8ef4a -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/FieldEncrypt/FieldEncryptPass.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/FieldEncrypt/FieldEncryptPass.cs deleted file mode 100644 index 3f82faf5..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/FieldEncrypt/FieldEncryptPass.cs +++ /dev/null @@ -1,102 +0,0 @@ -using dnlib.DotNet; -using dnlib.DotNet.Emit; -using Obfuz.Settings; -using System.Collections.Generic; - -namespace Obfuz.ObfusPasses.FieldEncrypt -{ - - public class FieldEncryptPass : InstructionObfuscationPassBase - { - private FieldEncryptionSettingsFacade _settings; - private IEncryptPolicy _encryptionPolicy; - private IFieldEncryptor _memoryEncryptor; - - public override ObfuscationPassType Type => ObfuscationPassType.FieldEncrypt; - - public FieldEncryptPass(FieldEncryptionSettingsFacade settings) - { - _settings = settings; - } - - protected override bool ForceProcessAllAssembliesAndIgnoreAllPolicy => true; - - public override void Start() - { - var ctx = ObfuscationPassContext.Current; - _memoryEncryptor = new DefaultFieldEncryptor(ctx.moduleEntityManager, _settings); - _encryptionPolicy = new ConfigurableEncryptPolicy(ctx.obfuzIgnoreScopeComputeCache, ctx.coreSettings.assembliesToObfuscate, _settings.ruleFiles); - } - - public override void Stop() - { - - } - - protected override bool NeedObfuscateMethod(MethodDef method) - { - return true; - } - - private bool IsSupportedFieldType(TypeSig type) - { - type = type.RemovePinnedAndModifiers(); - switch (type.ElementType) - { - case ElementType.I4: - case ElementType.I8: - case ElementType.U4: - case ElementType.U8: - case ElementType.R4: - case ElementType.R8: - return true; - default: return false; - } - } - - protected override bool TryObfuscateInstruction(MethodDef callingMethod, Instruction inst, IList instructions, int instructionIndex, List outputInstructions, List totalFinalInstructions) - { - Code code = inst.OpCode.Code; - if (!(inst.Operand is IField field) || !field.IsField) - { - return false; - } - FieldDef fieldDef = field.ResolveFieldDefThrow(); - if (!IsSupportedFieldType(fieldDef.FieldSig.Type) || !_encryptionPolicy.NeedEncrypt(fieldDef)) - { - return false; - } - switch (code) - { - case Code.Ldfld: - { - _memoryEncryptor.Decrypt(callingMethod, fieldDef, outputInstructions, inst); - break; - } - case Code.Stfld: - { - _memoryEncryptor.Encrypt(callingMethod, fieldDef, outputInstructions, inst); - break; - } - case Code.Ldsfld: - { - _memoryEncryptor.Decrypt(callingMethod, fieldDef, outputInstructions, inst); - break; - } - case Code.Stsfld: - { - _memoryEncryptor.Encrypt(callingMethod, fieldDef, outputInstructions, inst); - break; - } - case Code.Ldflda: - case Code.Ldsflda: - { - throw new System.Exception($"You shouldn't get reference to memory encryption field: {field}"); - } - default: return false; - } - //Debug.Log($"memory encrypt field: {field}"); - return true; - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/FieldEncrypt/FieldEncryptPass.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/FieldEncrypt/FieldEncryptPass.cs.meta deleted file mode 100644 index 1e60f28c..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/FieldEncrypt/FieldEncryptPass.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: f3da24d0f1f1fc7449cbd0e7ddd03aa2 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/FieldEncrypt/IEncryptPolicy.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/FieldEncrypt/IEncryptPolicy.cs deleted file mode 100644 index ee7dd534..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/FieldEncrypt/IEncryptPolicy.cs +++ /dev/null @@ -1,14 +0,0 @@ -using dnlib.DotNet; - -namespace Obfuz.ObfusPasses.FieldEncrypt -{ - public interface IEncryptPolicy - { - bool NeedEncrypt(FieldDef field); - } - - public abstract class EncryptPolicyBase : IEncryptPolicy - { - public abstract bool NeedEncrypt(FieldDef field); - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/FieldEncrypt/IEncryptPolicy.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/FieldEncrypt/IEncryptPolicy.cs.meta deleted file mode 100644 index d5c10473..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/FieldEncrypt/IEncryptPolicy.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: a48d0500d0737404cad9c9ef23a9467c -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/FieldEncrypt/IFieldEncryptor.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/FieldEncrypt/IFieldEncryptor.cs deleted file mode 100644 index 0b6d5821..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/FieldEncrypt/IFieldEncryptor.cs +++ /dev/null @@ -1,26 +0,0 @@ -using dnlib.DotNet; -using dnlib.DotNet.Emit; -using System.Collections.Generic; - -namespace Obfuz.ObfusPasses.FieldEncrypt -{ - public class MemoryEncryptionContext - { - public ModuleDef module; - - public Instruction currentInstruction; - } - - public interface IFieldEncryptor - { - void Encrypt(MethodDef method, FieldDef field, List outputInstructions, Instruction currentInstruction); - - void Decrypt(MethodDef method, FieldDef field, List outputInstructions, Instruction currentInstruction); - } - - public abstract class FieldEncryptorBase : IFieldEncryptor - { - public abstract void Encrypt(MethodDef method, FieldDef field, List outputInstructions, Instruction currentInstruction); - public abstract void Decrypt(MethodDef method, FieldDef field, List outputInstructions, Instruction currentInstruction); - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/FieldEncrypt/IFieldEncryptor.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/FieldEncrypt/IFieldEncryptor.cs.meta deleted file mode 100644 index dca50715..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/FieldEncrypt/IFieldEncryptor.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 8a3ec14fca5169d479529d21b2eeada1 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/Instinct.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/Instinct.meta deleted file mode 100644 index 97e300cc..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/Instinct.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: bb4f71e54c6a07341883ba0c642505c1 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/Instinct/InstinctPass.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/Instinct/InstinctPass.cs deleted file mode 100644 index f7b32753..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/Instinct/InstinctPass.cs +++ /dev/null @@ -1,138 +0,0 @@ -using dnlib.DotNet; -using dnlib.DotNet.Emit; -using Obfuz.Editor; -using Obfuz.Emit; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using UnityEngine.Assertions; - -namespace Obfuz.ObfusPasses.Instinct -{ - - public class InstinctPass : InstructionObfuscationPassBase - { - public override ObfuscationPassType Type => ObfuscationPassType.None; - - protected override bool ForceProcessAllAssembliesAndIgnoreAllPolicy => true; - - public InstinctPass() - { - } - - public override void Start() - { - } - - public override void Stop() - { - - } - - protected override bool NeedObfuscateMethod(MethodDef method) - { - return true; - } - - private string GetTypeName(TypeSig type) - { - type = type.RemovePinnedAndModifiers(); - switch (type.ElementType) - { - case ElementType.Class: - case ElementType.ValueType: - { - return type.ReflectionName; - } - case ElementType.GenericInst: - { - type = ((GenericInstSig)type).GenericType; - return type.ReflectionName; - } - default: return type.ReflectionName; - } - } - - private string GetTypeFullName(TypeSig type) - { - type = type.RemovePinnedAndModifiers(); - - switch (type.ElementType) - { - case ElementType.Class: - case ElementType.ValueType: - { - return type.ReflectionFullName; - } - case ElementType.GenericInst: - { - GenericInstSig genericInstSig = (GenericInstSig)type; - var typeName = new StringBuilder(genericInstSig.GenericType.ReflectionFullName); - typeName.Append("<").Append(string.Join(",", genericInstSig.GenericArguments.Select(GetTypeFullName))).Append(">"); - return typeName.ToString(); - } - default: return type.ReflectionFullName; - } - } - - protected override bool TryObfuscateInstruction(MethodDef callingMethod, Instruction inst, IList instructions, int instructionIndex, List outputInstructions, List totalFinalInstructions) - { - Code code = inst.OpCode.Code; - if (!(inst.Operand is IMethod method) || !method.IsMethod) - { - return false; - } - MethodDef methodDef = method.ResolveMethodDef(); - if (methodDef == null || methodDef.DeclaringType.Name != "ObfuscationInstincts" || methodDef.DeclaringType.DefinitionAssembly.Name != ConstValues.ObfuzRuntimeAssemblyName) - { - return false; - } - - ObfuscationPassContext ctx = ObfuscationPassContext.Current; - var importer = ctx.moduleEntityManager.GetEntity(callingMethod.Module); - - string methodName = methodDef.Name; - switch (methodName) - { - case "FullNameOf": - case "NameOf": - case "RegisterReflectionType": - { - MethodSpec methodSpec = (MethodSpec)method; - GenericInstMethodSig gims = methodSpec.GenericInstMethodSig; - Assert.AreEqual(1, gims.GenericArguments.Count, "FullNameOf should have exactly one generic argument"); - TypeSig type = gims.GenericArguments[0]; - switch (methodName) - { - case "FullNameOf": - { - string typeFullName = GetTypeFullName(type); - outputInstructions.Add(Instruction.Create(OpCodes.Ldstr, typeFullName)); - break; - } - case "NameOf": - { - string typeName = GetTypeName(type); - outputInstructions.Add(Instruction.Create(OpCodes.Ldstr, typeName)); - break; - } - case "RegisterReflectionType": - { - string typeFullName = GetTypeFullName(type); - outputInstructions.Add(Instruction.Create(OpCodes.Ldstr, typeFullName)); - var finalMethod = new MethodSpecUser((IMethodDefOrRef)importer.ObfuscationTypeMapperRegisterType, gims); - outputInstructions.Add(Instruction.Create(OpCodes.Call, finalMethod)); - break; - } - default: throw new NotSupportedException($"Unsupported instinct method: {methodDef.FullName}"); - } - break; - } - default: throw new NotSupportedException($"Unsupported instinct method: {methodDef.FullName}"); - } - //Debug.Log($"memory encrypt field: {field}"); - return true; - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/Instinct/InstinctPass.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/Instinct/InstinctPass.cs.meta deleted file mode 100644 index ca21ae47..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/Instinct/InstinctPass.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 08027d16e09664c40b561715ef9326fc -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/InstructionObfuscationPassBase.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/InstructionObfuscationPassBase.cs deleted file mode 100644 index 424c0d20..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/InstructionObfuscationPassBase.cs +++ /dev/null @@ -1,46 +0,0 @@ -using dnlib.DotNet; -using dnlib.DotNet.Emit; -using System.Collections.Generic; - -namespace Obfuz.ObfusPasses -{ - public abstract class InstructionObfuscationPassBase : ObfuscationMethodPassBase - { - protected abstract bool TryObfuscateInstruction(MethodDef callingMethod, Instruction inst, IList instructions, int instructionIndex, - List outputInstructions, List totalFinalInstructions); - - protected override void ObfuscateData(MethodDef method) - { - IList instructions = method.Body.Instructions; - var outputInstructions = new List(); - var totalFinalInstructions = new List(); - for (int i = 0; i < instructions.Count; i++) - { - Instruction inst = instructions[i]; - outputInstructions.Clear(); - if (TryObfuscateInstruction(method, inst, instructions, i, outputInstructions, totalFinalInstructions)) - { - // current instruction may be the target of control flow instruction, so we can't remove it directly. - // we replace it with nop now, then remove it in CleanUpInstructionPass - inst.OpCode = outputInstructions[0].OpCode; - inst.Operand = outputInstructions[0].Operand; - totalFinalInstructions.Add(inst); - for (int k = 1; k < outputInstructions.Count; k++) - { - totalFinalInstructions.Add(outputInstructions[k]); - } - } - else - { - totalFinalInstructions.Add(inst); - } - } - - instructions.Clear(); - foreach (var obInst in totalFinalInstructions) - { - instructions.Add(obInst); - } - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/InstructionObfuscationPassBase.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/InstructionObfuscationPassBase.cs.meta deleted file mode 100644 index ba2497af..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/InstructionObfuscationPassBase.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: e0cad4b764050f44f8c9b225056a4f49 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ObfuscationMethodPassBase.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ObfuscationMethodPassBase.cs deleted file mode 100644 index 7a2e0942..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ObfuscationMethodPassBase.cs +++ /dev/null @@ -1,47 +0,0 @@ -using dnlib.DotNet; -using System.Linq; - -namespace Obfuz.ObfusPasses -{ - public abstract class ObfuscationMethodPassBase : ObfuscationPassBase - { - protected virtual bool ForceProcessAllAssembliesAndIgnoreAllPolicy => false; - - protected abstract bool NeedObfuscateMethod(MethodDef method); - - protected abstract void ObfuscateData(MethodDef method); - - public override void Process() - { - var ctx = ObfuscationPassContext.Current; - var modules = ForceProcessAllAssembliesAndIgnoreAllPolicy ? ctx.allObfuscationRelativeModules : ctx.modulesToObfuscate; - ObfuscationMethodWhitelist whiteList = ctx.whiteList; - ConfigurablePassPolicy passPolicy = ctx.passPolicy; - foreach (ModuleDef mod in modules) - { - if (!ForceProcessAllAssembliesAndIgnoreAllPolicy && whiteList.IsInWhiteList(mod)) - { - continue; - } - // ToArray to avoid modify list exception - foreach (TypeDef type in mod.GetTypes().ToArray()) - { - if (!ForceProcessAllAssembliesAndIgnoreAllPolicy && whiteList.IsInWhiteList(type)) - { - continue; - } - // ToArray to avoid modify list exception - foreach (MethodDef method in type.Methods.ToArray()) - { - if (!method.HasBody || (!ForceProcessAllAssembliesAndIgnoreAllPolicy && (ctx.whiteList.IsInWhiteList(method) || !Support(passPolicy.GetMethodObfuscationPasses(method)) || !NeedObfuscateMethod(method)))) - { - continue; - } - // TODO if isGeneratedBy Obfuscator, continue - ObfuscateData(method); - } - } - } - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ObfuscationMethodPassBase.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ObfuscationMethodPassBase.cs.meta deleted file mode 100644 index 0be4d9f9..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ObfuscationMethodPassBase.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 84b0592af70b0cc41b546cf8ac39f889 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ObfuscationPassBase.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ObfuscationPassBase.cs deleted file mode 100644 index 48e23ec8..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ObfuscationPassBase.cs +++ /dev/null @@ -1,18 +0,0 @@ -namespace Obfuz.ObfusPasses -{ - public abstract class ObfuscationPassBase : IObfuscationPass - { - public abstract ObfuscationPassType Type { get; } - - public bool Support(ObfuscationPassType passType) - { - return passType.HasFlag(Type); - } - - public abstract void Start(); - - public abstract void Stop(); - - public abstract void Process(); - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ObfuscationPassBase.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ObfuscationPassBase.cs.meta deleted file mode 100644 index 335ee271..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ObfuscationPassBase.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 2f3e7e1d2a3ad3a4fb1a81e97730b5a4 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ObfuscationPassType.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ObfuscationPassType.cs deleted file mode 100644 index b5deb968..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ObfuscationPassType.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System; - -namespace Obfuz.ObfusPasses -{ - [Flags] - public enum ObfuscationPassType - { - None = 0, - - ConstEncrypt = 0x1, - FieldEncrypt = 0x2, - - SymbolObfus = 0x100, - CallObfus = 0x200, - ExprObfus = 0x400, - ControlFlowObfus = 0x800, - EvalStackObfus = 0x1000, - - AllObfus = SymbolObfus | CallObfus | ExprObfus | ControlFlowObfus | EvalStackObfus, - AllEncrypt = ConstEncrypt | FieldEncrypt, - - MethodBodyObfusOrEncrypt = ConstEncrypt | CallObfus | ExprObfus | ControlFlowObfus | EvalStackObfus, - - All = ~0, - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ObfuscationPassType.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ObfuscationPassType.cs.meta deleted file mode 100644 index b03ea206..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/ObfuscationPassType.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 5addd02f6f3dc0a4d888a0f74bd5ce4d -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus.meta deleted file mode 100644 index 331b3d15..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: b746569f7c0d9754fa6f2925538eddbd -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/INameMaker.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/INameMaker.cs deleted file mode 100644 index 6f95ffdb..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/INameMaker.cs +++ /dev/null @@ -1,37 +0,0 @@ -using dnlib.DotNet; - -namespace Obfuz.ObfusPasses.SymbolObfus -{ - public interface INameMaker - { - void AddPreservedName(TypeDef typeDef, string name); - - void AddPreservedNamespace(TypeDef typeDef, string name); - - void AddPreservedName(MethodDef methodDef, string name); - - void AddPreservedName(FieldDef fieldDef, string name); - - void AddPreservedName(PropertyDef propertyDef, string name); - - void AddPreservedName(EventDef eventDef, string name); - - bool IsNamePreserved(VirtualMethodGroup virtualMethodGroup, string name); - - string GetNewName(TypeDef typeDef, string originalName); - - string GetNewNamespace(TypeDef typeDef, string originalNamespace, bool reuse); - - string GetNewName(MethodDef methodDef, string originalName); - - string GetNewName(VirtualMethodGroup virtualMethodGroup, string originalName); - - string GetNewName(ParamDef param, string originalName); - - string GetNewName(FieldDef fieldDef, string originalName); - - string GetNewName(PropertyDef propertyDef, string originalName); - - string GetNewName(EventDef eventDef, string originalName); - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/INameMaker.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/INameMaker.cs.meta deleted file mode 100644 index 80621974..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/INameMaker.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 0c24d29f654d00b44bb6aa3b4bf222dd -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/IObfuscationPolicy.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/IObfuscationPolicy.cs deleted file mode 100644 index 2a39e451..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/IObfuscationPolicy.cs +++ /dev/null @@ -1,17 +0,0 @@ -using dnlib.DotNet; - -namespace Obfuz.ObfusPasses.SymbolObfus -{ - public interface IObfuscationPolicy - { - bool NeedRename(TypeDef typeDef); - - bool NeedRename(MethodDef methodDef); - - bool NeedRename(FieldDef fieldDef); - - bool NeedRename(PropertyDef propertyDef); - - bool NeedRename(EventDef eventDef); - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/IObfuscationPolicy.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/IObfuscationPolicy.cs.meta deleted file mode 100644 index ffe0fee1..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/IObfuscationPolicy.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: bd640b26c1d868544a7a91a0f986fdde -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/NameMakers.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/NameMakers.meta deleted file mode 100644 index 9cd6e532..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/NameMakers.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: c970ffd992fbc154aaa37a2c48c24d5c -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/NameMakers/DebugNameMaker.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/NameMakers/DebugNameMaker.cs deleted file mode 100644 index 038281e4..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/NameMakers/DebugNameMaker.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System.Text; - -namespace Obfuz.ObfusPasses.SymbolObfus.NameMakers -{ - public class DebugNameMaker : NameMakerBase - { - private class DebugNameScope : INameScope - { - - public bool AddPreservedName(string name) - { - return true; - } - - public string GetNewName(string originalName, bool reuse) - { - return $"${originalName}"; - } - - public bool IsNamePreserved(string name) - { - return false; - } - } - - protected override INameScope CreateNameScope() - { - return new DebugNameScope(); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/NameMakers/DebugNameMaker.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/NameMakers/DebugNameMaker.cs.meta deleted file mode 100644 index 11b505b8..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/NameMakers/DebugNameMaker.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: abc1adfad5c7754499ceed4d4646eb58 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/NameMakers/INameScope.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/NameMakers/INameScope.cs deleted file mode 100644 index c6ca426f..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/NameMakers/INameScope.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace Obfuz.ObfusPasses.SymbolObfus.NameMakers -{ - public interface INameScope - { - bool AddPreservedName(string name); - - bool IsNamePreserved(string name); - - string GetNewName(string originalName, bool reuse); - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/NameMakers/INameScope.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/NameMakers/INameScope.cs.meta deleted file mode 100644 index 4c632535..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/NameMakers/INameScope.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 6c3884d338faf564eab48d58f02adc39 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/NameMakers/NameMakerBase.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/NameMakers/NameMakerBase.cs deleted file mode 100644 index 1cd72c95..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/NameMakers/NameMakerBase.cs +++ /dev/null @@ -1,116 +0,0 @@ -using dnlib.DotNet; -using System.Collections.Generic; -using UnityEngine.Assertions; - -namespace Obfuz.ObfusPasses.SymbolObfus.NameMakers -{ - public abstract class NameMakerBase : INameMaker - { - - private readonly Dictionary _nameScopes = new Dictionary(); - - private readonly object _namespaceScope = new object(); - private readonly object _typeNameScope = new object(); - private readonly object _methodNameScope = new object(); - private readonly object _fieldNameScope = new object(); - - protected abstract INameScope CreateNameScope(); - - protected INameScope GetNameScope(object key) - { - if (!_nameScopes.TryGetValue(key, out var nameScope)) - { - nameScope = CreateNameScope(); - _nameScopes[key] = nameScope; - } - return nameScope; - } - - public void AddPreservedName(TypeDef typeDef, string name) - { - GetNameScope(_typeNameScope).AddPreservedName(name); - } - - public void AddPreservedName(MethodDef methodDef, string name) - { - GetNameScope(_methodNameScope).AddPreservedName(name); - } - - public void AddPreservedName(FieldDef fieldDef, string name) - { - GetNameScope(_fieldNameScope).AddPreservedName(name); - } - - public void AddPreservedName(PropertyDef propertyDef, string name) - { - GetNameScope(propertyDef.DeclaringType).AddPreservedName(name); - } - - public void AddPreservedName(EventDef eventDef, string name) - { - GetNameScope(eventDef.DeclaringType).AddPreservedName(name); - } - - public void AddPreservedNamespace(TypeDef typeDef, string name) - { - GetNameScope(_namespaceScope).AddPreservedName(name); - } - - public bool IsNamePreserved(VirtualMethodGroup virtualMethodGroup, string name) - { - var scope = GetNameScope(_methodNameScope); - return scope.IsNamePreserved(name); - } - - private string GetDefaultNewName(object scope, string originName) - { - return GetNameScope(scope).GetNewName(originName, false); - } - - public string GetNewNamespace(TypeDef typeDef, string originalNamespace, bool reuse) - { - if (string.IsNullOrEmpty(originalNamespace)) - { - return string.Empty; - } - return GetNameScope(_namespaceScope).GetNewName(originalNamespace, reuse); - } - - public string GetNewName(TypeDef typeDef, string originalName) - { - return GetDefaultNewName(_typeNameScope, originalName); - } - - public string GetNewName(MethodDef methodDef, string originalName) - { - Assert.IsFalse(methodDef.IsVirtual); - return GetDefaultNewName(_methodNameScope, originalName); - } - - public string GetNewName(VirtualMethodGroup virtualMethodGroup, string originalName) - { - var scope = GetNameScope(_methodNameScope); - return scope.GetNewName(originalName, false); - } - - public virtual string GetNewName(ParamDef param, string originalName) - { - return "1"; - } - - public string GetNewName(FieldDef fieldDef, string originalName) - { - return GetDefaultNewName(_fieldNameScope, originalName); - } - - public string GetNewName(PropertyDef propertyDef, string originalName) - { - return GetDefaultNewName(propertyDef.DeclaringType, originalName); - } - - public string GetNewName(EventDef eventDef, string originalName) - { - return GetDefaultNewName(eventDef.DeclaringType, originalName); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/NameMakers/NameMakerBase.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/NameMakers/NameMakerBase.cs.meta deleted file mode 100644 index d3ca8a02..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/NameMakers/NameMakerBase.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 205da3a8ebfd4ae4ba72d27db4b92d3f -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/NameMakers/NameMakerFactory.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/NameMakers/NameMakerFactory.cs deleted file mode 100644 index 08f3267d..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/NameMakers/NameMakerFactory.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System.Collections.Generic; - -namespace Obfuz.ObfusPasses.SymbolObfus.NameMakers -{ - public static class NameMakerFactory - { - public static INameMaker CreateDebugNameMaker() - { - return new DebugNameMaker(); - } - - public static INameMaker CreateNameMakerBaseASCIICharSet(string namePrefix) - { - var words = new List(); - for (int i = 0; i < 26; i++) - { - words.Add(((char)('a' + i)).ToString()); - words.Add(((char)('A' + i)).ToString()); - } - return new WordSetNameMaker(namePrefix, words); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/NameMakers/NameMakerFactory.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/NameMakers/NameMakerFactory.cs.meta deleted file mode 100644 index e1fb22c4..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/NameMakers/NameMakerFactory.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: afa0e87123ec9854b806098330c4980a -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/NameMakers/NameScope.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/NameMakers/NameScope.cs deleted file mode 100644 index 189ccf03..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/NameMakers/NameScope.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System.Collections.Generic; -using System.Text; - -namespace Obfuz.ObfusPasses.SymbolObfus.NameMakers -{ - - public class NameScope : NameScopeBase - { - private readonly string _namePrefix; - private readonly List _wordSet; - private int _nextIndex; - - public NameScope(string namePrefix, List wordSet) - { - _namePrefix = namePrefix; - _wordSet = wordSet; - _nextIndex = 0; - } - - protected override void BuildNewName(StringBuilder nameBuilder, string originalName, string lastName) - { - nameBuilder.Append(_namePrefix); - for (int i = _nextIndex++; ;) - { - nameBuilder.Append(_wordSet[i % _wordSet.Count]); - i = i / _wordSet.Count; - if (i == 0) - { - break; - } - } - - // keep generic type name pattern {name}`{n}, if not, il2cpp may raise exception in typeof(G) when G contains a field likes `T a`. - int index = originalName.LastIndexOf('`'); - if (index != -1) - { - nameBuilder.Append(originalName.Substring(index)); - } - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/NameMakers/NameScope.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/NameMakers/NameScope.cs.meta deleted file mode 100644 index e2242370..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/NameMakers/NameScope.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: a35c5c4b49c98a84f94b690c26900c33 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/NameMakers/NameScopeBase.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/NameMakers/NameScopeBase.cs deleted file mode 100644 index daa8cc8b..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/NameMakers/NameScopeBase.cs +++ /dev/null @@ -1,63 +0,0 @@ -using System.Collections.Generic; -using System.Text; - -namespace Obfuz.ObfusPasses.SymbolObfus.NameMakers -{ - public abstract class NameScopeBase : INameScope - { - - private readonly Dictionary _nameMap = new Dictionary(); - - private readonly HashSet _preservedNames = new HashSet(); - - - public bool AddPreservedName(string name) - { - if (!string.IsNullOrEmpty(name)) - { - return _preservedNames.Add(name); - } - return false; - } - - public bool IsNamePreserved(string name) - { - return _preservedNames.Contains(name); - } - - - protected abstract void BuildNewName(StringBuilder nameBuilder, string originalName, string lastName); - - private string CreateNewName(string originalName) - { - var nameBuilder = new StringBuilder(); - string lastName = null; - while (true) - { - nameBuilder.Clear(); - BuildNewName(nameBuilder, originalName, lastName); - string newName = nameBuilder.ToString(); - lastName = newName; - if (_preservedNames.Add(newName)) - { - return newName; - } - } - } - - public string GetNewName(string originalName, bool reuse) - { - if (!reuse) - { - return CreateNewName(originalName); - } - if (_nameMap.TryGetValue(originalName, out var newName)) - { - return newName; - } - newName = CreateNewName(originalName); - _nameMap[originalName] = newName; - return newName; - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/NameMakers/NameScopeBase.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/NameMakers/NameScopeBase.cs.meta deleted file mode 100644 index 17853c8a..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/NameMakers/NameScopeBase.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 26e6ae1f35e7f094c844cf1567b88a19 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/NameMakers/WordSetNameMaker.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/NameMakers/WordSetNameMaker.cs deleted file mode 100644 index f6edddb1..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/NameMakers/WordSetNameMaker.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System.Collections.Generic; - -namespace Obfuz.ObfusPasses.SymbolObfus.NameMakers -{ - - public class WordSetNameMaker : NameMakerBase - { - private readonly string _namePrefix; - private readonly List _wordSet; - - public WordSetNameMaker(string namePrefix, List wordSet) - { - _namePrefix = namePrefix; - _wordSet = wordSet; - } - - protected override INameScope CreateNameScope() - { - return new NameScope(_namePrefix, _wordSet); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/NameMakers/WordSetNameMaker.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/NameMakers/WordSetNameMaker.cs.meta deleted file mode 100644 index 23706b3d..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/NameMakers/WordSetNameMaker.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 47c92aea40a66e34b92f9eb5c0d380ca -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/Policies.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/Policies.meta deleted file mode 100644 index c16875c9..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/Policies.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 98e496436c90c0a4f82711af059471c7 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/Policies/CacheRenamePolicy.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/Policies/CacheRenamePolicy.cs deleted file mode 100644 index 7b84d727..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/Policies/CacheRenamePolicy.cs +++ /dev/null @@ -1,67 +0,0 @@ -using dnlib.DotNet; -using System.Collections.Generic; - -namespace Obfuz.ObfusPasses.SymbolObfus.Policies -{ - public class CacheRenamePolicy : ObfuscationPolicyBase - { - private readonly IObfuscationPolicy _underlyingPolicy; - - private readonly Dictionary _computeCache = new Dictionary(); - - public CacheRenamePolicy(IObfuscationPolicy underlyingPolicy) - { - _underlyingPolicy = underlyingPolicy; - } - - public override bool NeedRename(TypeDef typeDef) - { - if (!_computeCache.TryGetValue(typeDef, out var value)) - { - value = _underlyingPolicy.NeedRename(typeDef); - _computeCache[typeDef] = value; - } - return value; - } - - public override bool NeedRename(MethodDef methodDef) - { - if (!_computeCache.TryGetValue(methodDef, out var value)) - { - value = _underlyingPolicy.NeedRename(methodDef); - _computeCache[methodDef] = value; - } - return value; - } - - public override bool NeedRename(FieldDef fieldDef) - { - if (!_computeCache.TryGetValue(fieldDef, out var value)) - { - value = _underlyingPolicy.NeedRename(fieldDef); - _computeCache[fieldDef] = value; - } - return value; - } - - public override bool NeedRename(PropertyDef propertyDef) - { - if (!_computeCache.TryGetValue(propertyDef, out var value)) - { - value = _underlyingPolicy.NeedRename(propertyDef); - _computeCache[propertyDef] = value; - } - return value; - } - - public override bool NeedRename(EventDef eventDef) - { - if (!_computeCache.TryGetValue(eventDef, out var value)) - { - value = _underlyingPolicy.NeedRename(eventDef); - _computeCache[eventDef] = value; - } - return value; - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/Policies/CacheRenamePolicy.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/Policies/CacheRenamePolicy.cs.meta deleted file mode 100644 index ab4330f7..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/Policies/CacheRenamePolicy.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: c319b2ad62ad8794f9a8bc234c856d7f -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/Policies/CombineRenamePolicy.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/Policies/CombineRenamePolicy.cs deleted file mode 100644 index a84a5877..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/Policies/CombineRenamePolicy.cs +++ /dev/null @@ -1,40 +0,0 @@ -using dnlib.DotNet; -using System.Linq; - -namespace Obfuz.ObfusPasses.SymbolObfus.Policies -{ - public class CombineRenamePolicy : IObfuscationPolicy - { - private readonly IObfuscationPolicy[] _policies; - - public CombineRenamePolicy(params IObfuscationPolicy[] policies) - { - _policies = policies; - } - - public bool NeedRename(TypeDef typeDef) - { - return _policies.All(policy => policy.NeedRename(typeDef)); - } - - public bool NeedRename(MethodDef methodDef) - { - return _policies.All(policy => policy.NeedRename(methodDef)); - } - - public bool NeedRename(FieldDef fieldDef) - { - return _policies.All(policy => policy.NeedRename(fieldDef)); - } - - public bool NeedRename(PropertyDef propertyDef) - { - return _policies.All(policy => policy.NeedRename(propertyDef)); - } - - public bool NeedRename(EventDef eventDef) - { - return _policies.All(policy => policy.NeedRename(eventDef)); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/Policies/CombineRenamePolicy.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/Policies/CombineRenamePolicy.cs.meta deleted file mode 100644 index fcf6ea9d..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/Policies/CombineRenamePolicy.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 97be4546adeb71947bf644949c3a9e82 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/Policies/ConfigurableRenamePolicy.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/Policies/ConfigurableRenamePolicy.cs deleted file mode 100644 index 955c30d0..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/Policies/ConfigurableRenamePolicy.cs +++ /dev/null @@ -1,792 +0,0 @@ -using dnlib.DotNet; -using Obfuz.Utils; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Xml; -using UnityEngine; - -namespace Obfuz.ObfusPasses.SymbolObfus.Policies -{ - - public class ConfigurableRenamePolicy : ObfuscationPolicyBase - { - enum ModifierType - { - None = 0x0, - Private = 0x1, - Protected = 0x2, - Public = 0x3, - } - - class MethodRuleSpec - { - public NameMatcher nameMatcher; - public ModifierType? modifierType; - public bool? obfuscateName; - } - - class FieldRuleSpec - { - public NameMatcher nameMatcher; - public ModifierType? modifierType; - public bool? obfuscateName; - } - - class PropertyRuleSpec - { - public NameMatcher nameMatcher; - public ModifierType? modifierType; - public bool? obfuscateName; - public ObfuzScope? applyToMembers; - } - - class EventRuleSpec - { - public NameMatcher nameMatcher; - public ModifierType? modifierType; - public bool? obfuscateName; - public ObfuzScope? applyToMembers; - } - - class TypeRuleSpec - { - public NameMatcher nameMatcher; - public ModifierType? modifierType; - public ClassType? classType; - public List inheritTypes; - public List hasCustomAttributes; - public bool? obfuscateName; - public ObfuzScope? applyToMembers; - public bool applyToNestedTypes; - - public List fields; - public List methods; - public List properties; - public List events; - } - - class AssemblyRuleSpec - { - public string assemblyName; - public List types; - } - - private readonly Dictionary> _assemblyRuleSpecs = new Dictionary>(); - - private AssemblyRuleSpec ParseAssembly(XmlElement ele) - { - string assemblyName = ele.GetAttribute("name"); - if (string.IsNullOrEmpty(assemblyName)) - { - throw new Exception($"Invalid xml file, assembly name is empty"); - } - if (!_obfuscationAssemblyNames.Contains(assemblyName)) - { - throw new Exception($"unknown assembly name:{assemblyName}, not in ObfuzSettings.obfuscationAssemblyNames"); - } - var rule = new AssemblyRuleSpec() - { - assemblyName = assemblyName, - types = new List(), - }; - - foreach (XmlNode node in ele.ChildNodes) - { - if (!(node is XmlElement childElement)) - { - continue; - } - if (childElement.Name != "type") - { - throw new Exception($"Invalid xml file, unknown node {childElement.Name}"); - } - TypeRuleSpec type = ParseType(childElement); - rule.types.Add(type); - } - return rule; - } - - private enum ClassType - { - None = 0x0, - Class = 0x1, - Struct = 0x2, - Interface = 0x4, - Enum = 0x8, - Delegate = 0x10, - } - - private ClassType? ParseClassType(string classType) - { - if (string.IsNullOrEmpty(classType)) - { - return null; - } - - ClassType type = ClassType.None; - foreach (var s in classType.Split(',')) - { - switch (s) - { - case "class": type |= ClassType.Class; break; - case "struct": type |= ClassType.Struct; break; - case "interface": type |= ClassType.Interface; break; - case "enum": type |= ClassType.Enum; break; - case "delegate": type |= ClassType.Delegate; break; - default: throw new Exception($"Invalid class type {s}"); - } - } - return type; - } - - private ModifierType? ParseModifierType(string modifierType) - { - if (string.IsNullOrEmpty(modifierType)) - { - return null; - } - ModifierType type = ModifierType.None; - foreach (var s in modifierType.Split(',')) - { - switch (s) - { - case "public": type |= ModifierType.Public; break; - case "protected": type |= ModifierType.Protected; break; - case "private": type |= ModifierType.Private; break; - default: throw new Exception($"Invalid modifier type {s}"); - } - } - return type; - } - - - private ObfuzScope? ParseApplyToMembersScope(string membersScopeStr) - { - if (string.IsNullOrWhiteSpace(membersScopeStr)) - { - return null; - } - ObfuzScope scope = ObfuzScope.None; - - foreach (string s in membersScopeStr.Split(',')) - { - var s2 = s.Trim().ToLowerInvariant(); - switch (s2) - { - case "none": break; - case "field": scope |= ObfuzScope.Field; break; - case "eventname": scope |= ObfuzScope.EventName; break; - case "eventaddremovefirename": scope |= ObfuzScope.EventAddRemoveFireName; break; - case "event": scope |= ObfuzScope.Event; break; - case "methodname": scope |= ObfuzScope.MethodName; break; - case "method": scope |= ObfuzScope.MethodName; break; - case "propertyname": scope |= ObfuzScope.PropertyName; break; - case "propertygettersettername": scope |= ObfuzScope.PropertyGetterSetterName; break; - case "property": scope |= ObfuzScope.Property; break; - case "all": - case "*": scope |= ObfuzScope.All; break; - default: - { - throw new Exception($"Invalid applyToMembers scope {s2}"); - } - } - } - - return scope; - } - - private List ParseTypes(string inheritStr) - { - if (string.IsNullOrWhiteSpace(inheritStr)) - { - return null; - } - var inheritTypes = new List(); - foreach (var s in inheritStr.Split(',')) - { - var trimmed = s.Trim(); - if (!string.IsNullOrEmpty(trimmed)) - { - inheritTypes.Add(trimmed); - } - } - return inheritTypes; - } - - private TypeRuleSpec ParseType(XmlElement element) - { - var rule = new TypeRuleSpec(); - - rule.nameMatcher = new NameMatcher(element.GetAttribute("name")); - rule.obfuscateName = ConfigUtil.ParseNullableBool(element.GetAttribute("obName")); - rule.applyToMembers = ParseApplyToMembersScope(element.GetAttribute("applyToMembers")); - rule.applyToNestedTypes = ConfigUtil.ParseNullableBool(element.GetAttribute("applyToNestedTypes")) ?? true; - rule.modifierType = ParseModifierType(element.GetAttribute("modifier")); - rule.classType = ParseClassType(element.GetAttribute("classType")); - rule.inheritTypes = ParseTypes(element.GetAttribute("inherit")); - rule.hasCustomAttributes = ParseTypes(element.GetAttribute("hasCustomAttributes")); - - //rule.nestTypeRuleSpecs = new List(); - rule.fields = new List(); - rule.methods = new List(); - rule.properties = new List(); - rule.events = new List(); - foreach (XmlNode node in element.ChildNodes) - { - if (!(node is XmlElement childElement)) - { - continue; - } - switch (childElement.Name) - { - case "field": - { - var fieldRuleSpec = new FieldRuleSpec(); - fieldRuleSpec.nameMatcher = new NameMatcher(childElement.GetAttribute("name")); - fieldRuleSpec.modifierType = ParseModifierType(childElement.GetAttribute("modifier")); - fieldRuleSpec.obfuscateName = ConfigUtil.ParseNullableBool(childElement.GetAttribute("obName")); - rule.fields.Add(fieldRuleSpec); - break; - } - case "method": - { - var methodRuleSpec = new MethodRuleSpec(); - methodRuleSpec.nameMatcher = new NameMatcher(childElement.GetAttribute("name")); - methodRuleSpec.modifierType = ParseModifierType(childElement.GetAttribute("modifier")); - methodRuleSpec.obfuscateName = ConfigUtil.ParseNullableBool(childElement.GetAttribute("obName")); - rule.methods.Add(methodRuleSpec); - break; - } - case "property": - { - var propertyRulerSpec = new PropertyRuleSpec(); - propertyRulerSpec.nameMatcher = new NameMatcher(childElement.GetAttribute("name")); - propertyRulerSpec.modifierType = ParseModifierType(childElement.GetAttribute("modifier")); - propertyRulerSpec.obfuscateName = ConfigUtil.ParseNullableBool(childElement.GetAttribute("obName")); - propertyRulerSpec.applyToMembers = ParseApplyToMembersScope(childElement.GetAttribute("applyToMembers")); - rule.properties.Add(propertyRulerSpec); - break; - } - case "event": - { - var eventRuleSpec = new EventRuleSpec(); - eventRuleSpec.nameMatcher = new NameMatcher(childElement.GetAttribute("name")); - eventRuleSpec.modifierType = ParseModifierType(childElement.GetAttribute("modifier")); - eventRuleSpec.obfuscateName = ConfigUtil.ParseNullableBool(childElement.GetAttribute("obName")); - eventRuleSpec.applyToMembers = ParseApplyToMembersScope(childElement.GetAttribute("applyToMembers")); - rule.events.Add(eventRuleSpec); - break; - } - default: throw new Exception($"Invalid xml file, unknown node {childElement.Name} in type node"); - } - } - return rule; - } - - private void LoadXmls(List xmlFiles) - { - var rawAssemblySpecElements = new List(); - foreach (string file in xmlFiles) - { - LoadRawXml(file, rawAssemblySpecElements); - } - ResolveAssemblySpecs(rawAssemblySpecElements); - } - - private void ResolveAssemblySpecs(List rawAssemblySpecElements) - { - foreach (XmlElement ele in rawAssemblySpecElements) - { - var assemblyRule = ParseAssembly(ele); - if (!_assemblyRuleSpecs.TryGetValue(assemblyRule.assemblyName, out var existAssemblyRules)) - { - existAssemblyRules = new List(); - _assemblyRuleSpecs.Add(assemblyRule.assemblyName, existAssemblyRules); - } - existAssemblyRules.Add(assemblyRule); - } - } - - private void LoadRawXml(string xmlFile, List rawAssemblyElements) - { - Debug.Log($"ObfuscateRule::LoadXml {xmlFile}"); - var doc = new XmlDocument(); - doc.Load(xmlFile); - var root = doc.DocumentElement; - if (root.Name != "obfuz") - { - throw new Exception($"Invalid xml file {xmlFile}, root name should be 'obfuz'"); - } - foreach (XmlNode node in root.ChildNodes) - { - if (!(node is XmlElement element)) - { - continue; - } - switch (element.Name) - { - case "assembly": - { - rawAssemblyElements.Add(element); - break; - } - default: - { - throw new Exception($"Invalid xml file {xmlFile}, unknown node {element.Name}"); - } - } - } - } - - private ModifierType ComputeModifierType(TypeAttributes visibility) - { - if (visibility == TypeAttributes.NotPublic || visibility == TypeAttributes.NestedPrivate) - { - return ModifierType.Private; - } - if (visibility == TypeAttributes.Public || visibility == TypeAttributes.NestedPublic) - { - return ModifierType.Public; - } - return ModifierType.Protected; - } - - private ModifierType ComputeModifierType(FieldAttributes access) - { - if (access == FieldAttributes.Private || access == FieldAttributes.PrivateScope) - { - return ModifierType.Private; - } - if (access == FieldAttributes.Public) - { - return ModifierType.Public; - } - return ModifierType.Protected; - } - - //private ModifierType ComputeModifierType(MethodAttributes access) - //{ - // if (access == MethodAttributes.Private || access == MethodAttributes.PrivateScope) - // { - // return ModifierType.Private; - // } - // if (access == MethodAttributes.Public) - // { - // return ModifierType.Public; - // } - // return ModifierType.Protected; - //} - - private bool MatchModifier(ModifierType? modifierType, TypeDef typeDef) - { - return modifierType == null || (modifierType & ComputeModifierType(typeDef.Visibility)) != 0; - } - - private bool MatchModifier(ModifierType? modifierType, FieldDef fieldDef) - { - return modifierType == null || (modifierType & ComputeModifierType(fieldDef.Access)) != 0; - } - - private bool MatchModifier(ModifierType? modifierType, MethodDef methodDef) - { - return modifierType == null || (modifierType & ComputeModifierType((FieldAttributes)methodDef.Access)) != 0; - } - - private bool MatchModifier(ModifierType? modifierType, PropertyDef propertyDef) - { - return modifierType == null || (modifierType & ComputeModifierType((FieldAttributes)propertyDef.Attributes)) != 0; - } - - private bool MatchModifier(ModifierType? modifierType, EventDef eventDef) - { - return modifierType == null || (modifierType & ComputeModifierType((FieldAttributes)eventDef.Attributes)) != 0; - } - - private class MethodComputeCache - { - public bool obfuscateName = true; - public bool obfuscateParam = true; - public bool obfuscateBody = true; - } - - private class RuleResult - { - public bool? obfuscateName; - } - - private readonly Dictionary _typeSpecCache = new Dictionary(); - private readonly Dictionary _methodSpecCache = new Dictionary(); - private readonly Dictionary _fieldSpecCache = new Dictionary(); - private readonly Dictionary _propertySpecCache = new Dictionary(); - private readonly Dictionary _eventSpecCache = new Dictionary(); - - - private readonly HashSet _obfuscationAssemblyNames; - private readonly List _assembliesToObfuscate; - - public ConfigurableRenamePolicy(List obfuscationAssemblyNames, List assembliesToObfuscate, List xmlFiles) - { - _obfuscationAssemblyNames = new HashSet(obfuscationAssemblyNames); - _assembliesToObfuscate = assembliesToObfuscate; - LoadXmls(xmlFiles); - BuildRuleResultCaches(); - } - - private bool MatchClassType(ClassType? classType, TypeDef typeDef) - { - if (classType == null) - { - return true; - } - if (typeDef.IsInterface && (classType & ClassType.Interface) != 0) - { - return true; - } - if (typeDef.IsEnum && (classType & ClassType.Enum) != 0) - { - return true; - } - if (typeDef.IsDelegate && (classType & ClassType.Delegate) != 0) - { - return true; - } - if (typeDef.IsValueType && !typeDef.IsEnum && (classType & ClassType.Struct) != 0) - { - return true; - } - if (!typeDef.IsValueType && !typeDef.IsInterface && !typeDef.IsDelegate && (classType & ClassType.Class) != 0) - { - return true; - } - return false; - } - - - private RuleResult GetOrCreateTypeRuleResult(TypeDef typeDef) - { - if (!_typeSpecCache.TryGetValue(typeDef, out var ruleResult)) - { - ruleResult = new RuleResult(); - _typeSpecCache.Add(typeDef, ruleResult); - } - return ruleResult; - } - - private RuleResult GetOrCreateFieldRuleResult(FieldDef field) - { - if (!_fieldSpecCache.TryGetValue(field, out var ruleResult)) - { - ruleResult = new RuleResult(); - _fieldSpecCache.Add(field, ruleResult); - } - return ruleResult; - } - - private RuleResult GetOrCreateMethodRuleResult(MethodDef method) - { - if (!_methodSpecCache.TryGetValue(method, out var ruleResult)) - { - ruleResult = new RuleResult(); - _methodSpecCache.Add(method, ruleResult); - } - return ruleResult; - } - - private RuleResult GetOrCreatePropertyRuleResult(PropertyDef property) - { - if (!_propertySpecCache.TryGetValue(property, out var ruleResult)) - { - ruleResult = new RuleResult(); - _propertySpecCache.Add(property, ruleResult); - } - return ruleResult; - } - - private RuleResult GetOrCreateEventRuleResult(EventDef eventDef) - { - if (!_eventSpecCache.TryGetValue(eventDef, out var ruleResult)) - { - ruleResult = new RuleResult(); - _eventSpecCache.Add(eventDef, ruleResult); - } - return ruleResult; - } - - private void BuildTypeRuleResult(TypeRuleSpec typeSpec, TypeDef typeDef, RuleResult typeRuleResult) - { - string typeName = typeDef.FullName; - - if (typeSpec.obfuscateName != null) - { - typeRuleResult.obfuscateName = typeSpec.obfuscateName; - } - - foreach (var fieldDef in typeDef.Fields) - { - RuleResult fieldRuleResult = GetOrCreateFieldRuleResult(fieldDef); - if (typeSpec.applyToMembers != null && (typeSpec.applyToMembers & ObfuzScope.Field) != 0 && typeSpec.obfuscateName != null) - { - fieldRuleResult.obfuscateName = typeSpec.obfuscateName; - } - foreach (var fieldSpec in typeSpec.fields) - { - if (fieldSpec.nameMatcher.IsMatch(fieldDef.Name) && MatchModifier(fieldSpec.modifierType, fieldDef)) - { - if (fieldSpec.obfuscateName != null) - { - fieldRuleResult.obfuscateName = fieldSpec.obfuscateName; - } - } - } - } - - foreach (MethodDef methodDef in typeDef.Methods) - { - RuleResult methodRuleResult = GetOrCreateMethodRuleResult(methodDef); - if (typeSpec.applyToMembers != null && (typeSpec.applyToMembers & ObfuzScope.Method) != 0 && typeSpec.obfuscateName != null) - { - methodRuleResult.obfuscateName = typeSpec.obfuscateName; - } - } - - foreach (var eventDef in typeDef.Events) - { - RuleResult eventRuleResult = GetOrCreateEventRuleResult(eventDef); - if (typeSpec.applyToMembers != null && (typeSpec.applyToMembers & ObfuzScope.EventName) != 0 && typeSpec.obfuscateName != null) - { - eventRuleResult.obfuscateName = typeSpec.obfuscateName; - } - foreach (var eventSpec in typeSpec.events) - { - if (!eventSpec.nameMatcher.IsMatch(eventDef.Name) || !MatchModifier(eventSpec.modifierType, eventDef)) - { - continue; - } - if (typeSpec.obfuscateName != null && typeSpec.applyToMembers != null && (typeSpec.applyToMembers & ObfuzScope.EventAddRemoveFireName) != 0) - { - if (eventDef.AddMethod != null) - { - GetOrCreateMethodRuleResult(eventDef.AddMethod).obfuscateName = typeSpec.obfuscateName; - } - if (eventDef.RemoveMethod != null) - { - GetOrCreateMethodRuleResult(eventDef.RemoveMethod).obfuscateName = typeSpec.obfuscateName; - } - if (eventDef.InvokeMethod != null) - { - GetOrCreateMethodRuleResult(eventDef.InvokeMethod).obfuscateName = typeSpec.obfuscateName; - } - } - if (eventSpec.obfuscateName != null) - { - eventRuleResult.obfuscateName = eventSpec.obfuscateName; - if (eventSpec.applyToMembers != null && (eventSpec.applyToMembers & ObfuzScope.EventAddRemoveFireName) != 0) - { - if (eventDef.AddMethod != null) - { - GetOrCreateMethodRuleResult(eventDef.AddMethod).obfuscateName = eventSpec.obfuscateName; - } - if (eventDef.RemoveMethod != null) - { - GetOrCreateMethodRuleResult(eventDef.RemoveMethod).obfuscateName = eventSpec.obfuscateName; - } - if (eventDef.InvokeMethod != null) - { - GetOrCreateMethodRuleResult(eventDef.InvokeMethod).obfuscateName = eventSpec.obfuscateName; - } - } - } - } - } - - foreach (var propertyDef in typeDef.Properties) - { - RuleResult propertyRuleResult = GetOrCreatePropertyRuleResult(propertyDef); - if (typeSpec.applyToMembers != null && (typeSpec.applyToMembers & ObfuzScope.PropertyName) != 0 && typeSpec.obfuscateName != null) - { - propertyRuleResult.obfuscateName = typeSpec.obfuscateName; - } - foreach (var propertySpec in typeSpec.properties) - { - if (!propertySpec.nameMatcher.IsMatch(propertyDef.Name) || !MatchModifier(propertySpec.modifierType, propertyDef)) - { - continue; - } - if (typeSpec.obfuscateName != null && typeSpec.applyToMembers != null && (typeSpec.applyToMembers & ObfuzScope.PropertyGetterSetterName) != 0) - { - if (propertyDef.GetMethod != null) - { - GetOrCreateMethodRuleResult(propertyDef.GetMethod).obfuscateName = typeSpec.obfuscateName; - } - if (propertyDef.SetMethod != null) - { - GetOrCreateMethodRuleResult(propertyDef.SetMethod).obfuscateName = typeSpec.obfuscateName; - } - } - if (propertySpec.obfuscateName != null) - { - propertyRuleResult.obfuscateName = propertySpec.obfuscateName; - if (propertySpec.applyToMembers != null && (propertySpec.applyToMembers & ObfuzScope.PropertyGetterSetterName) != 0) - { - if (propertyDef.GetMethod != null) - { - GetOrCreateMethodRuleResult(propertyDef.GetMethod).obfuscateName = propertySpec.obfuscateName; - } - if (propertyDef.SetMethod != null) - { - GetOrCreateMethodRuleResult(propertyDef.SetMethod).obfuscateName = propertySpec.obfuscateName; - } - } - } - } - } - foreach (MethodDef methodDef in typeDef.Methods) - { - RuleResult methodRuleResult = GetOrCreateMethodRuleResult(methodDef); - foreach (MethodRuleSpec methodSpec in typeSpec.methods) - { - if (!methodSpec.nameMatcher.IsMatch(methodDef.Name) || !MatchModifier(methodSpec.modifierType, methodDef)) - { - continue; - } - if (methodSpec.obfuscateName != null) - { - methodRuleResult.obfuscateName = methodSpec.obfuscateName; - } - } - } - - if (typeSpec.applyToNestedTypes) - { - foreach (TypeDef nestedType in typeDef.NestedTypes) - { - var nestedRuleResult = GetOrCreateTypeRuleResult(nestedType); - BuildTypeRuleResult(typeSpec, nestedType, nestedRuleResult); - } - } - } - - private bool MatchInheritTypes(List inheritTypes, TypeDef typeDef) - { - if (inheritTypes == null || inheritTypes.Count == 0) - { - return true; - } - TypeDef currentType = typeDef; - while (currentType != null) - { - if (inheritTypes.Contains(currentType.FullName)) - { - return true; - } - foreach (var interfaceType in currentType.Interfaces) - { - if (inheritTypes.Contains(interfaceType.Interface.FullName)) - { - return true; - } - } - currentType = MetaUtil.GetBaseTypeDef(currentType); - } - return false; - } - - private bool MatchCustomAttributes(List customAttributes, TypeDef typeDef) - { - if (customAttributes == null || customAttributes.Count == 0) - { - return true; - } - foreach (string customAttributeName in customAttributes) - { - if (typeDef.CustomAttributes.Find(customAttributeName) != null) - { - return true; - } - } - return false; - } - - private IEnumerable GetMatchTypes(ModuleDef mod, List types, TypeRuleSpec typeSpec) - { - if (typeSpec.nameMatcher.IsWildcardPattern) - { - foreach (var typeDef in types) - { - if (!typeSpec.nameMatcher.IsMatch(typeDef.FullName) - || !MatchModifier(typeSpec.modifierType, typeDef) - || !MatchClassType(typeSpec.classType, typeDef) - || !MatchInheritTypes(typeSpec.inheritTypes, typeDef) - || !MatchCustomAttributes(typeSpec.hasCustomAttributes, typeDef)) - { - continue; - } - yield return typeDef; - } - } - else - { - TypeDef typeDef = mod.FindNormal(typeSpec.nameMatcher.NameOrPattern); - if (typeDef != null - && MatchModifier(typeSpec.modifierType, typeDef) - && MatchClassType(typeSpec.classType, typeDef) - && MatchInheritTypes(typeSpec.inheritTypes, typeDef) - && MatchCustomAttributes(typeSpec.hasCustomAttributes, typeDef)) - { - yield return typeDef; - } - } - } - - private void BuildRuleResultCaches() - { - foreach (AssemblyRuleSpec assSpec in _assemblyRuleSpecs.Values.SelectMany(arr => arr)) - { - ModuleDef module = _assembliesToObfuscate.FirstOrDefault(m => m.Assembly.Name == assSpec.assemblyName); - if (module == null) - { - continue; - } - List types = module.GetTypes().ToList(); - foreach (TypeRuleSpec typeSpec in assSpec.types) - { - foreach (var typeDef in GetMatchTypes(module, types, typeSpec)) - { - var ruleResult = GetOrCreateTypeRuleResult(typeDef); - if (typeSpec.obfuscateName != null) - { - ruleResult.obfuscateName = typeSpec.obfuscateName; - } - BuildTypeRuleResult(typeSpec, typeDef, ruleResult); - } - } - } - } - - public override bool NeedRename(TypeDef typeDef) - { - return GetOrCreateTypeRuleResult(typeDef).obfuscateName != false; - } - - public override bool NeedRename(MethodDef methodDef) - { - return GetOrCreateMethodRuleResult(methodDef).obfuscateName != false; - } - - public override bool NeedRename(FieldDef fieldDef) - { - return GetOrCreateFieldRuleResult(fieldDef).obfuscateName != false; - } - - public override bool NeedRename(PropertyDef propertyDef) - { - return GetOrCreatePropertyRuleResult(propertyDef).obfuscateName != false; - } - - public override bool NeedRename(EventDef eventDef) - { - return GetOrCreateEventRuleResult(eventDef).obfuscateName != false; - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/Policies/ConfigurableRenamePolicy.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/Policies/ConfigurableRenamePolicy.cs.meta deleted file mode 100644 index e6b4feea..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/Policies/ConfigurableRenamePolicy.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 9c063bc949939fe44972c3d99870527e -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/Policies/ObfuscationPolicyBase.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/Policies/ObfuscationPolicyBase.cs deleted file mode 100644 index 6a271ad0..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/Policies/ObfuscationPolicyBase.cs +++ /dev/null @@ -1,33 +0,0 @@ -using dnlib.DotNet; - -namespace Obfuz.ObfusPasses.SymbolObfus.Policies -{ - public abstract class ObfuscationPolicyBase : IObfuscationPolicy - { - - public virtual bool NeedRename(TypeDef typeDef) - { - return true; - } - - public virtual bool NeedRename(MethodDef methodDef) - { - return true; - } - - public virtual bool NeedRename(FieldDef fieldDef) - { - return true; - } - - public virtual bool NeedRename(PropertyDef propertyDef) - { - return true; - } - - public virtual bool NeedRename(EventDef eventDef) - { - return true; - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/Policies/ObfuscationPolicyBase.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/Policies/ObfuscationPolicyBase.cs.meta deleted file mode 100644 index 2d0bf054..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/Policies/ObfuscationPolicyBase.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 6ab98107a2ef9624b9b8a53061f682c3 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/Policies/SupportPassPolicy.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/Policies/SupportPassPolicy.cs deleted file mode 100644 index 132ed15a..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/Policies/SupportPassPolicy.cs +++ /dev/null @@ -1,45 +0,0 @@ -using dnlib.DotNet; - -namespace Obfuz.ObfusPasses.SymbolObfus.Policies -{ - internal class SupportPassPolicy : ObfuscationPolicyBase - { - private readonly ConfigurablePassPolicy _policy; - - - private bool Support(ObfuscationPassType passType) - { - return passType.HasFlag(ObfuscationPassType.SymbolObfus); - } - - public SupportPassPolicy(ConfigurablePassPolicy policy) - { - _policy = policy; - } - - public override bool NeedRename(TypeDef typeDef) - { - return Support(_policy.GetTypeObfuscationPasses(typeDef)); - } - - public override bool NeedRename(MethodDef methodDef) - { - return Support(_policy.GetMethodObfuscationPasses(methodDef)); - } - - public override bool NeedRename(FieldDef fieldDef) - { - return Support(_policy.GetFieldObfuscationPasses(fieldDef)); - } - - public override bool NeedRename(PropertyDef propertyDef) - { - return Support(_policy.GetPropertyObfuscationPasses(propertyDef)); - } - - public override bool NeedRename(EventDef eventDef) - { - return Support(_policy.GetEventObfuscationPasses(eventDef)); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/Policies/SupportPassPolicy.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/Policies/SupportPassPolicy.cs.meta deleted file mode 100644 index bf7d3b8d..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/Policies/SupportPassPolicy.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 584dd4d4e9b9fa64090611d84b50980b -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/Policies/SystemRenamePolicy.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/Policies/SystemRenamePolicy.cs deleted file mode 100644 index 68d4ea2f..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/Policies/SystemRenamePolicy.cs +++ /dev/null @@ -1,120 +0,0 @@ -using dnlib.DotNet; -using Obfuz.Editor; -using Obfuz.Utils; -using System.Collections.Generic; - -namespace Obfuz.ObfusPasses.SymbolObfus.Policies -{ - public class SystemRenamePolicy : ObfuscationPolicyBase - { - private readonly ObfuzIgnoreScopeComputeCache _obfuzIgnoreScopeComputeCache; - - public SystemRenamePolicy(ObfuzIgnoreScopeComputeCache obfuzIgnoreScopeComputeCache) - { - _obfuzIgnoreScopeComputeCache = obfuzIgnoreScopeComputeCache; - } - - private readonly HashSet _fullIgnoreTypeFullNames = new HashSet - { - ConstValues.ObfuzIgnoreAttributeFullName, - ConstValues.ObfuzScopeFullName, - ConstValues.EncryptFieldAttributeFullName, - ConstValues.EmbeddedAttributeFullName, - ConstValues.ZluaLuaInvokeAttributeFullName, - ConstValues.ZluaLuaCallbackAttributeFullName, - ConstValues.ZluaLuaMarshalAsAttributeFullName, - ConstValues.BurstCompileFullName, - }; - - - private readonly HashSet _fullIgnoreTypeNames = new HashSet - { - ConstValues.MonoPInvokeCallbackAttributeName, - }; - - private bool IsFullIgnoreObfuscatedType(TypeDef typeDef) - { - return _fullIgnoreTypeFullNames.Contains(typeDef.FullName) || _fullIgnoreTypeNames.Contains(typeDef.Name) || MetaUtil.HasMicrosoftCodeAnalysisEmbeddedAttribute(typeDef); - } - - public override bool NeedRename(TypeDef typeDef) - { - string name = typeDef.Name; - if (name == "") - { - return false; - } - if (IsFullIgnoreObfuscatedType(typeDef)) - { - return false; - } - - if (_obfuzIgnoreScopeComputeCache.HasSelfOrEnclosingOrInheritObfuzIgnoreScope(typeDef, ObfuzScope.TypeName)) - { - return false; - } - return true; - } - - public override bool NeedRename(MethodDef methodDef) - { - if (methodDef.DeclaringType.IsDelegate || IsFullIgnoreObfuscatedType(methodDef.DeclaringType)) - { - return false; - } - if (methodDef.Name == ".ctor" || methodDef.Name == ".cctor") - { - return false; - } - - if (_obfuzIgnoreScopeComputeCache.HasSelfOrInheritPropertyOrEventOrOrTypeDefIgnoreMethodName(methodDef)) - { - return false; - } - return true; - } - - public override bool NeedRename(FieldDef fieldDef) - { - if (fieldDef.DeclaringType.IsDelegate || IsFullIgnoreObfuscatedType(fieldDef.DeclaringType)) - { - return false; - } - if (_obfuzIgnoreScopeComputeCache.HasSelfOrDeclaringOrEnclosingOrInheritObfuzIgnoreScope(fieldDef, fieldDef.DeclaringType, ObfuzScope.Field)) - { - return false; - } - if (fieldDef.DeclaringType.IsEnum && !fieldDef.IsStatic) - { - return false; - } - return true; - } - - public override bool NeedRename(PropertyDef propertyDef) - { - if (propertyDef.DeclaringType.IsDelegate || IsFullIgnoreObfuscatedType(propertyDef.DeclaringType)) - { - return false; - } - if (_obfuzIgnoreScopeComputeCache.HasSelfOrDeclaringOrEnclosingOrInheritObfuzIgnoreScope(propertyDef, propertyDef.DeclaringType, ObfuzScope.PropertyName)) - { - return false; - } - return true; - } - - public override bool NeedRename(EventDef eventDef) - { - if (eventDef.DeclaringType.IsDelegate || IsFullIgnoreObfuscatedType(eventDef.DeclaringType)) - { - return false; - } - if (_obfuzIgnoreScopeComputeCache.HasSelfOrDeclaringOrEnclosingOrInheritObfuzIgnoreScope(eventDef, eventDef.DeclaringType, ObfuzScope.EventName)) - { - return false; - } - return true; - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/Policies/SystemRenamePolicy.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/Policies/SystemRenamePolicy.cs.meta deleted file mode 100644 index b7d45e3e..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/Policies/SystemRenamePolicy.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 7b7b98f2ff075c04aa9bd989f8797f00 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/Policies/UnityRenamePolicy.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/Policies/UnityRenamePolicy.cs deleted file mode 100644 index 594c5a1c..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/Policies/UnityRenamePolicy.cs +++ /dev/null @@ -1,264 +0,0 @@ -using dnlib.DotNet; -using Obfuz.Utils; -using System.Collections.Generic; -using System.Linq; - -namespace Obfuz.ObfusPasses.SymbolObfus.Policies -{ - - public class UnityRenamePolicy : ObfuscationPolicyBase - { - private static HashSet s_monoBehaviourEvents = new HashSet { - - // MonoBehaviour events - "Awake", - "FixedUpdate", - "LateUpdate", - "OnAnimatorIK", - - "OnAnimatorMove", - "OnApplicationFocus", - "OnApplicationPause", - "OnApplicationQuit", - "OnAudioFilterRead", - - "OnBecameVisible", - "OnBecameInvisible", - - "OnCollisionEnter", - "OnCollisionEnter2D", - "OnCollisionExit", - "OnCollisionExit2D", - "OnCollisionStay", - "OnCollisionStay2D", - "OnConnectedToServer", - "OnControllerColliderHit", - - "OnDrawGizmos", - "OnDrawGizmosSelected", - "OnDestroy", - "OnDisable", - "OnDisconnectedFromServer", - - "OnEnable", - - "OnFailedToConnect", - "OnFailedToConnectToMasterServer", - - "OnGUI", - - "OnJointBreak", - "OnJointBreak2D", - - "OnMasterServerEvent", - "OnMouseDown", - "OnMouseDrag", - "OnMouseEnter", - "OnMouseExit", - "OnMouseOver", - "OnMouseUp", - "OnMouseUpAsButton", - - "OnNetworkInstantiate", - - "OnParticleSystemStopped", - "OnParticleTrigger", - "OnParticleUpdateJobScheduled", - "OnPlayerConnected", - "OnPlayerDisconnected", - "OnPostRender", - "OnPreCull", - "OnPreRender", - "OnRenderImage", - "OnRenderObject", - - "OnSerializeNetworkView", - "OnServerInitialized", - - "OnTransformChildrenChanged", - "OnTransformParentChanged", - "OnTriggerEnter", - "OnTriggerEnter2D", - "OnTriggerExit", - "OnTriggerExit2D", - "OnTriggerStay", - "OnTriggerStay2D", - - "OnValidate", - "OnWillRenderObject", - "Reset", - "Start", - "Update", - - // Animator/StateMachineBehaviour - "OnStateEnter", - "OnStateExit", - "OnStateMove", - "OnStateUpdate", - "OnStateIK", - "OnStateMachineEnter", - "OnStateMachineExit", - - // ParticleSystem - "OnParticleTrigger", - "OnParticleCollision", - "OnParticleSystemStopped", - - // UGUI/EventSystems - "OnPointerClick", - "OnPointerDown", - "OnPointerUp", - "OnPointerEnter", - "OnPointerExit", - "OnDrag", - "OnBeginDrag", - "OnEndDrag", - "OnDrop", - "OnScroll", - "OnSelect", - "OnDeselect", - "OnMove", - "OnSubmit", - "OnCancel", -}; - - private readonly CachedDictionary _computeDeclaringTypeDisableAllMemberRenamingCache; - private readonly CachedDictionary _isSerializableCache; - private readonly CachedDictionary _isInheritFromMonoBehaviourCache; - private readonly CachedDictionary _isScriptOrSerializableTypeCache; - - public UnityRenamePolicy() - { - _computeDeclaringTypeDisableAllMemberRenamingCache = new CachedDictionary(ComputeDeclaringTypeDisableAllMemberRenaming); - _isSerializableCache = new CachedDictionary(MetaUtil.IsSerializableType); - _isInheritFromMonoBehaviourCache = new CachedDictionary(MetaUtil.IsInheritFromMonoBehaviour); - _isScriptOrSerializableTypeCache = new CachedDictionary(MetaUtil.IsScriptOrSerializableType); - } - - private bool IsUnitySourceGeneratedAssemblyType(TypeDef typeDef) - { - if (typeDef.Name.StartsWith("UnitySourceGeneratedAssemblyMonoScriptTypes_")) - { - return true; - } - if (typeDef.FullName == "Unity.Entities.CodeGeneratedRegistry.AssemblyTypeRegistry") - { - return true; - } - if (typeDef.Name.StartsWith("__JobReflectionRegistrationOutput")) - { - return true; - } - if (MetaUtil.HasDOTSCompilerGeneratedAttribute(typeDef)) - { - return true; - } - if (typeDef.DeclaringType != null) - { - return IsUnitySourceGeneratedAssemblyType(typeDef.DeclaringType); - } - return false; - } - - private bool ComputeDeclaringTypeDisableAllMemberRenaming(TypeDef typeDef) - { - if (typeDef.IsEnum && MetaUtil.HasBlackboardEnumAttribute(typeDef)) - { - return true; - } - if (IsUnitySourceGeneratedAssemblyType(typeDef)) - { - return true; - } - if (MetaUtil.IsInheritFromDOTSTypes(typeDef)) - { - return true; - } - return false; - } - - public override bool NeedRename(TypeDef typeDef) - { - if (_isScriptOrSerializableTypeCache.GetValue(typeDef)) - { - return false; - } - if (_computeDeclaringTypeDisableAllMemberRenamingCache.GetValue(typeDef)) - { - return false; - } - if (MetaUtil.HasBurstCompileAttribute(typeDef)) - { - return false; - } - if (typeDef.Methods.Any(m => MetaUtil.HasRuntimeInitializeOnLoadMethodAttribute(m))) - { - return false; - } - return true; - } - - public override bool NeedRename(MethodDef methodDef) - { - TypeDef typeDef = methodDef.DeclaringType; - if (s_monoBehaviourEvents.Contains(methodDef.Name) && _isInheritFromMonoBehaviourCache.GetValue(typeDef)) - { - return false; - } - if (_computeDeclaringTypeDisableAllMemberRenamingCache.GetValue(typeDef)) - { - return false; - } - if (MetaUtil.HasRuntimeInitializeOnLoadMethodAttribute(methodDef)) - { - return false; - } - if (MetaUtil.HasBurstCompileAttribute(methodDef) || MetaUtil.HasBurstCompileAttribute(methodDef.DeclaringType) || MetaUtil.HasDOTSCompilerGeneratedAttribute(methodDef)) - { - return false; - } - return true; - } - - public override bool NeedRename(FieldDef fieldDef) - { - TypeDef typeDef = fieldDef.DeclaringType; - if (_isScriptOrSerializableTypeCache.GetValue(typeDef)) - { - if (typeDef.IsEnum) - { - return false; - } - if (fieldDef.IsPublic && !fieldDef.IsStatic) - { - return false; - } - if (!fieldDef.IsStatic && MetaUtil.IsSerializableField(fieldDef)) - { - return false; - } - } - if (_computeDeclaringTypeDisableAllMemberRenamingCache.GetValue(typeDef)) - { - return false; - } - return true; - } - - public override bool NeedRename(PropertyDef propertyDef) - { - TypeDef typeDef = propertyDef.DeclaringType; - if (_isSerializableCache.GetValue(typeDef)) - { - bool isGetterPublic = propertyDef.GetMethod != null && propertyDef.GetMethod.IsPublic && !propertyDef.GetMethod.IsStatic; - bool isSetterPublic = propertyDef.SetMethod != null && propertyDef.SetMethod.IsPublic && !propertyDef.SetMethod.IsStatic; - - if (isGetterPublic || isSetterPublic) - { - return false; - } - } - return true; - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/Policies/UnityRenamePolicy.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/Policies/UnityRenamePolicy.cs.meta deleted file mode 100644 index f8f6f99a..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/Policies/UnityRenamePolicy.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 4357f35c667599246b2481b093f41f04 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/ReflectionCompatibilityDetector.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/ReflectionCompatibilityDetector.cs deleted file mode 100644 index 8d644bbe..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/ReflectionCompatibilityDetector.cs +++ /dev/null @@ -1,306 +0,0 @@ -using dnlib.DotNet; -using dnlib.DotNet.Emit; -using System; -using System.Collections.Generic; -using System.Linq; -using UnityEngine; - -namespace Obfuz.ObfusPasses.SymbolObfus -{ - public class ReflectionCompatibilityDetector - { - private readonly HashSet _assembliesToObfuscate; - private readonly List _obfuscatedAndNotObfuscatedModules; - private readonly IObfuscationPolicy _renamePolicy; - - public ReflectionCompatibilityDetector(List assembliesToObfuscate, List obfuscatedAndNotObfuscatedModules, IObfuscationPolicy renamePolicy) - { - _assembliesToObfuscate = new HashSet(assembliesToObfuscate); - _obfuscatedAndNotObfuscatedModules = obfuscatedAndNotObfuscatedModules; - _renamePolicy = renamePolicy; - } - - public void Analyze() - { - foreach (ModuleDef mod in _obfuscatedAndNotObfuscatedModules) - { - foreach (TypeDef type in mod.GetTypes()) - { - foreach (MethodDef method in type.Methods) - { - AnalyzeMethod(method); - } - } - } - } - - private MethodDef _curCallingMethod; - private IList _curInstructions; - private int _curInstIndex; - - private void AnalyzeMethod(MethodDef method) - { - if (!method.HasBody) - { - return; - } - _curCallingMethod = method; - _curInstructions = method.Body.Instructions; - _curInstIndex = 0; - for (int n = _curInstructions.Count; _curInstIndex < n; _curInstIndex++) - { - var inst = _curInstructions[_curInstIndex]; - switch (inst.OpCode.Code) - { - case Code.Call: - { - AnalyzeCall(inst.Operand as IMethod); - break; - } - case Code.Callvirt: - { - ITypeDefOrRef constrainedType = null; - if (_curInstIndex > 0) - { - var prevInst = _curInstructions[_curInstIndex - 1]; - if (prevInst.OpCode.Code == Code.Constrained) - { - constrainedType = prevInst.Operand as ITypeDefOrRef; - } - } - AnalyzeCallvir(inst.Operand as IMethod, constrainedType); - break; - } - } - } - } - - private ITypeDefOrRef FindLatestTypeOf(int backwardFindInstructionCount) - { - // find sequence ldtoken ; - for (int i = 2; i <= backwardFindInstructionCount; i++) - { - int index = _curInstIndex - i; - if (index < 0) - { - return null; - } - Instruction inst1 = _curInstructions[index]; - Instruction inst2 = _curInstructions[index + 1]; - if (inst1.OpCode.Code == Code.Ldtoken && inst2.OpCode.Code == Code.Call) - { - if (!(inst1.Operand is ITypeDefOrRef typeDefOrRef)) - { - continue; - } - IMethod method = inst2.Operand as IMethod; - if (method.Name == "GetTypeFromHandle" && method.DeclaringType.FullName == "System.Type") - { - // Ldtoken ; Call System.Type.GetTypeFromHandle(System.RuntimeTypeHandle handle) - return typeDefOrRef; - } - } - } - return null; - } - - private void AnalyzeCall(IMethod calledMethod) - { - TypeDef callType = calledMethod.DeclaringType.ResolveTypeDef(); - if (callType == null) - { - return; - } - switch (callType.FullName) - { - case "System.Enum": - { - AnalyzeEnum(calledMethod, callType); - break; - } - case "System.Type": - { - AnalyzeGetType(calledMethod, callType); - break; - } - case "System.Reflection.Assembly": - { - if (calledMethod.Name == "GetType") - { - AnalyzeGetType(calledMethod, callType); - } - break; - } - } - } - - - private bool IsAnyEnumItemRenamed(TypeDef typeDef) - { - return _assembliesToObfuscate.Contains(typeDef.Module) && typeDef.Fields.Any(f => _renamePolicy.NeedRename(f)); - } - - private void AnalyzeCallvir(IMethod calledMethod, ITypeDefOrRef constrainedType) - { - TypeDef callType = calledMethod.DeclaringType.ResolveTypeDef(); - if (callType == null) - { - return; - } - string calledMethodName = calledMethod.Name; - switch (callType.FullName) - { - case "System.Object": - { - if (calledMethodName == "ToString") - { - if (constrainedType != null) - { - TypeDef enumTypeDef = constrainedType.ResolveTypeDef(); - if (enumTypeDef != null && enumTypeDef.IsEnum && IsAnyEnumItemRenamed(enumTypeDef)) - { - Debug.LogError($"[ReflectionCompatibilityDetector] Reflection compatibility issue in {_curCallingMethod}: {enumTypeDef.FullName}.ToString() the enum members are renamed."); - } - } - } - break; - } - case "System.Type": - { - AnalyzeGetType(calledMethod, callType); - break; - } - } - } - - private TypeSig GetMethodGenericParameter(IMethod method) - { - if (method is MethodSpec ms) - { - return ms.GenericInstMethodSig.GenericArguments.FirstOrDefault(); - } - else - { - return null; - } - } - - private void AnalyzeEnum(IMethod method, TypeDef typeDef) - { - const int extraSearchInstructionCount = 3; - TypeSig parseTypeSig = GetMethodGenericParameter(method); - TypeDef parseType = parseTypeSig?.ToTypeDefOrRef().ResolveTypeDef(); - switch (method.Name) - { - case "Parse": - { - if (parseTypeSig != null) - { - // Enum.Parse(string name) or Enum.Parse(string name, bool caseInsensitive) - if (parseType != null) - { - if (IsAnyEnumItemRenamed(parseType)) - { - Debug.LogError($"[ReflectionCompatibilityDetector] Reflection compatibility issue in {_curCallingMethod}: Enum.Parse field of T:{parseType.FullName} is renamed."); - } - } - else - { - Debug.LogWarning($"[ReflectionCompatibilityDetector] Reflection compatibility issue in {_curCallingMethod}: Enum.Parse field of T should not be renamed."); - } - } - else - { - // Enum.Parse(Type type, string name) or Enum.Parse(Type type, string name, bool ignoreCase) - TypeDef enumType = FindLatestTypeOf(method.GetParamCount() + extraSearchInstructionCount)?.ResolveTypeDef(); - if (enumType != null && enumType.IsEnum && IsAnyEnumItemRenamed(enumType)) - { - Debug.LogError($"[ReflectionCompatibilityDetector] Reflection compatibility issue in {_curCallingMethod}: Enum.Parse field of argument type:{enumType.FullName} is renamed."); - } - else - { - Debug.LogWarning($"[ReflectionCompatibilityDetector] Reflection compatibility issue in {_curCallingMethod}: Enum.Parse field of argument `type` should not be renamed."); - } - } - break; - } - case "TryParse": - { - if (parseTypeSig != null) - { - // Enum.TryParse(string name, out T result) or Enum.TryParse(string name, bool ignoreCase, out T result) - if (parseType != null) - { - if (IsAnyEnumItemRenamed(parseType)) - { - Debug.LogError($"[ReflectionCompatibilityDetector] Reflection compatibility issue in {_curCallingMethod}: Enum.TryParse field of T:{parseType.FullName} is renamed."); - } - } - else - { - Debug.LogWarning($"[ReflectionCompatibilityDetector] Reflection compatibility issue in {_curCallingMethod}: Enum.TryParse field of T should not be renamed."); - } - } - else - { - throw new Exception("impossible"); - } - break; - } - case "GetName": - { - // Enum.GetName(Type type, object value) - TypeDef enumType = FindLatestTypeOf(method.GetParamCount() + extraSearchInstructionCount)?.ResolveTypeDef(); - if (enumType != null && enumType.IsEnum && IsAnyEnumItemRenamed(enumType)) - { - Debug.LogError($"[ReflectionCompatibilityDetector] Reflection compatibility issue in {_curCallingMethod}: Enum.GetName field of type:{enumType.FullName} is renamed."); - } - else - { - Debug.LogWarning($"[ReflectionCompatibilityDetector] Reflection compatibility issue in {_curCallingMethod}: Enum.GetName field of argument `type` should not be renamed."); - } - break; - } - case "GetNames": - { - // Enum.GetNames(Type type) - TypeDef enumType = FindLatestTypeOf(method.GetParamCount() + extraSearchInstructionCount)?.ResolveTypeDef(); - if (enumType != null && enumType.IsEnum && IsAnyEnumItemRenamed(enumType)) - { - Debug.LogError($"[ReflectionCompatibilityDetector] Reflection compatibility issue in {_curCallingMethod}: Enum.GetNames field of type:{enumType.FullName} is renamed."); - } - else - { - Debug.LogWarning($"[ReflectionCompatibilityDetector] Reflection compatibility issue in {_curCallingMethod}: Enum.GetNames field of argument `type` should not be renamed."); - } - break; - } - } - } - - private void AnalyzeGetType(IMethod method, TypeDef declaringType) - { - switch (method.Name) - { - case "GetType": - { - Debug.LogWarning($"[ReflectionCompatibilityDetector] Reflection compatibility issue in {_curCallingMethod}: Type.GetType argument `typeName` should not be renamed."); - break; - } - case "GetField": - case "GetFields": - case "GetMethod": - case "GetMethods": - case "GetProperty": - case "GetProperties": - case "GetEvent": - case "GetEvents": - case "GetMembers": - { - Debug.LogWarning($"[ReflectionCompatibilityDetector] Reflection compatibility issue in {_curCallingMethod}: called method:{method} the members of type should not be renamed."); - break; - } - } - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/ReflectionCompatibilityDetector.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/ReflectionCompatibilityDetector.cs.meta deleted file mode 100644 index f5212e11..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/ReflectionCompatibilityDetector.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: b98c97a4d1db5d945bce0fdd2bd09202 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/RenameRecordMap.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/RenameRecordMap.cs deleted file mode 100644 index 65486951..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/RenameRecordMap.cs +++ /dev/null @@ -1,742 +0,0 @@ -using dnlib.DotNet; -using Obfuz.Utils; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Xml; -using UnityEngine; -using UnityEngine.Assertions; - -namespace Obfuz.ObfusPasses.SymbolObfus -{ - - public class RenameRecordMap - { - private enum RenameStatus - { - NotRenamed, - Renamed, - } - - private class RenameRecord - { - public RenameStatus status; - public string signature; - public string oldName; - public string newName; - public string oldStackTraceSignature; // only for MethodDef - public object renameMappingData; - } - - private class RenameMappingField - { - public RenameStatus status; - public string signature; - public string newName; - } - - private class RenameMappingMethod - { - public RenameStatus status; - public string signature; - public string newName; - public string oldStackTraceSignature; - public string newStackTraceSignature; - } - - private class RenameMappingMethodParam - { - public RenameStatus status; - public int index; - public string newName; - } - - private class RenameMappingProperty - { - public RenameStatus status; - public string signature; - public string newName; - } - - private class RenameMappingEvent - { - public RenameStatus status; - public string signature; - public string newName; - } - - private class RenameMappingType - { - public RenameStatus status; - public string oldFullName; - public string newFullName; - - public Dictionary fields = new Dictionary(); - public Dictionary methods = new Dictionary(); - public Dictionary properties = new Dictionary(); - public Dictionary events = new Dictionary(); - } - - private class RenameMappingAssembly - { - public string assName; - - public Dictionary types = new Dictionary(); - } - - private readonly string _mappingFile; - private readonly bool _debug; - private readonly bool _keepUnknownSymbolInSymbolMappingFile; - private readonly Dictionary _assemblies = new Dictionary(); - - - private readonly Dictionary _modRenames = new Dictionary(); - private readonly Dictionary _typeRenames = new Dictionary(); - private readonly Dictionary _methodRenames = new Dictionary(); - private readonly Dictionary _fieldRenames = new Dictionary(); - private readonly Dictionary _propertyRenames = new Dictionary(); - private readonly Dictionary _eventRenames = new Dictionary(); - private readonly Dictionary _virtualMethodGroups = new Dictionary(); - - - public RenameRecordMap(string mappingFile, bool debug, bool keepUnknownSymbolInSymbolMappingFile) - { - _mappingFile = mappingFile; - _debug = debug; - _keepUnknownSymbolInSymbolMappingFile = keepUnknownSymbolInSymbolMappingFile; - } - - public void Init(List assemblies, INameMaker nameMaker) - { - LoadXmlMappingFile(_mappingFile); - foreach (ModuleDef mod in assemblies) - { - string name = mod.Assembly.Name; - - RenameMappingAssembly rma = _assemblies.GetValueOrDefault(name); - - _modRenames.Add(mod, new RenameRecord - { - status = RenameStatus.NotRenamed, - signature = name, - oldName = name, - newName = null, - renameMappingData = rma, - }); - - foreach (TypeDef type in mod.GetTypes()) - { - nameMaker.AddPreservedName(type, name); - nameMaker.AddPreservedNamespace(type, type.Namespace); - string fullTypeName = type.FullName; - RenameMappingType rmt = rma?.types.GetValueOrDefault(fullTypeName); - if (rmt != null && rmt.status == RenameStatus.Renamed) - { - var (newNamespace, newName) = MetaUtil.SplitNamespaceAndName(rmt.newFullName); - nameMaker.AddPreservedNamespace(type, newNamespace); - nameMaker.AddPreservedName(type, newName); - } - - _typeRenames.Add(type, new RenameRecord - { - status = RenameStatus.NotRenamed, - signature = fullTypeName, - oldName = fullTypeName, - newName = null, - renameMappingData = rmt, - }); - foreach (MethodDef method in type.Methods) - { - nameMaker.AddPreservedName(method, method.Name); - string methodSig = TypeSigUtil.ComputeMethodDefSignature(method); - - RenameMappingMethod rmm = rmt?.methods.GetValueOrDefault(methodSig); - if (rmm != null && rmm.status == RenameStatus.Renamed) - { - nameMaker.AddPreservedName(method, rmm.newName); - } - _methodRenames.Add(method, new RenameRecord - { - status = RenameStatus.NotRenamed, - signature = methodSig, - oldName = method.Name, - newName = null, - renameMappingData = rmm, - oldStackTraceSignature = MetaUtil.CreateMethodDefIl2CppStackTraceSignature(method), - }); - } - foreach (FieldDef field in type.Fields) - { - nameMaker.AddPreservedName(field, field.Name); - string fieldSig = TypeSigUtil.ComputeFieldDefSignature(field); - RenameMappingField rmf = rmt?.fields.GetValueOrDefault(fieldSig); - if (rmf != null && rmf.status == RenameStatus.Renamed) - { - nameMaker.AddPreservedName(field, rmf.newName); - } - _fieldRenames.Add(field, new RenameRecord - { - status = RenameStatus.NotRenamed, - signature = fieldSig, - oldName = field.Name, - newName = null, - renameMappingData = rmf, - }); - } - foreach (PropertyDef property in type.Properties) - { - nameMaker.AddPreservedName(property, property.Name); - string propertySig = TypeSigUtil.ComputePropertyDefSignature(property); - RenameMappingProperty rmp = rmt?.properties.GetValueOrDefault(propertySig); - if (rmp != null && rmp.status == RenameStatus.Renamed) - { - nameMaker.AddPreservedName(property, rmp.newName); - } - _propertyRenames.Add(property, new RenameRecord - { - status = RenameStatus.NotRenamed, - signature = propertySig, - oldName = property.Name, - newName = null, - renameMappingData = rmp, - }); - } - foreach (EventDef eventDef in type.Events) - { - nameMaker.AddPreservedName(eventDef, eventDef.Name); - string eventSig = TypeSigUtil.ComputeEventDefSignature(eventDef); - RenameMappingEvent rme = rmt?.events.GetValueOrDefault(eventSig); - if (rme != null && rme.status == RenameStatus.Renamed) - { - nameMaker.AddPreservedName(eventDef, rme.newName); - } - _eventRenames.Add(eventDef, new RenameRecord - { - status = RenameStatus.NotRenamed, - signature = eventSig, - oldName = eventDef.Name, - newName = null, - renameMappingData = rme, - }); - } - } - } - } - - private void LoadXmlMappingFile(string mappingFile) - { - if (string.IsNullOrEmpty(mappingFile) || !File.Exists(mappingFile)) - { - return; - } - if (_debug) - { - Debug.Log($"skip loading debug mapping file: {Path.GetFullPath(mappingFile)}"); - return; - } - var doc = new XmlDocument(); - doc.Load(mappingFile); - var root = doc.DocumentElement; - foreach (XmlNode node in root.ChildNodes) - { - if (!(node is XmlElement element)) - { - continue; - } - LoadAssemblyMapping(element); - } - } - - private void LoadAssemblyMapping(XmlElement ele) - { - if (ele.Name != "assembly") - { - throw new System.Exception($"Invalid node name: {ele.Name}. Expected 'assembly'."); - } - - var assemblyName = ele.Attributes["name"].Value; - var rma = new RenameMappingAssembly - { - assName = assemblyName, - }; - foreach (XmlNode node in ele.ChildNodes) - { - if (!(node is XmlElement element)) - { - continue; - } - if (element.Name != "type") - { - throw new System.Exception($"Invalid node name: {element.Name}. Expected 'type'."); - } - LoadTypeMapping(element, rma); - } - _assemblies.Add(assemblyName, rma); - } - - private void LoadTypeMapping(XmlElement ele, RenameMappingAssembly ass) - { - var typeName = ele.Attributes["fullName"].Value; - var newTypeName = ele.Attributes["newFullName"].Value; - var rmt = new RenameMappingType - { - oldFullName = typeName, - newFullName = newTypeName, - status = (RenameStatus)System.Enum.Parse(typeof(RenameStatus), ele.Attributes["status"].Value), - }; - foreach (XmlNode node in ele.ChildNodes) - { - if (!(node is XmlElement c)) - { - continue; - } - switch (node.Name) - { - case "field": LoadFieldMapping(c, rmt); break; - case "event": LoadEventMapping(c, rmt); break; - case "property": LoadPropertyMapping(c, rmt); break; - case "method": LoadMethodMapping(c, rmt); break; - default: throw new System.Exception($"Invalid node name:{node.Name}"); - } - } - ass.types.Add(typeName, rmt); - } - - private void LoadMethodMapping(XmlElement ele, RenameMappingType type) - { - string signature = ele.Attributes["signature"].Value; - string newName = ele.Attributes["newName"].Value; - string oldStackTraceSignature = ele.Attributes["oldStackTraceSignature"].Value; - string newStackTraceSignature = ele.Attributes["newStackTraceSignature"].Value; - var rmm = new RenameMappingMethod - { - signature = signature, - newName = newName, - status = RenameStatus.Renamed, - oldStackTraceSignature = oldStackTraceSignature, - newStackTraceSignature = newStackTraceSignature, - }; - type.methods.Add(signature, rmm); - } - - private void LoadFieldMapping(XmlElement ele, RenameMappingType type) - { - string signature = ele.Attributes["signature"].Value; - string newName = ele.Attributes["newName"].Value; - var rmf = new RenameMappingField - { - signature = signature, - newName = newName, - status = RenameStatus.Renamed, - }; - type.fields.Add(signature, rmf); - } - - private void LoadPropertyMapping(XmlElement ele, RenameMappingType type) - { - string signature = ele.Attributes["signature"].Value; - string newName = ele.Attributes["newName"].Value; - var rmp = new RenameMappingProperty - { - signature = signature, - newName = newName, - status = RenameStatus.Renamed, - }; - type.properties.Add(signature, rmp); - } - - private void LoadEventMapping(XmlElement ele, RenameMappingType type) - { - string signature = ele.Attributes["signature"].Value; - string newName = ele.Attributes["newName"].Value; - var rme = new RenameMappingEvent - { - signature = signature, - newName = newName, - status = RenameStatus.Renamed, - }; - type.events.Add(signature, rme); - } - - private List GetSortedValueList(Dictionary dic, Comparison comparer) - { - var list = dic.Values.ToList(); - list.Sort(comparer); - return list; - } - - public void WriteXmlMappingFile() - { - if (string.IsNullOrEmpty(_mappingFile)) - { - return; - } - var doc = new XmlDocument(); - var root = doc.CreateElement("mapping"); - doc.AppendChild(root); - - var totalAssNames = new HashSet(_modRenames.Keys.Select(m => m.Assembly.Name.ToString()).Concat(_assemblies.Keys)).ToList(); - totalAssNames.Sort((a, b) => a.CompareTo(b)); - foreach (string assName in totalAssNames) - { - ModuleDef mod = _modRenames.Keys.FirstOrDefault(m => m.Assembly.Name == assName); - var assemblyNode = doc.CreateElement("assembly"); - assemblyNode.SetAttribute("name", assName); - root.AppendChild(assemblyNode); - if (mod != null) - { - var types = mod.GetTypes().ToDictionary(t => _typeRenames.TryGetValue(t, out var rec) ? rec.oldName : t.FullName, t => t); - if (_assemblies.TryGetValue(assName, out var ass)) - { - var totalTypeNames = new HashSet(types.Keys.Concat(ass.types.Keys)).ToList(); - totalTypeNames.Sort((a, b) => a.CompareTo((b))); - foreach (string typeName in totalTypeNames) - { - if (types.TryGetValue(typeName, out TypeDef typeDef)) - { - WriteTypeMapping(assemblyNode, typeDef); - } - else if (_keepUnknownSymbolInSymbolMappingFile) - { - WriteTypeMapping(assemblyNode, typeName, ass.types[typeName]); - } - } - } - else - { - var sortedTypes = new SortedDictionary(types); - foreach (TypeDef type in sortedTypes.Values) - { - WriteTypeMapping(assemblyNode, type); - } - } - } - else - { - RenameMappingAssembly ass = _assemblies[assName]; - - var sortedTypes = GetSortedValueList(ass.types, (a, b) => a.oldFullName.CompareTo(b.oldFullName)); - foreach (var type in sortedTypes) - { - WriteTypeMapping(assemblyNode, type.oldFullName, type); - } - } - } - Directory.CreateDirectory(Path.GetDirectoryName(_mappingFile)); - doc.Save(_mappingFile); - Debug.Log($"Mapping file saved to {Path.GetFullPath(_mappingFile)}"); - } - - private void WriteTypeMapping(XmlElement assNode, TypeDef type) - { - _typeRenames.TryGetValue(type, out var record); - var typeNode = assNode.OwnerDocument.CreateElement("type"); - typeNode.SetAttribute("fullName", record?.signature ?? type.FullName); - typeNode.SetAttribute("newFullName", record != null && record.status == RenameStatus.Renamed ? record.newName : ""); - typeNode.SetAttribute("status", record != null ? record.status.ToString() : RenameStatus.NotRenamed.ToString()); - if (record != null && record.status == RenameStatus.Renamed) - { - Assert.IsFalse(string.IsNullOrWhiteSpace(record.newName), "New name for type cannot be null or empty when status is Renamed."); - } - - foreach (FieldDef field in type.Fields) - { - WriteFieldMapping(typeNode, field); - } - foreach (PropertyDef property in type.Properties) - { - WritePropertyMapping(typeNode, property); - } - foreach (EventDef eventDef in type.Events) - { - WriteEventMapping(typeNode, eventDef); - } - foreach (MethodDef method in type.Methods) - { - WriteMethodMapping(typeNode, method); - } - if ((record != null && record.status == RenameStatus.Renamed) || typeNode.ChildNodes.Count > 0) - { - assNode.AppendChild(typeNode); - } - } - - private void WriteTypeMapping(XmlElement assNode, string fullName, RenameMappingType type) - { - var typeNode = assNode.OwnerDocument.CreateElement("type"); - typeNode.SetAttribute("fullName", fullName); - typeNode.SetAttribute("newFullName", type.status == RenameStatus.Renamed ? type.newFullName : ""); - typeNode.SetAttribute("status", type.status.ToString()); - - foreach (var e in type.fields) - { - string signature = e.Key; - RenameMappingField field = e.Value; - WriteFieldMapping(typeNode, e.Key, e.Value); - } - foreach (var e in type.properties) - { - WritePropertyMapping(typeNode, e.Key, e.Value); - } - foreach (var e in type.events) - { - WriteEventMapping(typeNode, e.Key, e.Value); - } - foreach (var e in type.methods) - { - WriteMethodMapping(typeNode, e.Key, e.Value); - } - - assNode.AppendChild(typeNode); - } - - private void WriteFieldMapping(XmlElement typeEle, FieldDef field) - { - if (!_fieldRenames.TryGetValue(field, out var record) || record.status == RenameStatus.NotRenamed) - { - return; - } - var fieldNode = typeEle.OwnerDocument.CreateElement("field"); - fieldNode.SetAttribute("signature", record?.signature); - fieldNode.SetAttribute("newName", record.newName); - //fieldNode.SetAttribute("status", record.status.ToString()); - typeEle.AppendChild(fieldNode); - } - - private void WriteFieldMapping(XmlElement typeEle, string signature, RenameMappingField field) - { - var fieldNode = typeEle.OwnerDocument.CreateElement("field"); - fieldNode.SetAttribute("signature", signature); - fieldNode.SetAttribute("newName", field.newName); - //fieldNode.SetAttribute("status", record.status.ToString()); - typeEle.AppendChild(fieldNode); - } - - private void WritePropertyMapping(XmlElement typeEle, PropertyDef property) - { - if (!_propertyRenames.TryGetValue(property, out var record) || record.status == RenameStatus.NotRenamed) - { - return; - } - var propertyNode = typeEle.OwnerDocument.CreateElement("property"); - propertyNode.SetAttribute("signature", record.signature); - propertyNode.SetAttribute("newName", record.newName); - //propertyNode.SetAttribute("status", record.status.ToString()); - typeEle.AppendChild(propertyNode); - } - - private void WritePropertyMapping(XmlElement typeEle, string signature, RenameMappingProperty property) - { - var propertyNode = typeEle.OwnerDocument.CreateElement("property"); - propertyNode.SetAttribute("signature", signature); - propertyNode.SetAttribute("newName", property.newName); - //propertyNode.SetAttribute("status", record.status.ToString()); - typeEle.AppendChild(propertyNode); - } - - private void WriteEventMapping(XmlElement typeEle, EventDef eventDef) - { - if (!_eventRenames.TryGetValue(eventDef, out var record) || record.status == RenameStatus.NotRenamed) - { - return; - } - var eventNode = typeEle.OwnerDocument.CreateElement("event"); - eventNode.SetAttribute("signature", record.signature); - eventNode.SetAttribute("newName", record.newName); - typeEle.AppendChild(eventNode); - } - - private void WriteEventMapping(XmlElement typeEle, string signature, RenameMappingEvent eventDef) - { - var eventNode = typeEle.OwnerDocument.CreateElement("event"); - eventNode.SetAttribute("signature", signature); - eventNode.SetAttribute("newName", eventDef.newName); - typeEle.AppendChild(eventNode); - } - - private void WriteMethodMapping(XmlElement typeEle, MethodDef method) - { - if (!_methodRenames.TryGetValue(method, out var record) || record.status == RenameStatus.NotRenamed) - { - return; - } - var methodNode = typeEle.OwnerDocument.CreateElement("method"); - methodNode.SetAttribute("signature", record.signature); - methodNode.SetAttribute("newName", record.newName); - methodNode.SetAttribute("oldStackTraceSignature", record.oldStackTraceSignature); - methodNode.SetAttribute("newStackTraceSignature", MetaUtil.CreateMethodDefIl2CppStackTraceSignature(method)); - //methodNode.SetAttribute("status", record != null ? record.status.ToString() : RenameStatus.NotRenamed.ToString()); - typeEle.AppendChild(methodNode); - } - - private void WriteMethodMapping(XmlElement typeEle, string signature, RenameMappingMethod method) - { - var methodNode = typeEle.OwnerDocument.CreateElement("method"); - methodNode.SetAttribute("signature", signature); - methodNode.SetAttribute("newName", method.newName); - methodNode.SetAttribute("oldStackTraceSignature", method.oldStackTraceSignature); - methodNode.SetAttribute("newStackTraceSignature", method.newStackTraceSignature); - typeEle.AppendChild(methodNode); - } - - public void AddRename(ModuleDef mod, string newName) - { - RenameRecord record = _modRenames[mod]; - record.status = RenameStatus.Renamed; - record.newName = newName; - } - - public void AddRename(TypeDef type, string newName) - { - RenameRecord record = _typeRenames[type]; - record.status = RenameStatus.Renamed; - record.newName = newName; - } - - public void AddRename(MethodDef method, string newName) - { - if (_methodRenames.TryGetValue(method, out RenameRecord record)) - { - record.status = RenameStatus.Renamed; - record.newName = newName; - return; - } - else - { - string methodSig = TypeSigUtil.ComputeMethodDefSignature(method); - _methodRenames.Add(method, new RenameRecord - { - status = RenameStatus.Renamed, - signature = methodSig, - oldName = method.Name, - newName = newName, - renameMappingData = null, - oldStackTraceSignature = MetaUtil.CreateMethodDefIl2CppStackTraceSignature(method), - }); - } - } - - public void InitAndAddRename(VirtualMethodGroup methodGroup, string newName) - { - RenameRecord methodRecord = methodGroup.methods.Where(m => _methodRenames.ContainsKey(m)).Select(m => _methodRenames[m]).FirstOrDefault(); - MethodDef firstMethod = methodGroup.methods[0]; - _virtualMethodGroups.Add(methodGroup, new RenameRecord - { - status = RenameStatus.Renamed, - signature = methodRecord != null ? methodRecord.signature : TypeSigUtil.ComputeMethodDefSignature(firstMethod), - oldName = methodRecord != null ? methodRecord.oldName : (string)firstMethod.Name, - newName = newName, - }); - } - - public void AddRename(FieldDef field, string newName) - { - RenameRecord record = _fieldRenames[field]; - record.status = RenameStatus.Renamed; - record.newName = newName; - } - - public void AddRename(PropertyDef property, string newName) - { - RenameRecord record = _propertyRenames[property]; - record.status = RenameStatus.Renamed; - record.newName = newName; - } - - public void AddRename(EventDef eventDef, string newName) - { - RenameRecord record = _eventRenames[eventDef]; - record.status = RenameStatus.Renamed; - record.newName = newName; - } - - public bool TryGetExistRenameMapping(TypeDef type, out string newNamespace, out string newName) - { - if (_typeRenames.TryGetValue(type, out var record) && record.renameMappingData != null) - { - var rmt = (RenameMappingType)record.renameMappingData; - if (rmt.status == RenameStatus.Renamed) - { - Assert.IsFalse(string.IsNullOrWhiteSpace(rmt.newFullName)); - (newNamespace, newName) = MetaUtil.SplitNamespaceAndName(rmt.newFullName); - return true; - } - } - newNamespace = null; - newName = null; - return false; - } - - public bool TryGetExistRenameMapping(MethodDef method, out string newName) - { - if (_methodRenames.TryGetValue(method, out var record) && record.renameMappingData != null) - { - RenameMappingMethod rmm = (RenameMappingMethod)record.renameMappingData; - if (rmm.status == RenameStatus.Renamed) - { - newName = ((RenameMappingMethod)record.renameMappingData).newName; - return true; - } - } - newName = null; - return false; - } - - public bool TryGetExistRenameMapping(FieldDef field, out string newName) - { - if (_fieldRenames.TryGetValue(field, out var record) && record.renameMappingData != null) - { - RenameMappingField rmm = (RenameMappingField)record.renameMappingData; - if (rmm.status == RenameStatus.Renamed) - { - newName = ((RenameMappingField)record.renameMappingData).newName; - return true; - } - } - newName = null; - return false; - } - - public bool TryGetExistRenameMapping(PropertyDef property, out string newName) - { - if (_propertyRenames.TryGetValue(property, out var record) && record.renameMappingData != null) - { - RenameMappingProperty rmm = (RenameMappingProperty)record.renameMappingData; - if (rmm.status == RenameStatus.Renamed) - { - newName = ((RenameMappingProperty)record.renameMappingData).newName; - return true; - } - } - newName = null; - return false; - } - - public bool TryGetExistRenameMapping(EventDef eventDef, out string newName) - { - if (_eventRenames.TryGetValue(eventDef, out var record) && record.renameMappingData != null) - { - RenameMappingEvent rmm = (RenameMappingEvent)record.renameMappingData; - if (rmm.status == RenameStatus.Renamed) - { - newName = ((RenameMappingEvent)record.renameMappingData).newName; - return true; - } - } - newName = null; - return false; - } - - public bool TryGetRename(VirtualMethodGroup group, out string newName) - { - if (_virtualMethodGroups.TryGetValue(group, out var record)) - { - newName = record.newName; - return true; - } - newName = null; - return false; - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/RenameRecordMap.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/RenameRecordMap.cs.meta deleted file mode 100644 index 2a91341f..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/RenameRecordMap.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: a3ffbd28624d87c4382f62eb4fc19c70 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/SymbolObfusPass.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/SymbolObfusPass.cs deleted file mode 100644 index eb7970aa..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/SymbolObfusPass.cs +++ /dev/null @@ -1,31 +0,0 @@ -using Obfuz.Settings; - -namespace Obfuz.ObfusPasses.SymbolObfus -{ - public class SymbolObfusPass : ObfuscationPassBase - { - private SymbolRename _symbolRename; - - public override ObfuscationPassType Type => ObfuscationPassType.SymbolObfus; - - public SymbolObfusPass(SymbolObfuscationSettingsFacade settings) - { - _symbolRename = new SymbolRename(settings); - } - - public override void Start() - { - _symbolRename.Init(); - } - - public override void Stop() - { - _symbolRename.Save(); - } - - public override void Process() - { - _symbolRename.Process(); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/SymbolObfusPass.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/SymbolObfusPass.cs.meta deleted file mode 100644 index a86c04b1..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/SymbolObfusPass.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: a4c9a37b51ade6b46a299be7ad2155d6 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/SymbolRename.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/SymbolRename.cs deleted file mode 100644 index 1ceddfa7..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/SymbolRename.cs +++ /dev/null @@ -1,864 +0,0 @@ -using dnlib.DotNet; -using Obfuz.ObfusPasses.SymbolObfus.NameMakers; -using Obfuz.ObfusPasses.SymbolObfus.Policies; -using Obfuz.Settings; -using Obfuz.Utils; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using UnityEngine; -using UnityEngine.Assertions; - -namespace Obfuz.ObfusPasses.SymbolObfus -{ - public class SymbolRename - { - private readonly bool _useConsistentNamespaceObfuscation; - private readonly bool _detectReflectionCompatibility; - private readonly List _obfuscationRuleFiles; - private readonly string _mappingXmlPath; - - private AssemblyCache _assemblyCache; - - private List _toObfuscatedModules; - private List _obfuscatedAndNotObfuscatedModules; - private HashSet _toObfuscatedModuleSet; - private HashSet _nonObfuscatedButReferencingObfuscatedModuleSet; - private IObfuscationPolicy _renamePolicy; - private INameMaker _nameMaker; - private readonly Dictionary> _customAttributeArgumentsWithTypeByMods = new Dictionary>(); - private readonly RenameRecordMap _renameRecordMap; - private readonly VirtualMethodGroupCalculator _virtualMethodGroupCalculator; - private readonly List _customPolicies = new List(); - - class CustomAttributeInfo - { - public CustomAttributeCollection customAttributes; - public int index; - public List arguments; - public List namedArguments; - } - - public SymbolRename(SymbolObfuscationSettingsFacade settings) - { - _useConsistentNamespaceObfuscation = settings.useConsistentNamespaceObfuscation; - _detectReflectionCompatibility = settings.detectReflectionCompatibility; - _mappingXmlPath = settings.symbolMappingFile; - _obfuscationRuleFiles = settings.ruleFiles.ToList(); - _renameRecordMap = new RenameRecordMap(settings.symbolMappingFile, settings.debug, settings.keepUnknownSymbolInSymbolMappingFile); - _virtualMethodGroupCalculator = new VirtualMethodGroupCalculator(); - _nameMaker = settings.debug ? NameMakerFactory.CreateDebugNameMaker() : NameMakerFactory.CreateNameMakerBaseASCIICharSet(settings.obfuscatedNamePrefix); - - foreach (var customPolicyType in settings.customRenamePolicyTypes) - { - if (Activator.CreateInstance(customPolicyType, new object[] { this }) is IObfuscationPolicy customPolicy) - { - _customPolicies.Add(customPolicy); - } - else - { - Debug.LogWarning($"Custom rename policy type {customPolicyType} is not a valid IObfuscationPolicy"); - } - } - } - - public void Init() - { - var ctx = ObfuscationPassContext.Current; - _assemblyCache = ctx.assemblyCache; - _toObfuscatedModules = ctx.modulesToObfuscate; - _obfuscatedAndNotObfuscatedModules = ctx.allObfuscationRelativeModules; - _toObfuscatedModuleSet = new HashSet(ctx.modulesToObfuscate); - _nonObfuscatedButReferencingObfuscatedModuleSet = new HashSet(ctx.allObfuscationRelativeModules.Where(m => !_toObfuscatedModuleSet.Contains(m))); - - var obfuscateRuleConfig = new ConfigurableRenamePolicy(ctx.coreSettings.assembliesToObfuscate, ctx.modulesToObfuscate, _obfuscationRuleFiles); - var totalRenamePolicies = new List - { - new SupportPassPolicy(ctx.passPolicy), - new SystemRenamePolicy(ctx.obfuzIgnoreScopeComputeCache), - new UnityRenamePolicy(), - obfuscateRuleConfig, - }; - totalRenamePolicies.AddRange(_customPolicies); - - _renamePolicy = new CacheRenamePolicy(new CombineRenamePolicy(totalRenamePolicies.ToArray())); - BuildCustomAttributeArguments(); - } - - private void CollectCArgumentWithTypeOf(IHasCustomAttribute meta, List customAttributes) - { - int index = 0; - foreach (CustomAttribute ca in meta.CustomAttributes) - { - List arguments = null; - if (ca.ConstructorArguments.Any(a => MetaUtil.MayRenameCustomDataType(a.Type.ElementType))) - { - arguments = ca.ConstructorArguments.ToList(); - } - List namedArguments = ca.NamedArguments.Count > 0 ? ca.NamedArguments.ToList() : null; - if (arguments != null || namedArguments != null) - { - customAttributes.Add(new CustomAttributeInfo - { - customAttributes = meta.CustomAttributes, - index = index, - arguments = arguments, - namedArguments = namedArguments - }); - } - ++index; - } - } - - private void BuildCustomAttributeArguments() - { - foreach (ModuleDef mod in _obfuscatedAndNotObfuscatedModules) - { - var customAttributes = new List(); - CollectCArgumentWithTypeOf(mod, customAttributes); - foreach (TypeDef type in mod.GetTypes()) - { - CollectCArgumentWithTypeOf(type, customAttributes); - foreach (FieldDef field in type.Fields) - { - CollectCArgumentWithTypeOf(field, customAttributes); - } - foreach (MethodDef method in type.Methods) - { - CollectCArgumentWithTypeOf(method, customAttributes); - foreach (Parameter param in method.Parameters) - { - if (param.ParamDef != null) - { - CollectCArgumentWithTypeOf(param.ParamDef, customAttributes); - } - } - } - foreach (PropertyDef property in type.Properties) - { - CollectCArgumentWithTypeOf(property, customAttributes); - } - foreach (EventDef eventDef in type.Events) - { - CollectCArgumentWithTypeOf(eventDef, customAttributes); - } - } - - _customAttributeArgumentsWithTypeByMods.Add(mod, customAttributes); - } - } - - private void PrecomputeNeedRename() - { - foreach (ModuleDef mod in _toObfuscatedModules) - { - foreach (TypeDef type in mod.GetTypes()) - { - _renamePolicy.NeedRename(type); - foreach (var field in type.Fields) - { - _renamePolicy.NeedRename(field); - } - foreach (var method in type.Methods) - { - _renamePolicy.NeedRename(method); - } - foreach (var property in type.Properties) - { - _renamePolicy.NeedRename(property); - } - foreach (var eventDef in type.Events) - { - _renamePolicy.NeedRename(eventDef); - } - } - } - } - - public void Process() - { - _renameRecordMap.Init(_toObfuscatedModules, _nameMaker); - PrecomputeNeedRename(); - if (_detectReflectionCompatibility) - { - var reflectionCompatibilityDetector = new ReflectionCompatibilityDetector(_toObfuscatedModules, _obfuscatedAndNotObfuscatedModules, _renamePolicy); - reflectionCompatibilityDetector.Analyze(); - } - RenameTypes(); - RenameFields(); - RenameMethods(); - RenameProperties(); - RenameEvents(); - } - - class RefTypeDefMetas - { - public readonly List typeRefs = new List(); - - public readonly List customAttributes = new List(); - } - - private void BuildRefTypeDefMetasMap(Dictionary refTypeDefMetasMap) - { - foreach (ModuleDef mod in _obfuscatedAndNotObfuscatedModules) - { - foreach (TypeRef typeRef in mod.GetTypeRefs()) - { - if (typeRef.DefinitionAssembly.IsCorLib()) - { - continue; - } - TypeDef typeDef = typeRef.ResolveThrow(); - if (!refTypeDefMetasMap.TryGetValue(typeDef, out var typeDefMetas)) - { - typeDefMetas = new RefTypeDefMetas(); - refTypeDefMetasMap.Add(typeDef, typeDefMetas); - } - typeDefMetas.typeRefs.Add(typeRef); - } - } - - foreach (CustomAttributeInfo cai in _customAttributeArgumentsWithTypeByMods.Values.SelectMany(cas => cas)) - { - CustomAttribute ca = cai.customAttributes[cai.index]; - TypeDef typeDef = MetaUtil.GetTypeDefOrGenericTypeBaseThrowException(ca.Constructor.DeclaringType); - if (!refTypeDefMetasMap.TryGetValue(typeDef, out var typeDefMetas)) - { - typeDefMetas = new RefTypeDefMetas(); - refTypeDefMetasMap.Add(typeDef, typeDefMetas); - } - typeDefMetas.customAttributes.Add(ca); - } - } - - private void RetargetTypeRefInCustomAttributes() - { - foreach (CustomAttributeInfo cai in _customAttributeArgumentsWithTypeByMods.Values.SelectMany(cas => cas)) - { - CustomAttribute ca = cai.customAttributes[cai.index]; - bool anyChange = false; - if (cai.arguments != null) - { - for (int i = 0; i < cai.arguments.Count; i++) - { - CAArgument oldArg = cai.arguments[i]; - if (MetaUtil.TryRetargetTypeRefInArgument(oldArg, out CAArgument newArg)) - { - anyChange = true; - cai.arguments[i] = newArg; - } - } - } - if (cai.namedArguments != null) - { - for (int i = 0; i < cai.namedArguments.Count; i++) - { - if (MetaUtil.TryRetargetTypeRefInNamedArgument(cai.namedArguments[i])) - { - anyChange = true; - } - } - } - if (anyChange) - { - cai.customAttributes[cai.index] = new CustomAttribute(ca.Constructor, - cai.arguments != null ? cai.arguments : ca.ConstructorArguments, - cai.namedArguments != null ? cai.namedArguments : ca.NamedArguments); - } - } - } - - private readonly Dictionary _refTypeRefMetasMap = new Dictionary(); - - private void RenameTypes() - { - //Debug.Log("RenameTypes begin"); - - RetargetTypeRefInCustomAttributes(); - - BuildRefTypeDefMetasMap(_refTypeRefMetasMap); - _assemblyCache.EnableTypeDefCache = false; - - foreach (ModuleDef mod in _toObfuscatedModules) - { - foreach (TypeDef type in mod.GetTypes()) - { - if (_renamePolicy.NeedRename(type)) - { - Rename(type, _refTypeRefMetasMap.GetValueOrDefault(type)); - } - } - } - - // clean cache - _assemblyCache.EnableTypeDefCache = true; - //Debug.Log("Rename Types end"); - } - - - class RefFieldMetas - { - public readonly List fieldRefs = new List(); - public readonly List customAttributes = new List(); - } - - - private void BuildHierarchyFields(TypeDef type, List fields) - { - while (type != null) - { - fields.AddRange(type.Fields); - type = MetaUtil.GetBaseTypeDef(type); - } - } - - private IEnumerable WalkAllMethodInstructionOperand(ModuleDef mod) - { - foreach (TypeDef type in mod.GetTypes()) - { - foreach (MethodDef method in type.Methods) - { - if (!method.HasBody) - { - continue; - } - foreach (var instr in method.Body.Instructions) - { - if (instr.Operand is T memberRef) - { - yield return memberRef; - } - } - } - } - } - - private void BuildRefFieldMetasMap(Dictionary refFieldMetasMap) - { - foreach (ModuleDef mod in _obfuscatedAndNotObfuscatedModules) - { - foreach (MemberRef memberRef in WalkAllMethodInstructionOperand(mod)) - { - IMemberRefParent parent = memberRef.Class; - TypeDef parentTypeDef = MetaUtil.GetMemberRefTypeDefParentOrNull(parent); - if (parentTypeDef == null) - { - continue; - } - foreach (FieldDef field in parentTypeDef.Fields) - { - if (field.Name == memberRef.Name && TypeEqualityComparer.Instance.Equals(field.FieldSig.Type, memberRef.FieldSig.Type)) - { - if (!refFieldMetasMap.TryGetValue(field, out var fieldMetas)) - { - fieldMetas = new RefFieldMetas(); - refFieldMetasMap.Add(field, fieldMetas); - } - fieldMetas.fieldRefs.Add(memberRef); - break; - } - } - } - } - foreach (var e in _refTypeRefMetasMap) - { - TypeDef typeDef = e.Key; - var hierarchyFields = new List(); - BuildHierarchyFields(typeDef, hierarchyFields); - RefTypeDefMetas typeDefMetas = e.Value; - foreach (CustomAttribute ca in typeDefMetas.customAttributes) - { - foreach (var arg in ca.NamedArguments) - { - if (arg.IsProperty) - { - continue; - } - foreach (FieldDef field in hierarchyFields) - { - // FIXME. field of Generic Base Type may not be same - if (field.Name == arg.Name && TypeEqualityComparer.Instance.Equals(field.FieldType, arg.Type)) - { - if (!refFieldMetasMap.TryGetValue(field, out var fieldMetas)) - { - fieldMetas = new RefFieldMetas(); - refFieldMetasMap.Add(field, fieldMetas); - } - fieldMetas.customAttributes.Add(ca); - break; - } - } - } - } - } - } - - private void RenameFields() - { - //Debug.Log("Rename fields begin"); - var refFieldMetasMap = new Dictionary(); - BuildRefFieldMetasMap(refFieldMetasMap); - - foreach (ModuleDef mod in _toObfuscatedModules) - { - foreach (TypeDef type in mod.GetTypes()) - { - foreach (FieldDef field in type.Fields) - { - if (_renamePolicy.NeedRename(field)) - { - Rename(field, refFieldMetasMap.GetValueOrDefault(field)); - } - } - } - } - //Debug.Log("Rename fields end"); - } - - class RefMethodMetas - { - public readonly List memberRefs = new List(); - } - - private void RenameMethodRef(MemberRef memberRef, Dictionary refMethodMetasMap) - { - if (!memberRef.IsMethodRef) - { - return; - } - - IMemberRefParent parent = memberRef.Class; - TypeDef parentTypeDef = MetaUtil.GetMemberRefTypeDefParentOrNull(parent); - if (parentTypeDef == null) - { - return; - } - foreach (MethodDef methodDef in parentTypeDef.Methods) - { - if (methodDef.Name == memberRef.Name && new SigComparer(default).Equals(methodDef.MethodSig, memberRef.MethodSig)) - { - if (!refMethodMetasMap.TryGetValue(methodDef, out var refMethodMetas)) - { - refMethodMetas = new RefMethodMetas(); - refMethodMetasMap.Add(methodDef, refMethodMetas); - } - refMethodMetas.memberRefs.Add(memberRef); - break; - } - } - } - - - private void RenameMethodRefOrMethodSpec(IMethod method, Dictionary refMethodMetasMap) - { - if (method is MemberRef memberRef) - { - RenameMethodRef(memberRef, refMethodMetasMap); - } - else if (method is MethodSpec methodSpec) - { - if (methodSpec.Method is MemberRef memberRef2) - { - RenameMethodRef(memberRef2, refMethodMetasMap); - } - } - } - - private void BuildRefMethodMetasMap(Dictionary refMethodMetasMap) - { - foreach (ModuleDef mod in _obfuscatedAndNotObfuscatedModules) - { - foreach (IMethod method in WalkAllMethodInstructionOperand(mod)) - { - RenameMethodRefOrMethodSpec(method, refMethodMetasMap); - } - - foreach (var type in mod.GetTypes()) - { - foreach (MethodDef method in type.Methods) - { - if (method.HasOverrides) - { - foreach (MethodOverride methodOverride in method.Overrides) - { - RenameMethodRefOrMethodSpec(methodOverride.MethodDeclaration, refMethodMetasMap); - RenameMethodRefOrMethodSpec(methodOverride.MethodBody, refMethodMetasMap); - } - } - } - } - foreach (var e in _refTypeRefMetasMap) - { - TypeDef typeDef = e.Key; - var hierarchyFields = new List(); - BuildHierarchyFields(typeDef, hierarchyFields); - RefTypeDefMetas typeDefMetas = e.Value; - foreach (CustomAttribute ca in typeDefMetas.customAttributes) - { - if (ca.Constructor is IMethod method) - { - RenameMethodRefOrMethodSpec(method, refMethodMetasMap); - } - } - } - } - } - - private void RenameMethods() - { - //Debug.Log("Rename methods begin"); - //Debug.Log("Rename not virtual methods begin"); - var virtualMethods = new List(); - var refMethodMetasMap = new Dictionary(); - BuildRefMethodMetasMap(refMethodMetasMap); - foreach (ModuleDef mod in _toObfuscatedModules) - { - foreach (TypeDef type in mod.GetTypes()) - { - foreach (MethodDef method in type.Methods) - { - if (method.IsVirtual) - { - continue; - } - if (_renamePolicy.NeedRename(method)) - { - Rename(method, refMethodMetasMap.GetValueOrDefault(method)); - } - } - } - } - - foreach (ModuleDef mod in _obfuscatedAndNotObfuscatedModules) - { - foreach (TypeDef type in mod.GetTypes()) - { - _virtualMethodGroupCalculator.CalculateType(type); - foreach (MethodDef method in type.Methods) - { - if (method.IsVirtual) - { - virtualMethods.Add(method); - } - } - } - } - - //Debug.Log("Rename not virtual methods end"); - - - //Debug.Log("Rename virtual methods begin"); - var visitedVirtualMethods = new HashSet(); - var groupNeedRenames = new Dictionary(); - foreach (var method in virtualMethods) - { - if (!visitedVirtualMethods.Add(method)) - { - continue; - } - VirtualMethodGroup group = _virtualMethodGroupCalculator.GetMethodGroup(method); - if (!groupNeedRenames.TryGetValue(group, out var needRename)) - { - var rootBeInheritedTypes = group.GetRootBeInheritedTypes(); - // - if the group contains no obfuscated methods - // - if the group contains method defined in non-obfuscated module but referencing obfuscated module and virtual method in obfuscated type overrides virtual method from non-obfuscated type - if (!group.methods.Any(m => _toObfuscatedModuleSet.Contains(m.DeclaringType.Module)) || group.methods.Any(m => _nonObfuscatedButReferencingObfuscatedModuleSet.Contains(m.Module) && rootBeInheritedTypes.Contains(m.DeclaringType))) - { - needRename = false; - } - else - { - needRename = group.methods.All(m => _obfuscatedAndNotObfuscatedModules.Contains(m.Module) && _renamePolicy.NeedRename(m)); - } - groupNeedRenames.Add(group, needRename); - if (needRename) - { - bool conflict = false; - string newVirtualMethodName = null; - foreach (MethodDef m in group.methods) - { - if (_renameRecordMap.TryGetExistRenameMapping(m, out var existVirtualMethodName)) - { - if (newVirtualMethodName == null) - { - newVirtualMethodName = existVirtualMethodName; - } - else if (newVirtualMethodName != existVirtualMethodName) - { - Debug.LogWarning($"Virtual method rename conflict. {m} => {existVirtualMethodName} != {newVirtualMethodName}"); - conflict = true; - break; - } - } - } - if (newVirtualMethodName == null || conflict /*|| _nameMaker.IsNamePreserved(group, newVirtualMethodName)*/) - { - newVirtualMethodName = _nameMaker.GetNewName(group, method.Name); - } - _renameRecordMap.InitAndAddRename(group, newVirtualMethodName); - } - } - if (!needRename) - { - continue; - } - if (_renameRecordMap.TryGetRename(group, out var newName)) - { - Rename(method, refMethodMetasMap.GetValueOrDefault(method), newName); - } - else - { - throw new Exception($"group:{group} method:{method} not found in rename record map"); - } - } - //Debug.Log("Rename virtual methods end"); - //Debug.Log("Rename methods end"); - } - - class RefPropertyMetas - { - public List customAttributes = new List(); - } - - private void BuildHierarchyProperties(TypeDef type, List properties) - { - while (type != null) - { - properties.AddRange(type.Properties); - type = MetaUtil.GetBaseTypeDef(type); - } - } - - private void BuildRefPropertyMetasMap(Dictionary refPropertyMetasMap) - { - foreach (var e in _refTypeRefMetasMap) - { - TypeDef typeDef = e.Key; - var hierarchyProperties = new List(); - BuildHierarchyProperties(typeDef, hierarchyProperties); - RefTypeDefMetas typeDefMetas = e.Value; - foreach (CustomAttribute ca in typeDefMetas.customAttributes) - { - foreach (var arg in ca.NamedArguments) - { - if (arg.IsField) - { - continue; - } - foreach (PropertyDef field in hierarchyProperties) - { - // FIXME. field of Generic Base Type may not be same - if (field.Name == arg.Name && TypeEqualityComparer.Instance.Equals(arg.Type, field.PropertySig.RetType)) - { - if (!refPropertyMetasMap.TryGetValue(field, out var fieldMetas)) - { - fieldMetas = new RefPropertyMetas(); - refPropertyMetasMap.Add(field, fieldMetas); - } - fieldMetas.customAttributes.Add(ca); - break; - } - } - } - } - } - } - - private void RenameProperties() - { - //Debug.Log("Rename properties begin"); - var refPropertyMetasMap = new Dictionary(); - BuildRefPropertyMetasMap(refPropertyMetasMap); - foreach (ModuleDef mod in _toObfuscatedModules) - { - foreach (TypeDef type in mod.GetTypes()) - { - foreach (PropertyDef property in type.Properties) - { - if (_renamePolicy.NeedRename(property)) - { - Rename(property, refPropertyMetasMap.GetValueOrDefault(property)); - } - } - } - } - //Debug.Log("Rename properties end"); - } - - private void RenameEvents() - { - //Debug.Log("Rename events begin"); - foreach (ModuleDef mod in _toObfuscatedModules) - { - foreach (TypeDef type in mod.GetTypes()) - { - foreach (EventDef eventDef in type.Events) - { - if (_renamePolicy.NeedRename(eventDef)) - { - Rename(eventDef); - } - } - } - } - //Debug.Log("Rename events begin"); - } - - private void Rename(TypeDef type, RefTypeDefMetas refTypeDefMeta) - { - string moduleName = MetaUtil.GetModuleNameWithoutExt(type.Module.Name); - string oldFullName = type.FullName; - string oldNamespace = type.Namespace; - - string oldName = type.Name; - - string newNamespace; - string newName; - if (_renameRecordMap.TryGetExistRenameMapping(type, out var nns, out var nn)) - { - newNamespace = nns; - newName = nn; - } - else - { - newNamespace = _nameMaker.GetNewNamespace(type, oldNamespace, _useConsistentNamespaceObfuscation); - newName = _nameMaker.GetNewName(type, oldName); - } - - if (refTypeDefMeta != null) - { - foreach (TypeRef typeRef in refTypeDefMeta.typeRefs) - { - Assert.AreEqual(typeRef.FullName, oldFullName); - Assert.IsTrue(typeRef.DefinitionAssembly.Name == moduleName); - if (!string.IsNullOrEmpty(oldNamespace)) - { - typeRef.Namespace = newNamespace; - } - typeRef.Name = newName; - //Debug.Log($"rename assembly:{typeRef.Module.Name} reference {oldFullName} => {typeRef.FullName}"); - } - } - type.Name = newName; - type.Namespace = newNamespace; - string newFullName = type.FullName; - _renameRecordMap.AddRename(type, newFullName); - //Debug.Log($"rename typedef. assembly:{type.Module.Name} oldName:{oldFullName} => newName:{newFullName}"); - } - - private void Rename(FieldDef field, RefFieldMetas fieldMetas) - { - string oldName = field.Name; - string newName = _renameRecordMap.TryGetExistRenameMapping(field, out var nn) ? nn : _nameMaker.GetNewName(field, oldName); - if (fieldMetas != null) - { - foreach (var memberRef in fieldMetas.fieldRefs) - { - memberRef.Name = newName; - //Debug.Log($"rename assembly:{memberRef.Module.Name} reference {field.FullName} => {memberRef.FullName}"); - } - foreach (var ca in fieldMetas.customAttributes) - { - foreach (var arg in ca.NamedArguments) - { - if (arg.Name == oldName) - { - arg.Name = newName; - } - } - } - } - //Debug.Log($"rename field. {field} => {newName}"); - _renameRecordMap.AddRename(field, newName); - field.Name = newName; - - } - - private void Rename(MethodDef method, RefMethodMetas refMethodMetas) - { - string oldName = method.Name; - string newName = _renameRecordMap.TryGetExistRenameMapping(method, out var nn) ? nn : _nameMaker.GetNewName(method, oldName); - Rename(method, refMethodMetas, newName); - } - - private void Rename(MethodDef method, RefMethodMetas refMethodMetas, string newName) - { - ModuleDefMD mod = (ModuleDefMD)method.DeclaringType.Module; - RenameMethodParams(method); - RenameMethodBody(method); - if (refMethodMetas != null) - { - foreach (MemberRef memberRef in refMethodMetas.memberRefs) - { - string oldMethodFullName = memberRef.ToString(); - memberRef.Name = newName; - //Debug.Log($"rename assembly:{memberRef.Module.Name} method:{oldMethodFullName} => {memberRef}"); - } - } - _renameRecordMap.AddRename(method, newName); - method.Name = newName; - } - - private void RenameMethodBody(MethodDef method) - { - if (method.Body == null) - { - return; - } - } - - private void RenameMethodParams(MethodDef method) - { - foreach (Parameter param in method.Parameters) - { - if (param.ParamDef != null) - { - Rename(param.ParamDef); - } - } - } - - private void Rename(ParamDef param) - { - string newName = _nameMaker.GetNewName(param, param.Name); - param.Name = newName; - } - - private void Rename(EventDef eventDef) - { - string oldName = eventDef.Name; - string newName = _renameRecordMap.TryGetExistRenameMapping(eventDef, out var nn) ? nn : _nameMaker.GetNewName(eventDef, eventDef.Name); - _renameRecordMap.AddRename(eventDef, newName); - eventDef.Name = newName; - } - - private void Rename(PropertyDef property, RefPropertyMetas refPropertyMetas) - { - string oldName = property.Name; - string newName = _renameRecordMap.TryGetExistRenameMapping(property, out var nn) ? nn : _nameMaker.GetNewName(property, oldName); - - if (refPropertyMetas != null) - { - foreach (var ca in refPropertyMetas.customAttributes) - { - foreach (var arg in ca.NamedArguments) - { - if (arg.Name == oldName) - { - arg.Name = newName; - } - } - } - } - _renameRecordMap.AddRename(property, newName); - property.Name = newName; - } - - public void Save() - { - Directory.CreateDirectory(Path.GetDirectoryName(_mappingXmlPath)); - _renameRecordMap.WriteXmlMappingFile(); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/SymbolRename.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/SymbolRename.cs.meta deleted file mode 100644 index 739a842b..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/SymbolRename.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ec29be12f08e90741a59970f029c2eec -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/VirtualMethodGroupCalculator.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/VirtualMethodGroupCalculator.cs deleted file mode 100644 index ac6b4546..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/VirtualMethodGroupCalculator.cs +++ /dev/null @@ -1,299 +0,0 @@ -using dnlib.DotNet; -using Obfuz.Utils; -using System.Collections.Generic; - -namespace Obfuz.ObfusPasses.SymbolObfus -{ - - public class VirtualMethodGroup - { - public List methods; - - private HashSet _nameScopes; - - private HashSet _rootNameScope; - - public HashSet GetNameConflictTypeScopes() - { - if (_nameScopes != null) - { - return _nameScopes; - } - - _nameScopes = new HashSet(); - foreach (var method in methods) - { - TypeDef cur = method.DeclaringType; - while (cur != null) - { - _nameScopes.Add(cur); - cur = MetaUtil.GetBaseTypeDef(cur); - } - } - return _nameScopes; - } - - public HashSet GetRootBeInheritedTypes() - { - if (_rootNameScope != null) - { - return _rootNameScope; - } - _rootNameScope = new HashSet(); - var nameScopes = GetNameConflictTypeScopes(); - foreach (var type in nameScopes) - { - TypeDef parentType = MetaUtil.GetBaseTypeDef(type); - if (parentType == null || !nameScopes.Contains(parentType)) - { - _rootNameScope.Add(type); - } - } - return _rootNameScope; - } - - public IEnumerable GetNameDeclaringTypeScopes() - { - foreach (var method in methods) - { - yield return method.DeclaringType; - } - } - } - - public class VirtualMethodGroupCalculator - { - - private class TypeFlatMethods - { - public HashSet flatMethods = new HashSet(); - - - private bool IsFinalTypeSig(TypeSig type) - { - switch (type.ElementType) - { - case ElementType.Void: - case ElementType.Boolean: - case ElementType.Char: - case ElementType.I1: - case ElementType.I2: - case ElementType.I4: - case ElementType.I8: - case ElementType.U1: - case ElementType.U2: - case ElementType.U4: - case ElementType.U8: - case ElementType.R4: - case ElementType.R8: - case ElementType.String: - case ElementType.Object: - case ElementType.Class: - case ElementType.ValueType: - return true; - default: return false; - } - } - - private bool IsVarType(TypeSig t) - { - return t.ElementType == ElementType.MVar || t.ElementType == ElementType.Var; - } - - private bool IsClassOrValueType(TypeSig t) - { - return t.ElementType == ElementType.Class || t.ElementType == ElementType.ValueType; - } - - private bool IsLooseTypeSigMatch(TypeSig t1, TypeSig t2) - { - t1 = t1.RemovePinnedAndModifiers(); - t2 = t2.RemovePinnedAndModifiers(); - - if (t1.ElementType != t2.ElementType) - { - return IsVarType(t1) || IsVarType(t2); - } - - switch (t1.ElementType) - { - case ElementType.Void: - case ElementType.Boolean: - case ElementType.Char: - case ElementType.I1: - case ElementType.I2: - case ElementType.I4: - case ElementType.I8: - case ElementType.U1: - case ElementType.U2: - case ElementType.U4: - case ElementType.U8: - case ElementType.R4: - case ElementType.R8: - case ElementType.I: - case ElementType.U: - case ElementType.R: - case ElementType.String: - case ElementType.Object: - case ElementType.TypedByRef: - return true; - case ElementType.Class: - case ElementType.ValueType: - { - return t1.AssemblyQualifiedName == t2.AssemblyQualifiedName; - } - case ElementType.Ptr: - case ElementType.ByRef: - case ElementType.SZArray: - { - break; - } - case ElementType.Array: - { - var a1 = (ArraySig)t1; - var a2 = (ArraySig)t2; - if (a1.Rank != a2.Rank) - { - return false; - } - break; - } - case ElementType.Var: - case ElementType.MVar: - { - //var v1 = (GenericSig)t1; - //var v2 = (GenericSig)t2; - //return v1.Number == v2.Number; - return true; - } - default: return true; - } - if (t1.Next != null && t2.Next != null) - { - return IsLooseTypeSigMatch(t1.Next, t2.Next); - } - return true; - } - - private bool IsLooseMatch(MethodDef method1, MethodDef method2) - { - if (method1.Name != method2.Name) - { - return false; - } - if (method1.GetParamCount() != method2.GetParamCount()) - { - return false; - } - if (!IsLooseTypeSigMatch(method1.ReturnType, method2.ReturnType)) - { - return false; - } - for (int i = 0, n = method1.GetParamCount(); i < n; i++) - { - if (!IsLooseTypeSigMatch(method1.GetParam(i), method2.GetParam(i))) - { - return false; - } - } - - return true; - } - - public bool TryFindMatchVirtualMethod(MethodDef method, out MethodDef matchMethodDef) - { - foreach (var parentOrInterfaceMethod in flatMethods) - { - if (IsLooseMatch(method, parentOrInterfaceMethod)) - { - matchMethodDef = parentOrInterfaceMethod; - return true; - } - } - matchMethodDef = null; - return false; - } - } - - - private readonly Dictionary _methodGroups = new Dictionary(); - private readonly Dictionary _visitedTypes = new Dictionary(); - - - - public VirtualMethodGroup GetMethodGroup(MethodDef methodDef) - { - if (_methodGroups.TryGetValue(methodDef, out var group)) - { - return group; - } - return null; - } - - public void CalculateType(TypeDef typeDef) - { - if (_visitedTypes.ContainsKey(typeDef)) - { - return; - } - - var typeMethods = new TypeFlatMethods(); - - var interfaceMethods = new List(); - if (typeDef.BaseType != null) - { - TypeDef baseTypeDef = MetaUtil.GetTypeDefOrGenericTypeBaseThrowException(typeDef.BaseType); - CalculateType(baseTypeDef); - typeMethods.flatMethods.AddRange(_visitedTypes[baseTypeDef].flatMethods); - foreach (var intfType in typeDef.Interfaces) - { - TypeDef intfTypeDef = MetaUtil.GetTypeDefOrGenericTypeBaseThrowException(intfType.Interface); - CalculateType(intfTypeDef); - //typeMethods.flatMethods.AddRange(_visitedTypes[intfTypeDef].flatMethods); - interfaceMethods.AddRange(_visitedTypes[intfTypeDef].flatMethods); - } - } - foreach (MethodDef method in interfaceMethods) - { - if (typeMethods.TryFindMatchVirtualMethod(method, out var matchMethodDef)) - { - // merge group - var group = _methodGroups[matchMethodDef]; - var matchGroup = _methodGroups[method]; - if (group != matchGroup) - { - foreach (var m in matchGroup.methods) - { - group.methods.Add(m); - _methodGroups[m] = group; - } - } - } - typeMethods.flatMethods.Add(method); - } - - foreach (MethodDef method in typeDef.Methods) - { - if (!method.IsVirtual) - { - continue; - } - if (typeMethods.TryFindMatchVirtualMethod(method, out var matchMethodDef)) - { - var group = _methodGroups[matchMethodDef]; - group.methods.Add(method); - _methodGroups.Add(method, group); - } - else - { - _methodGroups.Add(method, new VirtualMethodGroup() { methods = new List { method } }); - } - if (method.IsNewSlot) - { - typeMethods.flatMethods.Add(method); - } - } - _visitedTypes.Add(typeDef, typeMethods); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/VirtualMethodGroupCalculator.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/VirtualMethodGroupCalculator.cs.meta deleted file mode 100644 index 097106aa..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfusPasses/SymbolObfus/VirtualMethodGroupCalculator.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 649aeb6306500a04f8b7a3e01f5aaf0d -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfuscationMethodWhitelist.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfuscationMethodWhitelist.cs deleted file mode 100644 index 4fe07f3e..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfuscationMethodWhitelist.cs +++ /dev/null @@ -1,110 +0,0 @@ -using dnlib.DotNet; -using Obfuz.Editor; -using Obfuz.Utils; -using System.Linq; -using UnityEngine; - -namespace Obfuz -{ - public class ObfuscationMethodWhitelist - { - private readonly ObfuzIgnoreScopeComputeCache _obfuzComputeCache; - private readonly BurstCompileComputeCache _burstCompileComputeCache; - - public ObfuscationMethodWhitelist(ObfuzIgnoreScopeComputeCache obfuzComputeCache, BurstCompileComputeCache burstCompileComputeCache) - { - _obfuzComputeCache = obfuzComputeCache; - _burstCompileComputeCache = burstCompileComputeCache; - } - - public bool IsInWhiteList(ModuleDef module) - { - string modName = module.Assembly.Name; - if (modName == ConstValues.ObfuzRuntimeAssemblyName) - { - return true; - } - //if (MetaUtil.HasObfuzIgnoreScope(module)) - //{ - // return true; - //} - return false; - } - - private bool DoesMethodContainsRuntimeInitializeOnLoadMethodAttributeAndLoadTypeGreaterEqualAfterAssembliesLoaded(MethodDef method) - { - CustomAttribute ca = method.CustomAttributes.Find(ConstValues.RuntimeInitializedOnLoadMethodAttributeFullName); - if (ca != null && ca.ConstructorArguments.Count > 0) - { - RuntimeInitializeLoadType loadType = (RuntimeInitializeLoadType)ca.ConstructorArguments[0].Value; - if (loadType >= RuntimeInitializeLoadType.AfterAssembliesLoaded) - { - return true; - } - } - return false; - } - - public bool IsInWhiteList(MethodDef method) - { - TypeDef typeDef = method.DeclaringType; - //if (IsInWhiteList(typeDef)) - //{ - // return true; - //} - if (method.Name.StartsWith(ConstValues.ObfuzInternalSymbolNamePrefix)) - { - return true; - } - if (_obfuzComputeCache.HasSelfOrDeclaringOrEnclosingOrInheritObfuzIgnoreScope(method, typeDef, ObfuzScope.MethodBody)) - { - return true; - } - CustomAttribute ca = method.CustomAttributes.Find(ConstValues.RuntimeInitializedOnLoadMethodAttributeFullName); - if (DoesMethodContainsRuntimeInitializeOnLoadMethodAttributeAndLoadTypeGreaterEqualAfterAssembliesLoaded(method)) - { - return true; - } - if (method.CustomAttributes.Find(ConstValues.BurstCompileFullName) != null || _burstCompileComputeCache.IsBurstCompileMethodOrReferencedByBurstCompileMethod(method)) - { - return true; - } - - // don't obfuscate cctor when it has RuntimeInitializeOnLoadMethodAttribute with load type AfterAssembliesLoaded - if (method.IsStatic && method.Name == ".cctor" && typeDef.Methods.Any(m => DoesMethodContainsRuntimeInitializeOnLoadMethodAttributeAndLoadTypeGreaterEqualAfterAssembliesLoaded(m))) - { - return true; - } - return false; - } - - public bool IsInWhiteList(TypeDef type) - { - if (type.Name.StartsWith(ConstValues.ObfuzInternalSymbolNamePrefix)) - { - return true; - } - if (IsInWhiteList(type.Module)) - { - return true; - } - if (type.CustomAttributes.Find(ConstValues.BurstCompileFullName) != null) - { - return true; - } - if (_obfuzComputeCache.HasSelfOrDeclaringOrEnclosingOrInheritObfuzIgnoreScope(type, type.DeclaringType, ObfuzScope.TypeName)) - { - return true; - } - //if (type.DeclaringType != null && IsInWhiteList(type.DeclaringType)) - //{ - // return true; - //} - if (type.FullName == ConstValues.GeneratedEncryptionVirtualMachineFullName) - { - return true; - } - return false; - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfuscationMethodWhitelist.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfuscationMethodWhitelist.cs.meta deleted file mode 100644 index 0ef3bf32..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfuscationMethodWhitelist.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 8824d47fdc31cef41a899294491c8844 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfuscationPassContext.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfuscationPassContext.cs deleted file mode 100644 index 7f2f60f1..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfuscationPassContext.cs +++ /dev/null @@ -1,70 +0,0 @@ -using dnlib.DotNet; -using Obfuz.Data; -using Obfuz.Emit; -using Obfuz.Utils; -using System.Collections.Generic; - -namespace Obfuz -{ - public delegate IRandom RandomCreator(int seed); - - public class EncryptionScopeInfo - { - public readonly IEncryptor encryptor; - public readonly RandomCreator localRandomCreator; - - public EncryptionScopeInfo(IEncryptor encryptor, RandomCreator localRandomCreator) - { - this.encryptor = encryptor; - this.localRandomCreator = localRandomCreator; - } - } - - public class EncryptionScopeProvider - { - private readonly EncryptionScopeInfo _defaultStaticScope; - private readonly EncryptionScopeInfo _defaultDynamicScope; - private readonly HashSet _dynamicSecretAssemblyNames; - - public EncryptionScopeProvider(EncryptionScopeInfo defaultStaticScope, EncryptionScopeInfo defaultDynamicScope, HashSet dynamicSecretAssemblyNames) - { - _defaultStaticScope = defaultStaticScope; - _defaultDynamicScope = defaultDynamicScope; - _dynamicSecretAssemblyNames = dynamicSecretAssemblyNames; - } - - public EncryptionScopeInfo GetScope(ModuleDef module) - { - if (_dynamicSecretAssemblyNames.Contains(module.Assembly.Name)) - { - return _defaultDynamicScope; - } - else - { - return _defaultStaticScope; - } - } - - public bool IsDynamicSecretAssembly(ModuleDef module) - { - return _dynamicSecretAssemblyNames.Contains(module.Assembly.Name); - } - } - - public class ObfuscationPassContext - { - public static ObfuscationPassContext Current { get; set; } - - public CoreSettingsFacade coreSettings; - - public GroupByModuleEntityManager moduleEntityManager; - - public AssemblyCache assemblyCache; - public List modulesToObfuscate; - public List allObfuscationRelativeModules; - public ObfuzIgnoreScopeComputeCache obfuzIgnoreScopeComputeCache; - - public ObfuscationMethodWhitelist whiteList; - public ConfigurablePassPolicy passPolicy; - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfuscationPassContext.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfuscationPassContext.cs.meta deleted file mode 100644 index 827ddc44..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfuscationPassContext.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 196d07f0366ce4b46bf0333fa4918d40 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Obfuscator.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Obfuscator.cs deleted file mode 100644 index 95a5f83f..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Obfuscator.cs +++ /dev/null @@ -1,352 +0,0 @@ -using dnlib.DotNet; -using Obfuz.Data; -using Obfuz.Emit; -using Obfuz.EncryptionVM; -using Obfuz.ObfusPasses.CleanUp; -using Obfuz.ObfusPasses.Instinct; -using Obfuz.ObfusPasses.SymbolObfus; -using Obfuz.Unity; -using Obfuz.Utils; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using UnityEngine; - -namespace Obfuz -{ - - public class Obfuscator - { - private readonly CoreSettingsFacade _coreSettings; - private readonly List _allObfuscationRelativeAssemblyNames; - private readonly HashSet _assembliesUsingDynamicSecretKeys; - private readonly CombinedAssemblyResolver _assemblyResolver; - - private readonly ConfigurablePassPolicy _passPolicy; - - private readonly Pipeline _pipeline1 = new Pipeline(); - private readonly Pipeline _pipeline2 = new Pipeline(); - - private ObfuscationPassContext _ctx; - - public Obfuscator(ObfuscatorBuilder builder) - { - CheckSettings(builder.CoreSettingsFacade); - _coreSettings = builder.CoreSettingsFacade; - - _allObfuscationRelativeAssemblyNames = _coreSettings.assembliesToObfuscate - .Concat(_coreSettings.nonObfuscatedButReferencingObfuscatedAssemblies) - .ToList(); - _assembliesUsingDynamicSecretKeys = new HashSet(_coreSettings.assembliesUsingDynamicSecretKeys); - - _assemblyResolver = new CombinedAssemblyResolver(new PathAssemblyResolver(_coreSettings.assemblySearchPaths.ToArray()), new UnityProjectManagedAssemblyResolver(_coreSettings.buildTarget)); - _passPolicy = new ConfigurablePassPolicy(_coreSettings.assembliesToObfuscate, _coreSettings.enabledObfuscationPasses, _coreSettings.obfuscationPassRuleConfigFiles); - - _pipeline1.AddPass(new InstinctPass()); - foreach (var pass in _coreSettings.obfuscationPasses) - { - if (pass is SymbolObfusPass symbolObfusPass) - { - _pipeline2.AddPass(pass); - } - else - { - _pipeline1.AddPass(pass); - } - } - _pipeline1.AddPass(new CleanUpInstructionPass()); - _pipeline2.AddPass(new RemoveObfuzAttributesPass()); - } - - private void CheckSettings(CoreSettingsFacade settings) - { - var totalAssemblies = new HashSet(); - foreach (var assName in settings.assembliesToObfuscate) - { - if (string.IsNullOrWhiteSpace(assName)) - { - throw new Exception($"the name of some assembly in assembliesToObfuscate is empty! Please check your settings."); - } - if (!totalAssemblies.Add(assName)) - { - throw new Exception($"the name of assembly `{assName}` in assembliesToObfuscate is duplicated! Please check your settings."); - } - } - foreach (var assName in settings.nonObfuscatedButReferencingObfuscatedAssemblies) - { - if (string.IsNullOrWhiteSpace(assName)) - { - throw new Exception($"the name of some assembly in nonObfuscatedButReferencingObfuscatedAssemblies is empty! Please check your settings."); - } - if (!totalAssemblies.Add(assName)) - { - throw new Exception($"the name of assembly `{assName}` in nonObfuscatedButReferencingObfuscatedAssemblies is duplicated! Please check your settings."); - } - } - } - - public void Run() - { - Debug.Log($"Obfuscator begin"); - var sw = new System.Diagnostics.Stopwatch(); - sw.Start(); - FileUtil.RecreateDir(_coreSettings.obfuscatedAssemblyOutputPath); - FileUtil.RecreateDir(_coreSettings.obfuscatedAssemblyTempOutputPath); - RunPipeline(_pipeline1); - _assemblyResolver.InsertFirst(new PathAssemblyResolver(_coreSettings.obfuscatedAssemblyTempOutputPath)); - RunPipeline(_pipeline2); - FileUtil.CopyDir(_coreSettings.obfuscatedAssemblyTempOutputPath, _coreSettings.obfuscatedAssemblyOutputPath, true); - sw.Stop(); - Debug.Log($"Obfuscator end. cost time: {sw.ElapsedMilliseconds} ms"); - } - - private void RunPipeline(Pipeline pipeline) - { - if (pipeline.Empty) - { - return; - } - OnPreObfuscation(pipeline); - DoObfuscation(pipeline); - OnPostObfuscation(pipeline); - } - - private IEncryptor CreateEncryptionVirtualMachine(byte[] secretKey) - { - var vmCreator = new VirtualMachineCreator(_coreSettings.encryptionVmGenerationSecretKey); - var vm = vmCreator.CreateVirtualMachine(_coreSettings.encryptionVmOpCodeCount); - var vmGenerator = new VirtualMachineCodeGenerator(vm); - - string encryptionVmCodeFile = _coreSettings.encryptionVmCodeFile; - if (!File.Exists(encryptionVmCodeFile)) - { - throw new Exception($"EncryptionVm CodeFile:`{encryptionVmCodeFile}` not exists! Please run `Obfuz/GenerateVm` to generate it!"); - } - if (!vmGenerator.ValidateMatch(encryptionVmCodeFile)) - { - throw new Exception($"EncryptionVm CodeFile:`{encryptionVmCodeFile}` not match with encryptionVM settings! Please run `Obfuz/GenerateVm` to update it!"); - } - var vms = new VirtualMachineSimulator(vm, secretKey); - - var generatedVmTypes = ReflectionUtil.FindTypesInCurrentAppDomain("Obfuz.EncryptionVM.GeneratedEncryptionVirtualMachine"); - if (generatedVmTypes.Count == 0) - { - throw new Exception($"class Obfuz.EncryptionVM.GeneratedEncryptionVirtualMachine not found in any assembly! Please run `Obfuz/GenerateVm` to generate it!"); - } - if (generatedVmTypes.Count > 1) - { - throw new Exception($"class Obfuz.EncryptionVM.GeneratedEncryptionVirtualMachine found in multiple assemblies! Please retain only one!"); - } - - var gvmInstance = (IEncryptor)Activator.CreateInstance(generatedVmTypes[0], new object[] { secretKey }); - - VerifyVm(vm, vms, gvmInstance); - - return vms; - } - - private void VerifyVm(VirtualMachine vm, VirtualMachineSimulator vms, IEncryptor gvm) - { - int testInt = 11223344; - long testLong = 1122334455667788L; - float testFloat = 1234f; - double testDouble = 1122334455.0; - string testString = "hello,world"; - for (int i = 0; i < vm.opCodes.Length; i++) - { - int ops = i * vm.opCodes.Length + i; - //int salt = i; - //int ops = -1135538782; - int salt = -879409147; - { - int encryptedIntOfVms = vms.Encrypt(testInt, ops, salt); - int decryptedIntOfVms = vms.Decrypt(encryptedIntOfVms, ops, salt); - if (decryptedIntOfVms != testInt) - { - throw new Exception($"VirtualMachineSimulator decrypt failed! opCode:{i}, originalValue:{testInt} decryptedValue:{decryptedIntOfVms}"); - } - int encryptedValueOfGvm = gvm.Encrypt(testInt, ops, salt); - int decryptedValueOfGvm = gvm.Decrypt(encryptedValueOfGvm, ops, salt); - if (encryptedValueOfGvm != encryptedIntOfVms) - { - throw new Exception($"encryptedValue not match! opCode:{i}, originalValue:{testInt} encryptedValue VirtualMachineSimulator:{encryptedIntOfVms} GeneratedEncryptionVirtualMachine:{encryptedValueOfGvm}"); - } - if (decryptedValueOfGvm != testInt) - { - throw new Exception($"GeneratedEncryptionVirtualMachine decrypt failed! opCode:{i}, originalValue:{testInt} decryptedValue:{decryptedValueOfGvm}"); - } - } - { - long encryptedLongOfVms = vms.Encrypt(testLong, ops, salt); - long decryptedLongOfVms = vms.Decrypt(encryptedLongOfVms, ops, salt); - if (decryptedLongOfVms != testLong) - { - throw new Exception($"VirtualMachineSimulator decrypt long failed! opCode:{i}, originalValue:{testLong} decryptedValue:{decryptedLongOfVms}"); - } - long encryptedValueOfGvm = gvm.Encrypt(testLong, ops, salt); - long decryptedValueOfGvm = gvm.Decrypt(encryptedValueOfGvm, ops, salt); - if (encryptedValueOfGvm != encryptedLongOfVms) - { - throw new Exception($"encryptedValue not match! opCode:{i}, originalValue:{testLong} encryptedValue VirtualMachineSimulator:{encryptedLongOfVms} GeneratedEncryptionVirtualMachine:{encryptedValueOfGvm}"); - } - if (decryptedValueOfGvm != testLong) - { - throw new Exception($"GeneratedEncryptionVirtualMachine decrypt long failed! opCode:{i}, originalValue:{testLong} decryptedValue:{decryptedValueOfGvm}"); - } - } - { - float encryptedFloatOfVms = vms.Encrypt(testFloat, ops, salt); - float decryptedFloatOfVms = vms.Decrypt(encryptedFloatOfVms, ops, salt); - if (decryptedFloatOfVms != testFloat) - { - throw new Exception("encryptedFloat not match"); - } - float encryptedValueOfGvm = gvm.Encrypt(testFloat, ops, salt); - float decryptedValueOfGvm = gvm.Decrypt(encryptedFloatOfVms, ops, salt); - if (encryptedFloatOfVms != encryptedValueOfGvm) - { - throw new Exception($"encryptedValue not match! opCode:{i}, originalValue:{testFloat} encryptedValue"); - } - if (decryptedValueOfGvm != testFloat) - { - throw new Exception($"GeneratedEncryptionVirtualMachine decrypt float failed! opCode:{i}, originalValue:{testFloat}"); - } - } - { - double encryptedFloatOfVms = vms.Encrypt(testDouble, ops, salt); - double decryptedFloatOfVms = vms.Decrypt(encryptedFloatOfVms, ops, salt); - if (decryptedFloatOfVms != testDouble) - { - throw new Exception("encryptedFloat not match"); - } - double encryptedValueOfGvm = gvm.Encrypt(testDouble, ops, salt); - double decryptedValueOfGvm = gvm.Decrypt(encryptedFloatOfVms, ops, salt); - if (encryptedFloatOfVms != encryptedValueOfGvm) - { - throw new Exception($"encryptedValue not match! opCode:{i}, originalValue:{testDouble} encryptedValue"); - } - if (decryptedValueOfGvm != testDouble) - { - throw new Exception($"GeneratedEncryptionVirtualMachine decrypt float failed! opCode:{i}, originalValue:{testDouble}"); - } - } - - { - byte[] encryptedStrOfVms = vms.Encrypt(testString, ops, salt); - string decryptedStrOfVms = vms.DecryptString(encryptedStrOfVms, 0, encryptedStrOfVms.Length, ops, salt); - if (decryptedStrOfVms != testString) - { - throw new Exception($"VirtualMachineSimulator decrypt string failed! opCode:{i}, originalValue:{testString} decryptedValue:{decryptedStrOfVms}"); - } - byte[] encryptedStrOfGvm = gvm.Encrypt(testString, ops, salt); - string decryptedStrOfGvm = gvm.DecryptString(encryptedStrOfGvm, 0, encryptedStrOfGvm.Length, ops, salt); - if (!encryptedStrOfGvm.SequenceEqual(encryptedStrOfVms)) - { - throw new Exception($"encryptedValue not match! opCode:{i}, originalValue:{testString} encryptedValue VirtualMachineSimulator:{encryptedStrOfVms} GeneratedEncryptionVirtualMachine:{encryptedStrOfGvm}"); - } - if (decryptedStrOfGvm != testString) - { - throw new Exception($"GeneratedEncryptionVirtualMachine decrypt string failed! opCode:{i}, originalValue:{testString} decryptedValue:{decryptedStrOfGvm}"); - } - } - } - } - - private EncryptionScopeInfo CreateEncryptionScope(byte[] byteSecret) - { - int[] intSecretKey = KeyGenerator.ConvertToIntKey(byteSecret); - IEncryptor encryption = CreateEncryptionVirtualMachine(byteSecret); - RandomCreator localRandomCreator = (seed) => new RandomWithKey(intSecretKey, _coreSettings.randomSeed ^ seed); - return new EncryptionScopeInfo(encryption, localRandomCreator); - } - - private EncryptionScopeProvider CreateEncryptionScopeProvider() - { - var defaultStaticScope = CreateEncryptionScope(_coreSettings.defaultStaticSecretKey); - var defaultDynamicScope = CreateEncryptionScope(_coreSettings.defaultDynamicSecretKey); - foreach (string dynamicAssName in _assembliesUsingDynamicSecretKeys) - { - if (!_coreSettings.assembliesToObfuscate.Contains(dynamicAssName)) - { - throw new Exception($"Dynamic secret assembly `{dynamicAssName}` should be in the assembliesToObfuscate list!"); - } - } - return new EncryptionScopeProvider(defaultStaticScope, defaultDynamicScope, _assembliesUsingDynamicSecretKeys); - } - - private void OnPreObfuscation(Pipeline pipeline) - { - AssemblyCache assemblyCache = new AssemblyCache(_assemblyResolver); - List modulesToObfuscate = new List(); - List allObfuscationRelativeModules = new List(); - LoadAssemblies(assemblyCache, modulesToObfuscate, allObfuscationRelativeModules); - - EncryptionScopeProvider encryptionScopeProvider = CreateEncryptionScopeProvider(); - var moduleEntityManager = new GroupByModuleEntityManager() - { - EncryptionScopeProvider = encryptionScopeProvider, - }; - var obfuzIgnoreScopeComputeCache = new ObfuzIgnoreScopeComputeCache(); - _ctx = new ObfuscationPassContext - { - coreSettings = _coreSettings, - assemblyCache = assemblyCache, - modulesToObfuscate = modulesToObfuscate, - allObfuscationRelativeModules = allObfuscationRelativeModules, - - moduleEntityManager = moduleEntityManager, - - obfuzIgnoreScopeComputeCache = obfuzIgnoreScopeComputeCache, - - whiteList = new ObfuscationMethodWhitelist(obfuzIgnoreScopeComputeCache, new BurstCompileComputeCache(modulesToObfuscate, allObfuscationRelativeModules)), - passPolicy = _passPolicy, - }; - ObfuscationPassContext.Current = _ctx; - pipeline.Start(); - } - - private void LoadAssemblies(AssemblyCache assemblyCache, List modulesToObfuscate, List allObfuscationRelativeModules) - { - foreach (string assName in _allObfuscationRelativeAssemblyNames) - { - ModuleDefMD mod = assemblyCache.TryLoadModule(assName); - if (mod == null) - { - Debug.Log($"assembly: {assName} not found! ignore."); - continue; - } - if (_coreSettings.assembliesToObfuscate.Contains(assName)) - { - modulesToObfuscate.Add(mod); - } - allObfuscationRelativeModules.Add(mod); - } - } - - private void WriteAssemblies() - { - foreach (ModuleDef mod in _ctx.allObfuscationRelativeModules) - { - string assNameWithExt = mod.Name; - string outputFile = $"{_coreSettings.obfuscatedAssemblyTempOutputPath}/{assNameWithExt}"; - mod.Write(outputFile); - Debug.Log($"save module. name:{mod.Assembly.Name} output:{outputFile}"); - } - } - - private void DoObfuscation(Pipeline pipeline) - { - pipeline.Run(); - } - - private void OnPostObfuscation(Pipeline pipeline) - { - pipeline.Stop(); - - _ctx.moduleEntityManager.Done(); - _ctx.moduleEntityManager.Done(); - WriteAssemblies(); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Obfuscator.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Obfuscator.cs.meta deleted file mode 100644 index 08291f34..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Obfuscator.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ca9c4e108bde2184885e599f2bd19a00 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfuscatorBuilder.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfuscatorBuilder.cs deleted file mode 100644 index 35e29ee7..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfuscatorBuilder.cs +++ /dev/null @@ -1,207 +0,0 @@ -using Obfuz.EncryptionVM; -using Obfuz.ObfusPasses; -using Obfuz.ObfusPasses.CallObfus; -using Obfuz.ObfusPasses.ConstEncrypt; -using Obfuz.ObfusPasses.ControlFlowObfus; -using Obfuz.ObfusPasses.EvalStackObfus; -using Obfuz.ObfusPasses.ExprObfus; -using Obfuz.ObfusPasses.FieldEncrypt; -using Obfuz.ObfusPasses.SymbolObfus; -using Obfuz.Settings; -using Obfuz.Utils; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using UnityEditor; - -namespace Obfuz -{ - - public class CoreSettingsFacade - { - public BuildTarget buildTarget; - - public byte[] defaultStaticSecretKey; - public byte[] defaultDynamicSecretKey; - public List assembliesUsingDynamicSecretKeys; - public int randomSeed; - - public string encryptionVmGenerationSecretKey; - public int encryptionVmOpCodeCount; - public string encryptionVmCodeFile; - - public List assembliesToObfuscate; - public List nonObfuscatedButReferencingObfuscatedAssemblies; - public List assemblySearchPaths; - public string obfuscatedAssemblyOutputPath; - public string obfuscatedAssemblyTempOutputPath; - - public ObfuscationPassType enabledObfuscationPasses; - public List obfuscationPassRuleConfigFiles; - public List obfuscationPasses; - } - - public class ObfuscatorBuilder - { - private CoreSettingsFacade _coreSettingsFacade; - - public CoreSettingsFacade CoreSettingsFacade => _coreSettingsFacade; - - public void InsertTopPriorityAssemblySearchPaths(List assemblySearchPaths) - { - _coreSettingsFacade.assemblySearchPaths.InsertRange(0, assemblySearchPaths); - } - - public ObfuscatorBuilder AddPass(IObfuscationPass pass) - { - _coreSettingsFacade.obfuscationPasses.Add(pass); - return this; - } - - public Obfuscator Build() - { - return new Obfuscator(this); - } - - public static List BuildUnityAssemblySearchPaths(bool searchPathIncludeUnityEditorDll = false) - { - string applicationContentsPath = EditorApplication.applicationContentsPath; - var searchPaths = new List - { -#if UNITY_2021_1_OR_NEWER -#if UNITY_STANDALONE_WIN || (UNITY_EDITOR_WIN && UNITY_SERVER) || UNITY_WSA || UNITY_LUMIN - "MonoBleedingEdge/lib/mono/unityaot-win32", - "MonoBleedingEdge/lib/mono/unityaot-win32/Facades", -#elif UNITY_STANDALONE_OSX || (UNITY_EDITOR_OSX && UNITY_SERVER) || UNITY_IOS || UNITY_TVOS - "MonoBleedingEdge/lib/mono/unityaot-macos", - "MonoBleedingEdge/lib/mono/unityaot-macos/Facades", -#else - "MonoBleedingEdge/lib/mono/unityaot-linux", - "MonoBleedingEdge/lib/mono/unityaot-linux/Facades", -#endif -#else - "MonoBleedingEdge/lib/mono/unityaot", - "MonoBleedingEdge/lib/mono/unityaot/Facades", -#endif - -#if UNITY_STANDALONE_WIN || (UNITY_EDITOR_WIN && UNITY_SERVER) - "PlaybackEngines/windowsstandalonesupport/Variations/il2cpp/Managed", -#elif UNITY_STANDALONE_OSX || (UNITY_EDITOR_OSX && UNITY_SERVER) - "PlaybackEngines/MacStandaloneSupport/Variations/il2cpp/Managed", -#elif UNITY_STANDALONE_LINUX || (UNITY_EDITOR_LINUX && UNITY_SERVER) - "PlaybackEngines/LinuxStandaloneSupport/Variations/il2cpp/Managed", -#elif UNITY_ANDROID - "PlaybackEngines/AndroidPlayer/Variations/il2cpp/Managed", -#elif UNITY_IOS - "PlaybackEngines/iOSSupport/Variations/il2cpp/Managed", -#elif UNITY_MINIGAME || UNITY_WEIXINMINIGAME -#if TUANJIE_1_1_OR_NEWER - "PlaybackEngines/WeixinMiniGameSupport/Variations/il2cpp/nondevelopment/Data/Managed", -#else - "PlaybackEngines/WeixinMiniGameSupport/Variations/nondevelopment/Data/Managed", -#endif -#elif UNITY_OPENHARMONY - "PlaybackEngines/OpenHarmonyPlayer/Variations/il2cpp/Managed", -#elif UNITY_WEBGL - "PlaybackEngines/WebGLSupport/Variations/nondevelopment/Data/Managed", -#elif UNITY_TVOS - "PlaybackEngines/AppleTVSupport/Variations/il2cpp/Managed", -#elif UNITY_WSA - "PlaybackEngines/WSASupport/Variations/il2cpp/Managed", -#elif UNITY_LUMIN - "PlaybackEngines/LuminSupport/Variations/il2cpp/Managed", -#else -#error "Unsupported platform, please report to us" -#endif - }; - - if (searchPathIncludeUnityEditorDll) - { - searchPaths.Add("Managed/UnityEngine"); - } - - var resultPaths = new List(); - foreach (var path in searchPaths) - { - string candidatePath1 = Path.Combine(applicationContentsPath, path); - if (Directory.Exists(candidatePath1)) - { - resultPaths.Add(candidatePath1); - } - if (path.StartsWith("PlaybackEngines")) - { - string candidatePath2 = Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(applicationContentsPath)), path); - if (Directory.Exists(candidatePath2)) - { - resultPaths.Add(candidatePath2); - } - } - } - return resultPaths; - } - - public static ObfuscatorBuilder FromObfuzSettings(ObfuzSettings settings, BuildTarget target, bool searchPathIncludeUnityEditorInstallLocation, bool searchPathIncludeUnityEditorDll = false) - { - List searchPaths = searchPathIncludeUnityEditorInstallLocation ? - BuildUnityAssemblySearchPaths(searchPathIncludeUnityEditorDll).Concat(settings.assemblySettings.additionalAssemblySearchPaths).ToList() - : settings.assemblySettings.additionalAssemblySearchPaths.ToList(); - foreach (var path in searchPaths) - { - bool exists = Directory.Exists(path); - UnityEngine.Debug.Log($"search path:{path} exists:{exists}"); - } - var builder = new ObfuscatorBuilder - { - _coreSettingsFacade = new CoreSettingsFacade() - { - buildTarget = target, - defaultStaticSecretKey = KeyGenerator.GenerateKey(settings.secretSettings.defaultStaticSecretKey, VirtualMachine.SecretKeyLength), - defaultDynamicSecretKey = KeyGenerator.GenerateKey(settings.secretSettings.defaultDynamicSecretKey, VirtualMachine.SecretKeyLength), - assembliesUsingDynamicSecretKeys = settings.secretSettings.assembliesUsingDynamicSecretKeys.ToList(), - randomSeed = settings.secretSettings.randomSeed, - encryptionVmGenerationSecretKey = settings.encryptionVMSettings.codeGenerationSecretKey, - encryptionVmOpCodeCount = settings.encryptionVMSettings.encryptionOpCodeCount, - encryptionVmCodeFile = settings.encryptionVMSettings.codeOutputPath, - assembliesToObfuscate = settings.assemblySettings.GetAssembliesToObfuscate(), - nonObfuscatedButReferencingObfuscatedAssemblies = settings.assemblySettings.nonObfuscatedButReferencingObfuscatedAssemblies.ToList(), - assemblySearchPaths = searchPaths, - obfuscatedAssemblyOutputPath = settings.GetObfuscatedAssemblyOutputPath(target), - obfuscatedAssemblyTempOutputPath = settings.GetObfuscatedAssemblyTempOutputPath(target), - enabledObfuscationPasses = settings.obfuscationPassSettings.enabledPasses, - obfuscationPassRuleConfigFiles = settings.obfuscationPassSettings.ruleFiles?.ToList() ?? new List(), - obfuscationPasses = new List(), - }, - }; - ObfuscationPassType obfuscationPasses = settings.obfuscationPassSettings.enabledPasses; - if (obfuscationPasses.HasFlag(ObfuscationPassType.ConstEncrypt)) - { - builder.AddPass(new ConstEncryptPass(settings.constEncryptSettings.ToFacade())); - } - if (obfuscationPasses.HasFlag(ObfuscationPassType.ExprObfus)) - { - builder.AddPass(new ExprObfusPass(settings.exprObfusSettings.ToFacade())); - } - if (obfuscationPasses.HasFlag(ObfuscationPassType.EvalStackObfus)) - { - builder.AddPass(new EvalStackObfusPass(settings.evalStackObfusSettings.ToFacade())); - } - if (obfuscationPasses.HasFlag(ObfuscationPassType.FieldEncrypt)) - { - builder.AddPass(new FieldEncryptPass(settings.fieldEncryptSettings.ToFacade())); - } - if (obfuscationPasses.HasFlag(ObfuscationPassType.CallObfus)) - { - builder.AddPass(new CallObfusPass(settings.callObfusSettings.ToFacade())); - } - if (obfuscationPasses.HasFlag(ObfuscationPassType.ControlFlowObfus)) - { - builder.AddPass(new ControlFlowObfusPass(settings.controlFlowObfusSettings.ToFacade())); - } - if (obfuscationPasses.HasFlag(ObfuscationPassType.SymbolObfus)) - { - builder.AddPass(new SymbolObfusPass(settings.symbolObfusSettings.ToFacade())); - } - return builder; - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfuscatorBuilder.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfuscatorBuilder.cs.meta deleted file mode 100644 index 261993be..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/ObfuscatorBuilder.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 77e279242d764ed4d996db96f35e8570 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Obfuz.Editor.asmdef b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Obfuz.Editor.asmdef deleted file mode 100644 index e1b3933b..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Obfuz.Editor.asmdef +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "Obfuz.Editor", - "rootNamespace": "", - "references": [ - "GUID:4140bd2e2764f1f47ab93125ecb61942" - ], - "includePlatforms": [ - "Editor" - ], - "excludePlatforms": [], - "allowUnsafeCode": true, - "overrideReferences": false, - "precompiledReferences": [], - "autoReferenced": true, - "defineConstraints": [], - "versionDefines": [], - "noEngineReferences": false -} \ No newline at end of file diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Obfuz.Editor.asmdef.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Obfuz.Editor.asmdef.meta deleted file mode 100644 index d010c098..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Obfuz.Editor.asmdef.meta +++ /dev/null @@ -1,7 +0,0 @@ -fileFormatVersion: 2 -guid: 66e09fc524ec6594b8d6ca1d91aa1a41 -AssemblyDefinitionImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Pipeline.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Pipeline.cs deleted file mode 100644 index e0869b41..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Pipeline.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System.Collections.Generic; -using System.Diagnostics; - -namespace Obfuz -{ - public class Pipeline - { - private readonly List _passes = new List(); - - public bool Empty => _passes.Count == 0; - - public Pipeline AddPass(IObfuscationPass pass) - { - _passes.Add(pass); - return this; - } - - public void Start() - { - foreach (var pass in _passes) - { - pass.Start(); - } - } - - public void Stop() - { - - foreach (var pass in _passes) - { - pass.Stop(); - } - } - - public void Run() - { - var sw = new Stopwatch(); - foreach (var pass in _passes) - { - sw.Restart(); - pass.Process(); - sw.Stop(); - UnityEngine.Debug.Log($"Pass: {pass.GetType().Name} process cost time: {sw.ElapsedMilliseconds}ms"); - } - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Pipeline.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Pipeline.cs.meta deleted file mode 100644 index fd3558ce..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Pipeline.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 0915452219e923d428b9a408cf413844 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings.meta deleted file mode 100644 index 64d3c0a6..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 4939d1f80df50b34c85ffc8fbe530887 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/AssemblySettings.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/AssemblySettings.cs deleted file mode 100644 index 97923519..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/AssemblySettings.cs +++ /dev/null @@ -1,41 +0,0 @@ -using Obfuz.Editor; -using System; -using System.Collections.Generic; -using UnityEngine; - -namespace Obfuz.Settings -{ - [Serializable] - public class AssemblySettings - { - - [Tooltip("name of assemblies to obfuscate, please don't add 'Obfuz.Runtime'")] - public string[] assembliesToObfuscate; - - [Tooltip("name of assemblies not obfuscated but reference assemblies to obfuscated ")] - public string[] nonObfuscatedButReferencingObfuscatedAssemblies; - - [Tooltip("additional assembly search paths")] - public string[] additionalAssemblySearchPaths; - - [Tooltip("obfuscate Obfuz.Runtime")] - public bool obfuscateObfuzRuntime = true; - - public List GetAssembliesToObfuscate() - { - var asses = new List(assembliesToObfuscate ?? Array.Empty()); - if (obfuscateObfuzRuntime && !asses.Contains(ConstValues.ObfuzRuntimeAssemblyName)) - { - asses.Add(ConstValues.ObfuzRuntimeAssemblyName); - } - return asses; - } - - public List GetObfuscationRelativeAssemblyNames() - { - var asses = GetAssembliesToObfuscate(); - asses.AddRange(nonObfuscatedButReferencingObfuscatedAssemblies ?? Array.Empty()); - return asses; - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/AssemblySettings.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/AssemblySettings.cs.meta deleted file mode 100644 index 8a139403..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/AssemblySettings.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 735c01fddc6f0c54a83e1feb9a60e13a -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/BuildPipelineSettings.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/BuildPipelineSettings.cs deleted file mode 100644 index 8d167fad..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/BuildPipelineSettings.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; -using UnityEngine; - -namespace Obfuz.Settings -{ - [Serializable] - public class BuildPipelineSettings - { - [Tooltip("enable Obfuz")] - public bool enable = true; - - [Tooltip("callback order of LinkXmlProcessor")] - public int linkXmlProcessCallbackOrder = 10000; - - [Tooltip("callback order of ObfuscationProcess")] - public int obfuscationProcessCallbackOrder = 10000; - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/BuildPipelineSettings.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/BuildPipelineSettings.cs.meta deleted file mode 100644 index 64ce1ddb..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/BuildPipelineSettings.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 68737b215ecfe344a93d56007e186432 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/CallObfuscationSettings.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/CallObfuscationSettings.cs deleted file mode 100644 index a7ee139a..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/CallObfuscationSettings.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using UnityEngine; - -namespace Obfuz.Settings -{ - public enum ProxyMode - { - Dispatch, - Delegate, - } - - public class CallObfuscationSettingsFacade - { - public ProxyMode proxyMode; - public int obfuscationLevel; - public int maxProxyMethodCountPerDispatchMethod; - public bool obfuscateCallToMethodInMscorlib; - public List ruleFiles; - } - - [Serializable] - public class CallObfuscationSettings - { - public ProxyMode proxyMode = ProxyMode.Dispatch; - - [Tooltip("The obfuscation level for the obfuscation. Higher levels provide more security but may impact performance.")] - [Range(1, 4)] - public int obfuscationLevel = 1; - - [Tooltip("The maximum number of proxy methods that can be generated per dispatch method. This helps to limit the complexity of the generated code and improve performance.")] - public int maxProxyMethodCountPerDispatchMethod = 100; - - [Tooltip("Whether to obfuscate calls to methods in mscorlib. Enable this option will impact performance.")] - public bool obfuscateCallToMethodInMscorlib; - - [Tooltip("rule config xml files")] - public string[] ruleFiles; - - public CallObfuscationSettingsFacade ToFacade() - { - return new CallObfuscationSettingsFacade - { - proxyMode = proxyMode, - obfuscationLevel = obfuscationLevel, - maxProxyMethodCountPerDispatchMethod = maxProxyMethodCountPerDispatchMethod, - obfuscateCallToMethodInMscorlib = obfuscateCallToMethodInMscorlib, - ruleFiles = ruleFiles?.ToList() ?? new List(), - }; - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/CallObfuscationSettings.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/CallObfuscationSettings.cs.meta deleted file mode 100644 index ce268f1e..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/CallObfuscationSettings.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ae4ddc19ecf8d9940b444f5b66c23efa -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/ConstEncryptionSettings.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/ConstEncryptionSettings.cs deleted file mode 100644 index 6baffbc1..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/ConstEncryptionSettings.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using UnityEngine; - -namespace Obfuz.Settings -{ - public class ConstEncryptionSettingsFacade - { - public int encryptionLevel; - public List ruleFiles; - } - - [Serializable] - public class ConstEncryptionSettings - { - [Tooltip("The encryption level for the obfuscation. Higher levels provide more security but may impact performance.")] - [Range(1, 4)] - public int encryptionLevel = 1; - - [Tooltip("config xml files")] - public string[] ruleFiles; - - public ConstEncryptionSettingsFacade ToFacade() - { - return new ConstEncryptionSettingsFacade - { - ruleFiles = ruleFiles?.ToList() ?? new List(), - encryptionLevel = encryptionLevel, - }; - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/ConstEncryptionSettings.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/ConstEncryptionSettings.cs.meta deleted file mode 100644 index d5cef401..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/ConstEncryptionSettings.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 2b189f76d7da58e4b9403b4fe87265b4 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/ControlFlowObfuscationSettings.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/ControlFlowObfuscationSettings.cs deleted file mode 100644 index 67474b1b..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/ControlFlowObfuscationSettings.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System; -using System.Collections.Generic; -using UnityEngine; - -namespace Obfuz.Settings -{ - - public class ControlFlowObfuscationSettingsFacade - { - public int minInstructionCountOfBasicBlockToObfuscate; - public List ruleFiles; - } - - [Serializable] - public class ControlFlowObfuscationSettings - { - public int minInstructionCountOfBasicBlockToObfuscate = 3; - - [Tooltip("rule config xml files")] - public string[] ruleFiles; - - public ControlFlowObfuscationSettingsFacade ToFacade() - { - return new ControlFlowObfuscationSettingsFacade - { - minInstructionCountOfBasicBlockToObfuscate = minInstructionCountOfBasicBlockToObfuscate, - ruleFiles = new List(ruleFiles ?? Array.Empty()), - }; - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/ControlFlowObfuscationSettings.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/ControlFlowObfuscationSettings.cs.meta deleted file mode 100644 index 8d8b0f28..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/ControlFlowObfuscationSettings.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: d40d2fb33f081b2458505c7566b1bc8f -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/EncryptionVMSettings.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/EncryptionVMSettings.cs deleted file mode 100644 index 50159587..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/EncryptionVMSettings.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; -using UnityEngine; - -namespace Obfuz.Settings -{ - [Serializable] - public class EncryptionVMSettings - { - [Tooltip("secret key for generating encryption virtual machine source code")] - public string codeGenerationSecretKey = "Obfuz"; - - [Tooltip("encryption OpCode count, should be power of 2 and >= 64")] - public int encryptionOpCodeCount = 256; - - [Tooltip("encryption virtual machine source code output path")] - public string codeOutputPath = "Assets/Obfuz/GeneratedEncryptionVirtualMachine.cs"; - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/EncryptionVMSettings.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/EncryptionVMSettings.cs.meta deleted file mode 100644 index 0257381b..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/EncryptionVMSettings.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: f0e626d510710c540bdc36b4dca93340 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/EvalStackObfuscationSettings.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/EvalStackObfuscationSettings.cs deleted file mode 100644 index b880f534..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/EvalStackObfuscationSettings.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System; -using System.Collections.Generic; -using UnityEngine; - -namespace Obfuz.Settings -{ - - public class EvalStackObfuscationSettingsFacade - { - public List ruleFiles; - } - - [Serializable] - public class EvalStackObfuscationSettings - { - [Tooltip("rule config xml files")] - public string[] ruleFiles; - - public EvalStackObfuscationSettingsFacade ToFacade() - { - return new EvalStackObfuscationSettingsFacade - { - ruleFiles = new List(ruleFiles ?? Array.Empty()), - }; - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/EvalStackObfuscationSettings.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/EvalStackObfuscationSettings.cs.meta deleted file mode 100644 index 8e4d8d59..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/EvalStackObfuscationSettings.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 3c985896b3a4ef84292cb0cfbc79dc10 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/ExprObfuscationSettings.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/ExprObfuscationSettings.cs deleted file mode 100644 index c4d0f750..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/ExprObfuscationSettings.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System; -using System.Collections.Generic; -using UnityEngine; - -namespace Obfuz.Settings -{ - - public class ExprObfuscationSettingsFacade - { - public List ruleFiles; - } - - [Serializable] - public class ExprObfuscationSettings - { - [Tooltip("rule config xml files")] - public string[] ruleFiles; - - public ExprObfuscationSettingsFacade ToFacade() - { - return new ExprObfuscationSettingsFacade - { - ruleFiles = new List(ruleFiles ?? Array.Empty()), - }; - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/ExprObfuscationSettings.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/ExprObfuscationSettings.cs.meta deleted file mode 100644 index 55fb66c9..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/ExprObfuscationSettings.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: d63d19f2b1a9f7c4b9812577d215c367 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/FieldEncryptionSettings.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/FieldEncryptionSettings.cs deleted file mode 100644 index 460eca1d..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/FieldEncryptionSettings.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using UnityEngine; - -namespace Obfuz.Settings -{ - public class FieldEncryptionSettingsFacade - { - public int encryptionLevel; - public List ruleFiles; - } - - [Serializable] - public class FieldEncryptionSettings - { - [Tooltip("The encryption level for the obfuscation. Higher levels provide more security but may impact performance.")] - [Range(1, 4)] - public int encryptionLevel = 1; - - [Tooltip("rule config xml files")] - public string[] ruleFiles; - - public FieldEncryptionSettingsFacade ToFacade() - { - return new FieldEncryptionSettingsFacade - { - ruleFiles = ruleFiles?.ToList() ?? new List(), - encryptionLevel = encryptionLevel, - }; - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/FieldEncryptionSettings.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/FieldEncryptionSettings.cs.meta deleted file mode 100644 index fbc0e2ed..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/FieldEncryptionSettings.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 56cff1f5683d9114e8f13cee917ea582 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/GarbageCodeGenerationSettings.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/GarbageCodeGenerationSettings.cs deleted file mode 100644 index b17748f1..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/GarbageCodeGenerationSettings.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System; - -namespace Obfuz.Settings -{ - public enum GarbageCodeType - { - None, - Config, - UI, - } - - [Serializable] - public class GarbageCodeGenerationTask - { - public int codeGenerationRandomSeed; - - public string classNamespace = "__GarbageCode"; - - public string classNamePrefix = "__GeneratedGarbageClass"; - - public int classCount = 100; - - public int methodCountPerClass = 10; - - public int fieldCountPerClass = 50; - - public GarbageCodeType garbageCodeType = GarbageCodeType.Config; - - public string outputPath = "Assets/Obfuz/GarbageCode"; - } - - [Serializable] - public class GarbageCodeGenerationSettings - { - public string codeGenerationSecret = "Garbage Code"; - - public GarbageCodeGenerationTask defaultTask; - - public GarbageCodeGenerationTask[] additionalTasks; - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/GarbageCodeGenerationSettings.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/GarbageCodeGenerationSettings.cs.meta deleted file mode 100644 index 326444eb..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/GarbageCodeGenerationSettings.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 220b44e477cfa2848bd287c38db4fd21 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/ObfuscationLevel.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/ObfuscationLevel.cs deleted file mode 100644 index b3f57020..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/ObfuscationLevel.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace Obfuz.Settings -{ - public enum ObfuscationLevel - { - None = 0, - Basic = 1, - Advanced = 2, - MostAdvanced = 3 - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/ObfuscationLevel.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/ObfuscationLevel.cs.meta deleted file mode 100644 index c6567f4e..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/ObfuscationLevel.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: dd8e1281c6c9bcd419fecc67980cb673 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/ObfuscationPassSettings.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/ObfuscationPassSettings.cs deleted file mode 100644 index 837c8b0c..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/ObfuscationPassSettings.cs +++ /dev/null @@ -1,16 +0,0 @@ -using Obfuz.ObfusPasses; -using System; -using UnityEngine; - -namespace Obfuz.Settings -{ - [Serializable] - public class ObfuscationPassSettings - { - [Tooltip("enable obfuscation pass")] - public ObfuscationPassType enabledPasses = ObfuscationPassType.All; - - [Tooltip("rule config xml files")] - public string[] ruleFiles; - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/ObfuscationPassSettings.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/ObfuscationPassSettings.cs.meta deleted file mode 100644 index 147fed67..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/ObfuscationPassSettings.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 9cb41a6fb7293ce47807e432d80f2b2a -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/ObfuzSettings.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/ObfuzSettings.cs deleted file mode 100644 index 19fbe3cb..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/ObfuzSettings.cs +++ /dev/null @@ -1,122 +0,0 @@ -using System.IO; -using UnityEditor; -using UnityEditorInternal; -using UnityEngine; - -namespace Obfuz.Settings -{ - - public class ObfuzSettings : ScriptableObject - { - [Tooltip("build pipeline settings")] - public BuildPipelineSettings buildPipelineSettings; - - [Tooltip("assembly settings")] - public AssemblySettings assemblySettings; - - [Tooltip("obfuscation pass settings")] - public ObfuscationPassSettings obfuscationPassSettings; - - [Tooltip("secret settings")] - public SecretSettings secretSettings; - - [Tooltip("encryption virtual machine settings")] - public EncryptionVMSettings encryptionVMSettings; - - [Tooltip("symbol obfuscation settings")] - public SymbolObfuscationSettings symbolObfusSettings; - - [Tooltip("const encryption settings")] - public ConstEncryptionSettings constEncryptSettings; - - [Tooltip("eval stack obfuscation settings")] - public EvalStackObfuscationSettings evalStackObfusSettings; - - [Tooltip("field encryption settings")] - public FieldEncryptionSettings fieldEncryptSettings; - - [Tooltip("call obfuscation settings")] - public CallObfuscationSettings callObfusSettings; - - [Tooltip("expression obfuscation settings")] - public ExprObfuscationSettings exprObfusSettings; - - [Tooltip("control flow obfuscation settings")] - public ControlFlowObfuscationSettings controlFlowObfusSettings; - - [Tooltip("garbage code generator settings")] - public GarbageCodeGenerationSettings garbageCodeGenerationSettings; - - [Tooltip("polymorphic dll settings")] - public PolymorphicDllSettings polymorphicDllSettings; - - public string ObfuzRootDir => $"Library/Obfuz"; - - public string GetObfuscatedAssemblyOutputPath(BuildTarget target) - { - return $"{ObfuzRootDir}/{target}/ObfuscatedAssemblies"; - } - - public string GetOriginalAssemblyBackupDir(BuildTarget target) - { - return $"{ObfuzRootDir}/{target}/OriginalAssemblies"; - } - - public string GetObfuscatedAssemblyTempOutputPath(BuildTarget target) - { - return $"{ObfuzRootDir}/{target}/TempObfuscatedAssemblies"; - } - - public string GetObfuscatedLinkXmlPath(BuildTarget target) - { - return $"{ObfuzRootDir}/{target}/link.xml"; - } - - private static ObfuzSettings s_Instance; - - public static ObfuzSettings Instance - { - get - { - if (!s_Instance) - { - LoadOrCreate(); - } - return s_Instance; - } - } - - protected static string SettingsPath => "ProjectSettings/Obfuz.asset"; - - private static ObfuzSettings LoadOrCreate() - { - string filePath = SettingsPath; - var arr = InternalEditorUtility.LoadSerializedFileAndForget(filePath); - //Debug.Log($"typeof arr:{arr?.GetType()} arr[0]:{(arr != null && arr.Length > 0 ? arr[0].GetType(): null)}"); - - if (arr != null && arr.Length > 0 && arr[0] is ObfuzSettings obfuzSettings) - { - s_Instance = obfuzSettings; - } - else - { - s_Instance = s_Instance ?? CreateInstance(); - } - return s_Instance; - } - - public static void Save() - { - if (!s_Instance) - { - return; - } - - string filePath = SettingsPath; - string directoryName = Path.GetDirectoryName(filePath); - Directory.CreateDirectory(directoryName); - UnityEngine.Object[] obj = new ObfuzSettings[1] { s_Instance }; - InternalEditorUtility.SaveToSerializedFileAndForget(obj, filePath, true); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/ObfuzSettings.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/ObfuzSettings.cs.meta deleted file mode 100644 index 8bad58fc..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/ObfuzSettings.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: c414eef017e565c4db1442ec64ec52fe -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/ObfuzSettingsProvider.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/ObfuzSettingsProvider.cs deleted file mode 100644 index 2b0afced..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/ObfuzSettingsProvider.cs +++ /dev/null @@ -1,123 +0,0 @@ -using UnityEditor; -using UnityEngine.UIElements; - -namespace Obfuz.Settings -{ - public class ObfuzSettingsProvider : SettingsProvider - { - - private static ObfuzSettingsProvider s_provider; - - [SettingsProvider] - public static SettingsProvider CreateMyCustomSettingsProvider() - { - if (s_provider == null) - { - s_provider = new ObfuzSettingsProvider(); - using (var so = new SerializedObject(ObfuzSettings.Instance)) - { - s_provider.keywords = GetSearchKeywordsFromSerializedObject(so); - } - } - return s_provider; - } - - - private SerializedObject _serializedObject; - private SerializedProperty _buildPipelineSettings; - - private SerializedProperty _assemblySettings; - private SerializedProperty _obfuscationPassSettings; - private SerializedProperty _secretSettings; - private SerializedProperty _encryptionVMSettings; - - private SerializedProperty _symbolObfusSettings; - private SerializedProperty _constEncryptSettings; - private SerializedProperty _evalStackObfusSettings; - private SerializedProperty _fieldEncryptSettings; - private SerializedProperty _callObfusSettings; - private SerializedProperty _exprObfusSettings; - private SerializedProperty _controlFlowObfusSettings; - - private SerializedProperty _garbageCodeGenerationSettings; - - private SerializedProperty _polymorphicDllSettings; - - public ObfuzSettingsProvider() : base("Project/Obfuz", SettingsScope.Project) - { - } - - public override void OnActivate(string searchContext, VisualElement rootElement) - { - InitGUI(); - } - - public override void OnDeactivate() - { - base.OnDeactivate(); - ObfuzSettings.Save(); - } - - private void InitGUI() - { - var setting = ObfuzSettings.Instance; - _serializedObject?.Dispose(); - _serializedObject = new SerializedObject(setting); - _buildPipelineSettings = _serializedObject.FindProperty("buildPipelineSettings"); - - _assemblySettings = _serializedObject.FindProperty("assemblySettings"); - _obfuscationPassSettings = _serializedObject.FindProperty("obfuscationPassSettings"); - _secretSettings = _serializedObject.FindProperty("secretSettings"); - - _encryptionVMSettings = _serializedObject.FindProperty("encryptionVMSettings"); - - _symbolObfusSettings = _serializedObject.FindProperty("symbolObfusSettings"); - _constEncryptSettings = _serializedObject.FindProperty("constEncryptSettings"); - _evalStackObfusSettings = _serializedObject.FindProperty("evalStackObfusSettings"); - _exprObfusSettings = _serializedObject.FindProperty("exprObfusSettings"); - _fieldEncryptSettings = _serializedObject.FindProperty("fieldEncryptSettings"); - _callObfusSettings = _serializedObject.FindProperty("callObfusSettings"); - _controlFlowObfusSettings = _serializedObject.FindProperty("controlFlowObfusSettings"); - - _garbageCodeGenerationSettings = _serializedObject.FindProperty("garbageCodeGenerationSettings"); - - _polymorphicDllSettings = _serializedObject.FindProperty("polymorphicDllSettings"); - } - - public override void OnGUI(string searchContext) - { - if (_serializedObject == null || !_serializedObject.targetObject) - { - InitGUI(); - } - _serializedObject.Update(); - EditorGUI.BeginChangeCheck(); - - EditorGUILayout.PropertyField(_buildPipelineSettings); - - EditorGUILayout.PropertyField(_assemblySettings); - EditorGUILayout.PropertyField(_obfuscationPassSettings); - EditorGUILayout.PropertyField(_secretSettings); - - EditorGUILayout.PropertyField(_encryptionVMSettings); - - EditorGUILayout.PropertyField(_symbolObfusSettings); - EditorGUILayout.PropertyField(_constEncryptSettings); - EditorGUILayout.PropertyField(_evalStackObfusSettings); - EditorGUILayout.PropertyField(_exprObfusSettings); - EditorGUILayout.PropertyField(_fieldEncryptSettings); - EditorGUILayout.PropertyField(_callObfusSettings); - EditorGUILayout.PropertyField(_controlFlowObfusSettings); - - EditorGUILayout.PropertyField(_garbageCodeGenerationSettings); - - EditorGUILayout.PropertyField(_polymorphicDllSettings); - - if (EditorGUI.EndChangeCheck()) - { - _serializedObject.ApplyModifiedProperties(); - ObfuzSettings.Save(); - } - } - } -} \ No newline at end of file diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/ObfuzSettingsProvider.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/ObfuzSettingsProvider.cs.meta deleted file mode 100644 index 471477b1..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/ObfuzSettingsProvider.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 9f020d09993a1aa41bae3258ec33d5fc -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/PolymorphicDllSettings.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/PolymorphicDllSettings.cs deleted file mode 100644 index e2d1180e..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/PolymorphicDllSettings.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; -using UnityEngine; - -namespace Obfuz.Settings -{ - [Serializable] - public class PolymorphicDllSettings - { - [Tooltip("enable polymorphic DLL generation")] - public bool enable = true; - - [Tooltip("secret key for generating polymorphic DLL source code")] - public string codeGenerationSecretKey = "obfuz-polymorphic-key"; - - [Tooltip("disable load standard dotnet dll")] - public bool disableLoadStandardDll = false; - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/PolymorphicDllSettings.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/PolymorphicDllSettings.cs.meta deleted file mode 100644 index f1885893..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/PolymorphicDllSettings.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ecab9aab707d08949b2d602a4d61084a -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/SecretSettings.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/SecretSettings.cs deleted file mode 100644 index 9a9f6947..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/SecretSettings.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System; -using UnityEngine; - -namespace Obfuz.Settings -{ - [Serializable] - public class SecretSettings - { - - [Tooltip("default static secret key")] - public string defaultStaticSecretKey = "Code Philosophy-Static"; - - [Tooltip("default dynamic secret key")] - public string defaultDynamicSecretKey = "Code Philosophy-Dynamic"; - - [Tooltip("default static secret key output path")] - public string staticSecretKeyOutputPath = $"Assets/Resources/Obfuz/defaultStaticSecretKey.bytes"; - - [Tooltip("default dynamic secret key output path")] - public string dynamicSecretKeyOutputPath = $"Assets/Resources/Obfuz/defaultDynamicSecretKey.bytes"; - - [Tooltip("random seed")] - public int randomSeed = 0; - - [Tooltip("name of assemblies those use dynamic secret key")] - public string[] assembliesUsingDynamicSecretKeys; - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/SecretSettings.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/SecretSettings.cs.meta deleted file mode 100644 index 7e26a78a..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/SecretSettings.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 7ac4fe2a6df113444b67412254452a00 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/SymbolObfuscationSettings.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/SymbolObfuscationSettings.cs deleted file mode 100644 index f661c4d7..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/SymbolObfuscationSettings.cs +++ /dev/null @@ -1,70 +0,0 @@ -using Obfuz.Utils; -using System; -using System.Collections.Generic; -using System.Linq; -using UnityEngine; - -namespace Obfuz.Settings -{ - public class SymbolObfuscationSettingsFacade - { - public bool debug; - public string obfuscatedNamePrefix; - public bool useConsistentNamespaceObfuscation; - public bool detectReflectionCompatibility; - public bool keepUnknownSymbolInSymbolMappingFile; - public string symbolMappingFile; - public List ruleFiles; - public List customRenamePolicyTypes; - } - - [Serializable] - public class SymbolObfuscationSettings - { - public bool debug; - - [Tooltip("prefix for obfuscated name to avoid name confliction with original name")] - public string obfuscatedNamePrefix = "$"; - - [Tooltip("obfuscate same namespace to one name")] - public bool useConsistentNamespaceObfuscation = true; - - [Tooltip("detect reflection compatibility, if true, will detect if the obfuscated name is compatibility with reflection, such as Type.GetType(), Enum.Parse(), etc.")] - public bool detectReflectionCompatibility = true; - - [Tooltip("keep unknown symbol in symbol mapping file, if false, unknown symbol will be removed from mapping file")] - public bool keepUnknownSymbolInSymbolMappingFile = true; - - [Tooltip("symbol mapping file path")] - public string symbolMappingFile = "Assets/Obfuz/SymbolObfus/symbol-mapping.xml"; - - [Tooltip("debug symbol mapping file path, used for debugging purposes")] - public string debugSymbolMappingFile = "Assets/Obfuz/SymbolObfus/symbol-mapping-debug.xml"; - - [Tooltip("rule files")] - public string[] ruleFiles; - - [Tooltip("custom rename policy types")] - public string[] customRenamePolicyTypes; - - public string GetSymbolMappingFile() - { - return debug ? debugSymbolMappingFile : symbolMappingFile; - } - - public SymbolObfuscationSettingsFacade ToFacade() - { - return new SymbolObfuscationSettingsFacade - { - debug = debug, - obfuscatedNamePrefix = obfuscatedNamePrefix, - useConsistentNamespaceObfuscation = useConsistentNamespaceObfuscation, - detectReflectionCompatibility = detectReflectionCompatibility, - keepUnknownSymbolInSymbolMappingFile = keepUnknownSymbolInSymbolMappingFile, - symbolMappingFile = GetSymbolMappingFile(), - ruleFiles = ruleFiles?.ToList() ?? new List(), - customRenamePolicyTypes = customRenamePolicyTypes?.Select(typeName => ReflectionUtil.FindUniqueTypeInCurrentAppDomain(typeName)).ToList() ?? new List(), - }; - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/SymbolObfuscationSettings.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/SymbolObfuscationSettings.cs.meta deleted file mode 100644 index 58779d69..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Settings/SymbolObfuscationSettings.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 2484a8a12a689df46b5eb7fc4ccac81f -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Unity.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Unity.meta deleted file mode 100644 index 8456b1dc..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Unity.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: bc9b206fbf6a69f4c99a6ec9b0b27c69 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Unity/LinkXmlProcess.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Unity/LinkXmlProcess.cs deleted file mode 100644 index 23f27653..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Unity/LinkXmlProcess.cs +++ /dev/null @@ -1,149 +0,0 @@ -using Obfuz.Settings; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Xml; -using UnityEditor; -using UnityEditor.Build; -using UnityEditor.Build.Reporting; -using UnityEditor.UnityLinker; -using UnityEngine; -using FileUtil = Obfuz.Utils.FileUtil; - -namespace Obfuz.Unity -{ - public class LinkXmlProcess : IUnityLinkerProcessor - { - public int callbackOrder => ObfuzSettings.Instance.buildPipelineSettings.linkXmlProcessCallbackOrder; - - public string GenerateAdditionalLinkXmlFile(BuildReport report, UnityLinkerBuildPipelineData data) - { - return GenerateAdditionalLinkXmlFile(data.target); - } - -#if !UNITY_2021_2_OR_NEWER - - public void OnBeforeRun(BuildReport report, UnityLinkerBuildPipelineData data) - { - - } - - public void OnAfterRun(BuildReport report, UnityLinkerBuildPipelineData data) - { - - } -#endif - - public static string GenerateAdditionalLinkXmlFile(BuildTarget target) - { - ObfuzSettings settings = ObfuzSettings.Instance; - string symbolMappingFile = settings.symbolObfusSettings.GetSymbolMappingFile(); - if (!File.Exists(symbolMappingFile)) - { - Debug.LogWarning($"Symbol mapping file not found: {symbolMappingFile}. Skipping link.xml generation."); - return null; - } - string linkXmlPath = settings.GetObfuscatedLinkXmlPath(target); - FileUtil.CreateParentDir(linkXmlPath); - - var writer = System.Xml.XmlWriter.Create(linkXmlPath, - new System.Xml.XmlWriterSettings { Encoding = Encoding.UTF8, Indent = true }); - try - { - var symbolMapping = new LiteSymbolMappingReader(symbolMappingFile); - string[] linkGuids = AssetDatabase.FindAssets("t:TextAsset"); - var linkXmlPaths = linkGuids.Select(guid => AssetDatabase.GUIDToAssetPath(guid)) - .Where(f => Path.GetFileName(f) == "link.xml") - .ToArray(); - - var assembliesToObfuscated = new HashSet(settings.assemblySettings.GetAssembliesToObfuscate()); - - writer.WriteStartDocument(); - writer.WriteStartElement("linker"); - - // Preserve Obfuz.Runtime assembly - writer.WriteStartElement("assembly"); - writer.WriteAttributeString("fullname", "Obfuz.Runtime"); - writer.WriteAttributeString("preserve", "all"); - writer.WriteEndElement(); - - foreach (string linkPath in linkXmlPaths) - { - TransformLinkXml(linkPath, symbolMapping, assembliesToObfuscated, writer); - } - writer.WriteEndElement(); - writer.WriteEndDocument(); - } - finally - { - writer.Close(); - } - Debug.Log($"LinkXmlProcess write {Path.GetFullPath(linkXmlPath)}"); - return Path.GetFullPath(linkXmlPath); - } - - private static void TransformLinkXml(string xmlFile, LiteSymbolMappingReader symbolMapping, HashSet assembliesToObfuscated, XmlWriter writer) - { - Debug.Log($"LinkXmlProcess transform link.xml:{xmlFile}"); - var doc = new XmlDocument(); - doc.Load(xmlFile); - var root = doc.DocumentElement; - foreach (XmlNode assNode in root.ChildNodes) - { - if (!(assNode is XmlElement assElement)) - { - continue; - } - if (assElement.Name == "assembly") - { - string assemblyName = assElement.GetAttribute("fullname"); - if (string.IsNullOrEmpty(assemblyName)) - { - throw new Exception($"Invalid node name: {assElement.Name}. attribute 'fullname' missing."); - } - if (!assembliesToObfuscated.Contains(assemblyName)) - { - continue; // Skip assemblies that are not to be obfuscated - } - writer.WriteStartElement("assembly"); - writer.WriteAttributeString("fullname", assemblyName); - if (assElement.HasAttribute("preserve")) - { - writer.WriteAttributeString("preserve", assElement.GetAttribute("preserve")); - } - - foreach (XmlNode typeNode in assElement.ChildNodes) - { - if (typeNode is XmlElement typeElement) - { - if (typeElement.Name == "type") - { - string typeName = typeElement.GetAttribute("fullname"); - if (string.IsNullOrEmpty(typeName)) - { - throw new Exception($"Invalid node name: {typeElement.Name}. attribute 'fullname' missing."); - } - if (!symbolMapping.TryGetNewTypeName(assemblyName, typeName, out string newTypeName)) - { - continue; - } - - writer.WriteStartElement("type"); - writer.WriteAttributeString("fullname", newTypeName); - if (typeElement.HasAttribute("preserve")) - { - writer.WriteAttributeString("preserve", typeElement.GetAttribute("preserve")); - } - writer.WriteEndElement(); - } - } - } - - writer.WriteEndElement(); - } - } - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Unity/LinkXmlProcess.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Unity/LinkXmlProcess.cs.meta deleted file mode 100644 index 7ddd2b48..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Unity/LinkXmlProcess.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 66881cca1e4a78c44b4c9fcd7f8b4fb9 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Unity/LiteSymbolMappingReader.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Unity/LiteSymbolMappingReader.cs deleted file mode 100644 index c04c6838..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Unity/LiteSymbolMappingReader.cs +++ /dev/null @@ -1,116 +0,0 @@ - -using System.Collections.Generic; -using System.Xml; - -namespace Obfuz.Unity -{ - - public class LiteSymbolMappingReader - { - class TypeMappingInfo - { - public string oldFullName; - public string newFullName; - - //public Dictionary MethodMappings = new Dictionary(); - } - - class AssemblyMappingInfo - { - public Dictionary TypeMappings = new Dictionary(); - public Dictionary MethodMappings = new Dictionary(); - } - - private readonly Dictionary _assemblies = new Dictionary(); - - public LiteSymbolMappingReader(string mappingFile) - { - LoadXmlMappingFile(mappingFile); - } - - private void LoadXmlMappingFile(string mappingFile) - { - var doc = new XmlDocument(); - doc.Load(mappingFile); - var root = doc.DocumentElement; - foreach (XmlNode node in root.ChildNodes) - { - if (!(node is XmlElement element)) - { - continue; - } - LoadAssemblyMapping(element); - } - } - - private void LoadAssemblyMapping(XmlElement ele) - { - if (ele.Name != "assembly") - { - throw new System.Exception($"Invalid node name: {ele.Name}. Expected 'assembly'."); - } - string assName = ele.GetAttribute("name"); - if (string.IsNullOrEmpty(assName)) - { - throw new System.Exception($"Invalid node name: {ele.Name}. attribute 'name' missing."); - } - if (!_assemblies.TryGetValue(assName, out var assemblyMappingInfo)) - { - assemblyMappingInfo = new AssemblyMappingInfo(); - _assemblies[assName] = assemblyMappingInfo; - } - - foreach (XmlNode node in ele.ChildNodes) - { - if (!(node is XmlElement element)) - { - continue; - } - if (element.Name == "type") - { - LoadTypeMapping(element, assemblyMappingInfo); - } - } - } - - private void LoadTypeMapping(XmlElement ele, AssemblyMappingInfo assemblyMappingInfo) - { - string oldFullName = ele.GetAttribute("fullName"); - string newFullName = ele.GetAttribute("newFullName"); - string status = ele.GetAttribute("status"); - if (status == "Renamed") - { - if (string.IsNullOrEmpty(oldFullName) || string.IsNullOrEmpty(newFullName)) - { - throw new System.Exception($"Invalid node name: {ele.Name}. attributes 'fullName' or 'newFullName' missing."); - } - assemblyMappingInfo.TypeMappings[oldFullName] = newFullName; - } - //foreach (XmlNode node in ele.ChildNodes) - //{ - // if (!(node is XmlElement c)) - // { - // continue; - // } - // if (node.Name == "method") - // { - // LoadMethodMapping(c); - // } - //} - } - - public bool TryGetNewTypeName(string assemblyName, string oldFullName, out string newFullName) - { - newFullName = null; - if (_assemblies.TryGetValue(assemblyName, out var assemblyMappingInfo)) - { - if (assemblyMappingInfo.TypeMappings.TryGetValue(oldFullName, out newFullName)) - { - return true; - } - } - return false; - } - - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Unity/LiteSymbolMappingReader.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Unity/LiteSymbolMappingReader.cs.meta deleted file mode 100644 index 4abd760e..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Unity/LiteSymbolMappingReader.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 8429e75dcc6a7e742a3cabaa3e8491c5 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Unity/ObfuscationBeginEventArgs.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Unity/ObfuscationBeginEventArgs.cs deleted file mode 100644 index b8f2397e..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Unity/ObfuscationBeginEventArgs.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace Obfuz.Unity -{ - public class ObfuscationBeginEventArgs - { - public string scriptAssembliesPath; - public string obfuscatedScriptAssembliesPath; - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Unity/ObfuscationBeginEventArgs.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Unity/ObfuscationBeginEventArgs.cs.meta deleted file mode 100644 index a2d5e11a..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Unity/ObfuscationBeginEventArgs.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 8e3d38018839d4844bf1e15631946e65 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Unity/ObfuscationEndEventArgs.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Unity/ObfuscationEndEventArgs.cs deleted file mode 100644 index ac2fa76a..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Unity/ObfuscationEndEventArgs.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace Obfuz.Unity -{ - public class ObfuscationEndEventArgs - { - public bool success; - public string originalScriptAssembliesPath; - public string obfuscatedScriptAssembliesPath; - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Unity/ObfuscationEndEventArgs.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Unity/ObfuscationEndEventArgs.cs.meta deleted file mode 100644 index fe376819..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Unity/ObfuscationEndEventArgs.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 6b198ad99d0a9c145b1bc2b29b25b8ac -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Unity/ObfuscationProcess.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Unity/ObfuscationProcess.cs deleted file mode 100644 index 8dd48a3d..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Unity/ObfuscationProcess.cs +++ /dev/null @@ -1,144 +0,0 @@ -using dnlib.DotNet; -using Obfuz.Settings; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using UnityEditor; -using UnityEditor.Build; -using UnityEditor.Build.Reporting; -using UnityEngine; -using FileUtil = Obfuz.Utils.FileUtil; - -namespace Obfuz.Unity -{ - -#if UNITY_2019_1_OR_NEWER - public class ObfuscationProcess : IPostBuildPlayerScriptDLLs - { - public int callbackOrder => ObfuzSettings.Instance.buildPipelineSettings.obfuscationProcessCallbackOrder; - - public static event Action OnObfuscationBegin; - - public static event Action OnObfuscationEnd; - - public void OnPostBuildPlayerScriptDLLs(BuildReport report) - { -#if !UNITY_2022_1_OR_NEWER - RunObfuscate(report.files); -#else - RunObfuscate(report.GetFiles()); -#endif - } - - private static void BackupOriginalDlls(string srcDir, string dstDir, HashSet dllNames) - { - FileUtil.RecreateDir(dstDir); - foreach (string dllName in dllNames) - { - string srcFile = Path.Combine(srcDir, dllName + ".dll"); - string dstFile = Path.Combine(dstDir, dllName + ".dll"); - if (File.Exists(srcFile)) - { - File.Copy(srcFile, dstFile, true); - Debug.Log($"BackupOriginalDll {srcFile} -> {dstFile}"); - } - } - } - - public static void ValidateReferences(string stagingAreaTempManagedDllDir, HashSet assembliesToObfuscated, HashSet obfuscationRelativeAssemblyNames) - { - var modCtx = ModuleDef.CreateModuleContext(); - var asmResolver = (AssemblyResolver)modCtx.AssemblyResolver; - - foreach (string assFile in Directory.GetFiles(stagingAreaTempManagedDllDir, "*.dll", SearchOption.AllDirectories)) - { - ModuleDefMD mod = ModuleDefMD.Load(File.ReadAllBytes(assFile), modCtx); - string modName = mod.Assembly.Name; - foreach (AssemblyRef assRef in mod.GetAssemblyRefs()) - { - string refAssName = assRef.Name; - if (assembliesToObfuscated.Contains(refAssName) && !obfuscationRelativeAssemblyNames.Contains(modName)) - { - throw new BuildFailedException($"assembly:{modName} references to obfuscated assembly:{refAssName}, but it's not been added to ObfuzSettings.AssemblySettings.NonObfuscatedButReferencingObfuscatedAssemblies."); - } - } - mod.Dispose(); - } - } - - private static void RunObfuscate(BuildFile[] files) - { - ObfuzSettings settings = ObfuzSettings.Instance; - if (!settings.buildPipelineSettings.enable) - { - Debug.Log("Obfuscation is disabled."); - return; - } - - Debug.Log("Obfuscation begin..."); - var buildTarget = EditorUserBuildSettings.activeBuildTarget; - - var obfuscationRelativeAssemblyNames = new HashSet(settings.assemblySettings.GetObfuscationRelativeAssemblyNames()); - string stagingAreaTempManagedDllDir = Path.GetDirectoryName(files.First(file => file.path.EndsWith(".dll")).path); - string backupPlayerScriptAssembliesPath = settings.GetOriginalAssemblyBackupDir(buildTarget); - BackupOriginalDlls(stagingAreaTempManagedDllDir, backupPlayerScriptAssembliesPath, obfuscationRelativeAssemblyNames); - - string applicationContentsPath = EditorApplication.applicationContentsPath; - - var obfuscatorBuilder = ObfuscatorBuilder.FromObfuzSettings(settings, buildTarget, false); - - var assemblySearchDirs = new List - { - stagingAreaTempManagedDllDir, - }; - obfuscatorBuilder.InsertTopPriorityAssemblySearchPaths(assemblySearchDirs); - - ValidateReferences(stagingAreaTempManagedDllDir, new HashSet(obfuscatorBuilder.CoreSettingsFacade.assembliesToObfuscate), obfuscationRelativeAssemblyNames); - - - OnObfuscationBegin?.Invoke(new ObfuscationBeginEventArgs - { - scriptAssembliesPath = stagingAreaTempManagedDllDir, - obfuscatedScriptAssembliesPath = obfuscatorBuilder.CoreSettingsFacade.obfuscatedAssemblyOutputPath, - }); - bool succ = false; - - try - { - Obfuscator obfuz = obfuscatorBuilder.Build(); - obfuz.Run(); - - foreach (var dllName in obfuscationRelativeAssemblyNames) - { - string src = $"{obfuscatorBuilder.CoreSettingsFacade.obfuscatedAssemblyOutputPath}/{dllName}.dll"; - string dst = $"{stagingAreaTempManagedDllDir}/{dllName}.dll"; - - if (!File.Exists(src)) - { - Debug.LogWarning($"obfuscation assembly not found! skip copy. path:{src}"); - continue; - } - File.Copy(src, dst, true); - Debug.Log($"obfuscate dll:{dst}"); - } - succ = true; - } - catch (Exception e) - { - succ = false; - Debug.LogException(e); - Debug.LogError($"Obfuscation failed."); - } - OnObfuscationEnd?.Invoke(new ObfuscationEndEventArgs - { - success = succ, - originalScriptAssembliesPath = backupPlayerScriptAssembliesPath, - obfuscatedScriptAssembliesPath = stagingAreaTempManagedDllDir, - }); - - Debug.Log("Obfuscation end."); - } - } -#endif -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Unity/ObfuscationProcess.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Unity/ObfuscationProcess.cs.meta deleted file mode 100644 index de6b391f..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Unity/ObfuscationProcess.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: fc7a8b1e20c66164699de44d0a302cb7 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Unity/ObfuzMenu.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Unity/ObfuzMenu.cs deleted file mode 100644 index be1147d1..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Unity/ObfuzMenu.cs +++ /dev/null @@ -1,88 +0,0 @@ -using Obfuz.EncryptionVM; -using Obfuz.GarbageCodeGeneration; -using Obfuz.Settings; -using Obfuz.Utils; -using System.IO; -using UnityEditor; -using UnityEngine; -using FileUtil = Obfuz.Utils.FileUtil; - -namespace Obfuz.Unity -{ - public static class ObfuzMenu - { - - [MenuItem("Obfuz/Settings...", priority = 1)] - public static void OpenSettings() => SettingsService.OpenProjectSettings("Project/Obfuz"); - - [MenuItem("Obfuz/GenerateEncryptionVM", priority = 62)] - public static void GenerateEncryptionVM() - { - EncryptionVMSettings settings = ObfuzSettings.Instance.encryptionVMSettings; - var generator = new VirtualMachineCodeGenerator(settings.codeGenerationSecretKey, settings.encryptionOpCodeCount); - generator.Generate(settings.codeOutputPath); - AssetDatabase.Refresh(); - } - - [MenuItem("Obfuz/GenerateSecretKeyFile", priority = 63)] - public static void SaveSecretFile() - { - SecretSettings settings = ObfuzSettings.Instance.secretSettings; - - var staticSecretBytes = KeyGenerator.GenerateKey(settings.defaultStaticSecretKey, VirtualMachine.SecretKeyLength); - SaveKey(staticSecretBytes, settings.staticSecretKeyOutputPath); - Debug.Log($"Save static secret key to {settings.staticSecretKeyOutputPath}"); - var dynamicSecretBytes = KeyGenerator.GenerateKey(settings.defaultDynamicSecretKey, VirtualMachine.SecretKeyLength); - SaveKey(dynamicSecretBytes, settings.dynamicSecretKeyOutputPath); - Debug.Log($"Save dynamic secret key to {settings.dynamicSecretKeyOutputPath}"); - AssetDatabase.Refresh(); - } - - [MenuItem("Obfuz/GarbageCode/GenerateCodes", priority = 100)] - public static void GenerateGarbageCodes() - { - Debug.Log($"Generating garbage codes begin."); - GarbageCodeGenerationSettings settings = ObfuzSettings.Instance.garbageCodeGenerationSettings; - var generator = new GarbageCodeGenerator(settings); - generator.Generate(); - AssetDatabase.Refresh(); - Debug.Log($"Generating garbage codes end."); - } - - [MenuItem("Obfuz/GarbageCode/CleanGeneratedCodes", priority = 101)] - public static void CleanGeneratedGarbageCodes() - { - Debug.Log($"Clean generated garbage codes begin."); - GarbageCodeGenerationSettings settings = ObfuzSettings.Instance.garbageCodeGenerationSettings; - var generator = new GarbageCodeGenerator(settings); - generator.CleanCodes(); - AssetDatabase.Refresh(); - Debug.Log($"Clean generated garbage codes end."); - } - - private static void SaveKey(byte[] secret, string secretOutputPath) - { - FileUtil.CreateParentDir(secretOutputPath); - File.WriteAllBytes(secretOutputPath, secret); - } - - [MenuItem("Obfuz/Documents/Quick Start")] - public static void OpenQuickStart() => Application.OpenURL("https://www.obfuz.com/docs/beginner/quickstart"); - - [MenuItem("Obfuz/Documents/FAQ")] - public static void OpenFAQ() => Application.OpenURL("https://www.obfuz.com/docs/help/faq"); - - [MenuItem("Obfuz/Documents/Common Errors")] - public static void OpenCommonErrors() => Application.OpenURL("https://www.obfuz.com/docs/help/commonerrors"); - - [MenuItem("Obfuz/Documents/Bug Report")] - public static void OpenBugReport() => Application.OpenURL("https://www.obfuz.com/docs/help/issue"); - - [MenuItem("Obfuz/Documents/GitHub")] - public static void OpenGitHub() => Application.OpenURL("https://github.com/focus-creative-games/obfuz"); - - [MenuItem("Obfuz/Documents/About")] - public static void OpenAbout() => Application.OpenURL("https://www.obfuz.com/docs/intro"); - } - -} \ No newline at end of file diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Unity/ObfuzMenu.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Unity/ObfuzMenu.cs.meta deleted file mode 100644 index ae1f6f80..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Unity/ObfuzMenu.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ce8d804a6c4640e45a3d5c98b30c0c31 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Unity/UnityProjectManagedAssemblyResolver.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Unity/UnityProjectManagedAssemblyResolver.cs deleted file mode 100644 index 9d838aee..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Unity/UnityProjectManagedAssemblyResolver.cs +++ /dev/null @@ -1,57 +0,0 @@ -using Obfuz.Utils; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using UnityEditor; -using UnityEngine; - -namespace Obfuz.Unity -{ - public class UnityProjectManagedAssemblyResolver : AssemblyResolverBase - { - private readonly Dictionary _managedAssemblyNameToPaths = new Dictionary(); - - public UnityProjectManagedAssemblyResolver(BuildTarget target) - { - string[] dllGuids = AssetDatabase.FindAssets("t:DefaultAsset"); - var dllPaths = dllGuids.Select(guid => AssetDatabase.GUIDToAssetPath(guid)) - .Where(f => f.EndsWith(".dll")) - .Where(dllPath => - { - PluginImporter importer = AssetImporter.GetAtPath(dllPath) as PluginImporter; - if (importer == null || importer.isNativePlugin) - { - return false; - } - if (!importer.GetCompatibleWithAnyPlatform() && !importer.GetCompatibleWithPlatform(target)) - { - return false; - } - return true; - }).ToArray(); - - foreach (string dllPath in dllPaths) - { - Debug.Log($"UnityProjectManagedAssemblyResolver find managed dll:{dllPath}"); - string assName = Path.GetFileNameWithoutExtension(dllPath); - if (_managedAssemblyNameToPaths.TryGetValue(assName, out var existAssPath)) - { - Debug.LogWarning($"UnityProjectManagedAssemblyResolver find duplicate assembly1:{existAssPath} assembly2:{dllPath}"); - } - else - { - _managedAssemblyNameToPaths.Add(Path.GetFileNameWithoutExtension(dllPath), dllPath); - } - } - } - - public override string ResolveAssembly(string assemblyName) - { - if (_managedAssemblyNameToPaths.TryGetValue(assemblyName, out string assemblyPath)) - { - return assemblyPath; - } - return null; - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Unity/UnityProjectManagedAssemblyResolver.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Unity/UnityProjectManagedAssemblyResolver.cs.meta deleted file mode 100644 index ac1c4aa1..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Unity/UnityProjectManagedAssemblyResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 20abbffaf6419c448883ffaa21949753 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils.meta deleted file mode 100644 index 8a3e253d..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: ade28aaad1116b143a4027071e71010f -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/AssemblyCache.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/AssemblyCache.cs deleted file mode 100644 index 0c3eeaa4..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/AssemblyCache.cs +++ /dev/null @@ -1,88 +0,0 @@ -using dnlib.DotNet; -using System.Collections.Generic; -using System.IO; - -namespace Obfuz.Utils -{ - - public class AssemblyCache - { - private readonly IAssemblyResolver _assemblyPathResolver; - private readonly ModuleContext _modCtx; - private readonly AssemblyResolver _asmResolver; - private bool _enableTypeDefCache; - - - public ModuleContext ModCtx => _modCtx; - - public Dictionary LoadedModules { get; } = new Dictionary(); - - public AssemblyCache(IAssemblyResolver assemblyResolver) - { - _enableTypeDefCache = true; - _assemblyPathResolver = assemblyResolver; - _modCtx = ModuleDef.CreateModuleContext(); - _asmResolver = (AssemblyResolver)_modCtx.AssemblyResolver; - _asmResolver.EnableTypeDefCache = _enableTypeDefCache; - _asmResolver.UseGAC = false; - } - - public bool EnableTypeDefCache - { - get => _enableTypeDefCache; - set - { - _enableTypeDefCache = value; - _asmResolver.EnableTypeDefCache = value; - foreach (var mod in LoadedModules.Values) - { - mod.EnableTypeDefFindCache = value; - } - } - } - - - public ModuleDefMD TryLoadModule(string moduleName) - { - string dllPath = _assemblyPathResolver.ResolveAssembly(moduleName); - if (string.IsNullOrEmpty(dllPath)) - { - return null; - } - return LoadModule(moduleName); - } - - public ModuleDefMD LoadModule(string moduleName) - { - // Debug.Log($"load module:{moduleName}"); - if (LoadedModules.TryGetValue(moduleName, out var mod)) - { - return mod; - } - string assemblyPath = _assemblyPathResolver.ResolveAssembly(moduleName); - if (string.IsNullOrEmpty(assemblyPath)) - { - throw new FileNotFoundException($"Assembly {moduleName} not found"); - } - mod = DoLoadModule(assemblyPath); - LoadedModules.Add(moduleName, mod); - - - foreach (var refAsm in mod.GetAssemblyRefs()) - { - LoadModule(refAsm.Name); - } - - return mod; - } - - private ModuleDefMD DoLoadModule(string dllPath) - { - //Debug.Log($"do load module:{dllPath}"); - ModuleDefMD mod = ModuleDefMD.Load(File.ReadAllBytes(dllPath), _modCtx); - mod.EnableTypeDefFindCache = _enableTypeDefCache; - _asmResolver.AddToCache(mod); - return mod; - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/AssemblyCache.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/AssemblyCache.cs.meta deleted file mode 100644 index bb922298..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/AssemblyCache.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ce64ad992f9807d4994d4f41a54b170b -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/AssemblyResolverBase.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/AssemblyResolverBase.cs deleted file mode 100644 index 73aa7e6a..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/AssemblyResolverBase.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace Obfuz.Utils -{ - public abstract class AssemblyResolverBase : IAssemblyResolver - { - public abstract string ResolveAssembly(string assemblyName); - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/AssemblyResolverBase.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/AssemblyResolverBase.cs.meta deleted file mode 100644 index 4a7f4a0e..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/AssemblyResolverBase.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: c7332848ca18498459e6248d06bc5b31 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/AssertUtil.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/AssertUtil.cs deleted file mode 100644 index 112899a7..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/AssertUtil.cs +++ /dev/null @@ -1,28 +0,0 @@ -using UnityEngine.Assertions; - -namespace Obfuz.Utils -{ - public static class AssertUtil - { - private static bool IsArrayEqual(byte[] a, byte[] b) - { - if (a.Length != b.Length) - { - return false; - } - for (int i = 0; i < a.Length; i++) - { - if (a[i] != b[i]) - { - return false; - } - } - return true; - } - - public static void AreArrayEqual(byte[] expected, byte[] actual, string message) - { - Assert.IsTrue(IsArrayEqual(expected, actual), message); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/AssertUtil.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/AssertUtil.cs.meta deleted file mode 100644 index e0097382..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/AssertUtil.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: aba0c82c527b6494ab5c9c67c25656ed -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/BurstCompileComputeCache.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/BurstCompileComputeCache.cs deleted file mode 100644 index f2f22884..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/BurstCompileComputeCache.cs +++ /dev/null @@ -1,90 +0,0 @@ -using dnlib.DotNet; -using System.Collections.Generic; - -namespace Obfuz.Utils -{ - public class BurstCompileComputeCache - { - private readonly List _modulesToObfuscate; - private readonly List _allObfuscationRelativeModules; - - private readonly HashSet _burstCompileMethods = new HashSet(); - private readonly HashSet _burstCompileRelativeMethods = new HashSet(); - public BurstCompileComputeCache(List modulesToObfuscate, List allObfuscationRelativeModules) - { - _modulesToObfuscate = modulesToObfuscate; - _allObfuscationRelativeModules = allObfuscationRelativeModules; - Build(); - } - - - private void BuildBurstCompileMethods() - { - foreach (var module in _allObfuscationRelativeModules) - { - foreach (var type in module.GetTypes()) - { - bool hasBurstCompileAttribute = MetaUtil.HasBurstCompileAttribute(type); - foreach (var method in type.Methods) - { - if (hasBurstCompileAttribute || MetaUtil.HasBurstCompileAttribute(method)) - { - _burstCompileMethods.Add(method); - } - } - } - } - } - - private void CollectBurstCompileReferencedMethods() - { - var modulesToObfuscateSet = new HashSet(_modulesToObfuscate); - var allObfuscationRelativeModulesSet = new HashSet(_allObfuscationRelativeModules); - - var pendingWalking = new Queue(_burstCompileMethods); - var visitedMethods = new HashSet(); - while (pendingWalking.Count > 0) - { - var method = pendingWalking.Dequeue(); - - if (!visitedMethods.Add(method)) - { - continue; // Skip already visited methods - } - if (modulesToObfuscateSet.Contains(method.Module)) - { - _burstCompileRelativeMethods.Add(method); - } - if (!method.HasBody) - { - continue; - } - // Check for calls to other methods - foreach (var instruction in method.Body.Instructions) - { - if (instruction.OpCode.Code == dnlib.DotNet.Emit.Code.Call || - instruction.OpCode.Code == dnlib.DotNet.Emit.Code.Callvirt) - { - MethodDef calledMethod = ((IMethod)instruction.Operand).ResolveMethodDef(); - if (calledMethod == null || !allObfuscationRelativeModulesSet.Contains(calledMethod.Module) || visitedMethods.Contains(calledMethod)) - { - continue; // Skip if the method could not be resolved - } - pendingWalking.Enqueue(calledMethod); - } - } - } - } - - private void Build() - { - BuildBurstCompileMethods(); - CollectBurstCompileReferencedMethods(); - } - - public bool IsBurstCompileMethodOrReferencedByBurstCompileMethod(MethodDef method) - { - return _burstCompileRelativeMethods.Contains(method); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/BurstCompileComputeCache.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/BurstCompileComputeCache.cs.meta deleted file mode 100644 index 07dd6517..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/BurstCompileComputeCache.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 37efeee0ad0b5c34e84bd1b7b401672a -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/CachedDictionary.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/CachedDictionary.cs deleted file mode 100644 index 1e0f1d02..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/CachedDictionary.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace Obfuz.Utils -{ - public class CachedDictionary - { - private readonly Func _valueFactory; - private readonly Dictionary _cache; - - public CachedDictionary(Func valueFactory) - { - _cache = new Dictionary(); - _valueFactory = valueFactory; - } - - public CachedDictionary(IEqualityComparer equalityComparer, Func valueFactory) - { - _cache = new Dictionary(equalityComparer); - _valueFactory = valueFactory; - } - - public V GetValue(K key) - { - if (!_cache.TryGetValue(key, out var value)) - { - value = _valueFactory(key); - _cache[key] = value; - } - return value; - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/CachedDictionary.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/CachedDictionary.cs.meta deleted file mode 100644 index 115dde01..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/CachedDictionary.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 66494da674feeb741b889590cb663d4e -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/CollectionExtensions.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/CollectionExtensions.cs deleted file mode 100644 index 6753fe5d..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/CollectionExtensions.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System.Collections.Generic; - -namespace Obfuz.Utils -{ - public static class CollectionExtensions - { - public static void AddRange(this HashSet values, IEnumerable newValues) - { - foreach (var value in newValues) - { - values.Add(value); - } - } - - public static V GetValueOrDefault(this Dictionary dic, K key) - { - return dic.TryGetValue(key, out V v) ? v : default(V); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/CollectionExtensions.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/CollectionExtensions.cs.meta deleted file mode 100644 index ba4aa2ac..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/CollectionExtensions.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 58fc4438f86bc174aba662f1d7058f45 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/CombinedAssemblyResolver.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/CombinedAssemblyResolver.cs deleted file mode 100644 index fd1c9443..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/CombinedAssemblyResolver.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System.Collections.Generic; -using System.Linq; - -namespace Obfuz.Utils -{ - public class CombinedAssemblyResolver : AssemblyResolverBase - { - private readonly List _resolvers; - - public CombinedAssemblyResolver(params IAssemblyResolver[] resolvers) - { - _resolvers = resolvers.ToList(); - } - - public override string ResolveAssembly(string assemblyName) - { - foreach (var resolver in _resolvers) - { - var assemblyPath = resolver.ResolveAssembly(assemblyName); - if (assemblyPath != null) - { - return assemblyPath; - } - } - return null; - } - - public void InsertFirst(IAssemblyResolver resolver) - { - _resolvers.Insert(0, resolver); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/CombinedAssemblyResolver.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/CombinedAssemblyResolver.cs.meta deleted file mode 100644 index dd9890d7..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/CombinedAssemblyResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 1576f3534f31509458104d2a7ebcd9cc -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/ConfigUtil.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/ConfigUtil.cs deleted file mode 100644 index bc2c5492..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/ConfigUtil.cs +++ /dev/null @@ -1,78 +0,0 @@ -using Obfuz.Settings; -using System; - -namespace Obfuz.Utils -{ - public static class ConfigUtil - { - - public static bool ParseBool(string str) - { - switch (str.ToLowerInvariant()) - { - case "1": - case "true": return true; - case "0": - case "false": return false; - default: throw new Exception($"Invalid bool value {str}"); - } - } - - public static bool? ParseNullableBool(string str) - { - if (string.IsNullOrEmpty(str)) - { - return null; - } - switch (str.ToLowerInvariant()) - { - case "1": - case "true": return true; - case "0": - case "false": return false; - default: throw new Exception($"Invalid bool value {str}"); - } - } - - public static int? ParseNullableInt(string str) - { - if (string.IsNullOrEmpty(str)) - { - return null; - } - return int.Parse(str); - } - - public static long? ParseNullableLong(string str) - { - if (string.IsNullOrEmpty(str)) - { - return null; - } - return long.Parse(str); - } - - public static float? ParseNullableFloat(string str) - { - if (string.IsNullOrEmpty(str)) - { - return null; - } - return float.Parse(str); - } - - public static double? ParseNullableDouble(string str) - { - if (string.IsNullOrEmpty(str)) - { - return null; - } - return double.Parse(str); - } - - public static ObfuscationLevel ParseObfuscationLevel(string str) - { - return (ObfuscationLevel)Enum.Parse(typeof(ObfuscationLevel), str); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/ConfigUtil.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/ConfigUtil.cs.meta deleted file mode 100644 index bba160a6..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/ConfigUtil.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ff35a8e07f37adf4483eaf5cc5da5c78 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/ConstObfusUtil.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/ConstObfusUtil.cs deleted file mode 100644 index 67c64d05..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/ConstObfusUtil.cs +++ /dev/null @@ -1,177 +0,0 @@ -using dnlib.DotNet; -using dnlib.DotNet.Emit; -using Obfuz.Data; -using System.Collections.Generic; - -namespace Obfuz.Utils -{ - internal static class ConstObfusUtil - { - public static void LoadConstInt(int a, IRandom random, float constProbability, ConstFieldAllocator constFieldAllocator, List outputInsts) - { - Instruction inst; - if (random.NextInPercentage(constProbability)) - { - inst = Instruction.Create(OpCodes.Ldc_I4, a); - } - else - { - FieldDef field = constFieldAllocator.Allocate(a); - inst = Instruction.Create(OpCodes.Ldsfld, field); - } - outputInsts.Add(inst); - } - - public static void LoadConstLong(long a, IRandom random, float constProbability, ConstFieldAllocator constFieldAllocator, List outputInsts) - { - Instruction inst; - if (random.NextInPercentage(constProbability)) - { - inst = Instruction.Create(OpCodes.Ldc_I8, a); - } - else - { - FieldDef field = constFieldAllocator.Allocate(a); - inst = Instruction.Create(OpCodes.Ldsfld, field); - } - outputInsts.Add(inst); - } - - public static void LoadConstFloat(float a, IRandom random, float constProbability, ConstFieldAllocator constFieldAllocator, List outputInsts) - { - Instruction inst; - if (random.NextInPercentage(constProbability)) - { - inst = Instruction.Create(OpCodes.Ldc_R4, a); - } - else - { - FieldDef field = constFieldAllocator.Allocate(a); - inst = Instruction.Create(OpCodes.Ldsfld, field); - } - outputInsts.Add(inst); - } - - public static void LoadConstDouble(double a, IRandom random, float constProbability, ConstFieldAllocator constFieldAllocator, List outputInsts) - { - Instruction inst; - if (random.NextInPercentage(constProbability)) - { - inst = Instruction.Create(OpCodes.Ldc_R8, a); - } - else - { - FieldDef field = constFieldAllocator.Allocate(a); - inst = Instruction.Create(OpCodes.Ldsfld, field); - } - outputInsts.Add(inst); - } - - - public static void LoadConstTwoInt(int a, int b, IRandom random, float constProbability, ConstFieldAllocator constFieldAllocator, List outputInsts) - { - if (random.NextInPercentage(constProbability)) - { - outputInsts.Add(Instruction.Create(OpCodes.Ldc_I4, a)); - - // at most one ldc instruction - FieldDef field = constFieldAllocator.Allocate(b); - outputInsts.Add(Instruction.Create(OpCodes.Ldsfld, field)); - } - else - { - FieldDef field = constFieldAllocator.Allocate(a); - outputInsts.Add(Instruction.Create(OpCodes.Ldsfld, field)); - - if (random.NextInPercentage(constProbability)) - { - // at most one ldc instruction - outputInsts.Add(Instruction.Create(OpCodes.Ldc_I4, b)); - } - else - { - field = constFieldAllocator.Allocate(b); - outputInsts.Add(Instruction.Create(OpCodes.Ldsfld, field)); - } - } - } - - public static void LoadConstTwoLong(long a, long b, IRandom random, float constProbability, ConstFieldAllocator constFieldAllocator, List outputInsts) - { - if (random.NextInPercentage(constProbability)) - { - outputInsts.Add(Instruction.Create(OpCodes.Ldc_I8, a)); - // at most one ldc instruction - FieldDef field = constFieldAllocator.Allocate(b); - outputInsts.Add(Instruction.Create(OpCodes.Ldsfld, field)); - } - else - { - FieldDef field = constFieldAllocator.Allocate(a); - outputInsts.Add(Instruction.Create(OpCodes.Ldsfld, field)); - if (random.NextInPercentage(constProbability)) - { - // at most one ldc instruction - outputInsts.Add(Instruction.Create(OpCodes.Ldc_I8, b)); - } - else - { - field = constFieldAllocator.Allocate(b); - outputInsts.Add(Instruction.Create(OpCodes.Ldsfld, field)); - } - } - } - - public static void LoadConstTwoFloat(float a, float b, IRandom random, float constProbability, ConstFieldAllocator constFieldAllocator, List outputInsts) - { - if (random.NextInPercentage(constProbability)) - { - outputInsts.Add(Instruction.Create(OpCodes.Ldc_R4, a)); - // at most one ldc instruction - FieldDef field = constFieldAllocator.Allocate(b); - outputInsts.Add(Instruction.Create(OpCodes.Ldsfld, field)); - } - else - { - FieldDef field = constFieldAllocator.Allocate(a); - outputInsts.Add(Instruction.Create(OpCodes.Ldsfld, field)); - if (random.NextInPercentage(constProbability)) - { - // at most one ldc instruction - outputInsts.Add(Instruction.Create(OpCodes.Ldc_R4, b)); - } - else - { - field = constFieldAllocator.Allocate(b); - outputInsts.Add(Instruction.Create(OpCodes.Ldsfld, field)); - } - } - } - - public static void LoadConstTwoDouble(double a, double b, IRandom random, float constProbability, ConstFieldAllocator constFieldAllocator, List outputInsts) - { - if (random.NextInPercentage(constProbability)) - { - outputInsts.Add(Instruction.Create(OpCodes.Ldc_R8, a)); - // at most one ldc instruction - FieldDef field = constFieldAllocator.Allocate(b); - outputInsts.Add(Instruction.Create(OpCodes.Ldsfld, field)); - } - else - { - FieldDef field = constFieldAllocator.Allocate(a); - outputInsts.Add(Instruction.Create(OpCodes.Ldsfld, field)); - if (random.NextInPercentage(constProbability)) - { - // at most one ldc instruction - outputInsts.Add(Instruction.Create(OpCodes.Ldc_R8, b)); - } - else - { - field = constFieldAllocator.Allocate(b); - outputInsts.Add(Instruction.Create(OpCodes.Ldsfld, field)); - } - } - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/ConstObfusUtil.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/ConstObfusUtil.cs.meta deleted file mode 100644 index 1646815d..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/ConstObfusUtil.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 4330e358b953be54c9f1ada2ff34156d -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/DisableTypeDefFindCacheScope.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/DisableTypeDefFindCacheScope.cs deleted file mode 100644 index 30ccef2d..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/DisableTypeDefFindCacheScope.cs +++ /dev/null @@ -1,21 +0,0 @@ -using dnlib.DotNet; -using System; - -namespace Obfuz.Utils -{ - public class DisableTypeDefFindCacheScope : IDisposable - { - private readonly ModuleDef _module; - - public DisableTypeDefFindCacheScope(ModuleDef module) - { - _module = module; - _module.EnableTypeDefFindCache = false; - } - - public void Dispose() - { - _module.EnableTypeDefFindCache = true; - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/DisableTypeDefFindCacheScope.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/DisableTypeDefFindCacheScope.cs.meta deleted file mode 100644 index 349b119e..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/DisableTypeDefFindCacheScope.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 89640cb831c78f8429c861fb49bae0e7 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/EncryptionUtil.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/EncryptionUtil.cs deleted file mode 100644 index d2f956ff..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/EncryptionUtil.cs +++ /dev/null @@ -1,45 +0,0 @@ -using System; -using UnityEngine; - -namespace Obfuz.Utils -{ - public static class EncryptionUtil - { - public static int GetBitCount(int value) - { - int count = 0; - while (value > 0) - { - count++; - value >>= 1; - } - return count; - } - - public static int GenerateEncryptionOpCodes(IRandom random, IEncryptor encryptor, int encryptionLevel) - { - if (encryptionLevel <= 0 || encryptionLevel > 4) - { - throw new ArgumentException($"Invalid encryption level: {encryptionLevel}, should be in range [1,4]"); - } - int vmOpCodeCount = encryptor.OpCodeCount; - long ops = 0; - for (int i = 0; i < encryptionLevel; i++) - { - long newOps = ops * vmOpCodeCount; - // don't use 0 - int op = random.NextInt(1, vmOpCodeCount); - newOps |= (uint)op; - if (newOps > uint.MaxValue) - { - Debug.LogWarning($"OpCode overflow. encryptionLevel:{encryptionLevel}, vmOpCodeCount:{vmOpCodeCount}"); - } - else - { - ops = newOps; - } - } - return (int)ops; - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/EncryptionUtil.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/EncryptionUtil.cs.meta deleted file mode 100644 index 5c82b2ba..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/EncryptionUtil.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 0b8fc4c92fa6f0b40a9734b347cd265c -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/FileUtil.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/FileUtil.cs deleted file mode 100644 index f7c38ee4..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/FileUtil.cs +++ /dev/null @@ -1,96 +0,0 @@ -using System; -using System.IO; -using System.Threading; - -namespace Obfuz.Utils -{ - public static class FileUtil - { - public static void CreateParentDir(string path) - { - Directory.CreateDirectory(Path.GetDirectoryName(path)); - } - - 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); - } - - private static void CopyWithCheckLongFile(string srcFile, string dstFile) - { - var maxPathLength = 255; -#if UNITY_EDITOR_OSX - maxPathLength = 1024; -#endif - if (srcFile.Length > maxPathLength) - { - UnityEngine.Debug.LogError($"srcFile:{srcFile} path is too long. skip copy!"); - return; - } - if (dstFile.Length > maxPathLength) - { - UnityEngine.Debug.LogError($"dstFile:{dstFile} path is too long. skip copy!"); - return; - } - File.Copy(srcFile, dstFile); - } - - public static void CopyDir(string src, string dst, bool log = false) - { - if (log) - { - UnityEngine.Debug.Log($"copyDir {src} => {dst}"); - } - RemoveDir(dst); - Directory.CreateDirectory(dst); - foreach (var file in Directory.GetFiles(src)) - { - CopyWithCheckLongFile(file, $"{dst}/{Path.GetFileName(file)}"); - } - foreach (var subDir in Directory.GetDirectories(src)) - { - CopyDir(subDir, $"{dst}/{Path.GetFileName(subDir)}"); - } - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/FileUtil.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/FileUtil.cs.meta deleted file mode 100644 index c8523ce5..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/FileUtil.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: b6385af8bd061b142a3d7dcf41ab7e79 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/GenericArgumentContext.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/GenericArgumentContext.cs deleted file mode 100644 index 52328adb..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/GenericArgumentContext.cs +++ /dev/null @@ -1,111 +0,0 @@ -using dnlib.DotNet; -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Obfuz.Utils -{ - public sealed class GenericArgumentContext - { - public readonly List typeArgsStack; - public readonly List methodArgsStack; - - public GenericArgumentContext(IList typeArgsStack, IList methodArgsStack) - { - this.typeArgsStack = typeArgsStack?.ToList(); - this.methodArgsStack = methodArgsStack?.ToList(); - } - - public TypeSig Resolve(TypeSig typeSig) - { - if (!typeSig.ContainsGenericParameter) - { - 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)); - - 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: - { - GenericVar genericVar = (GenericVar)typeSig; - var newSig = Resolve(typeArgsStack, genericVar.Number); - if (newSig == null) - { - throw new Exception(); - } - return newSig; - } - - case ElementType.MVar: - { - 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()); - } - - case ElementType.FnPtr: - { - var fptr = (FnPtrSig)typeSig; - var cs = fptr.Signature; - CallingConventionSig ccs; - switch (cs) - { - case MethodSig ms: - { - ccs = new MethodSig(ms.GetCallingConvention(), ms.GenParamCount, Resolve(ms.RetType), ms.Params.Select(p => Resolve(p)).ToList()); - break; - } - case PropertySig ps: - { - ccs = new PropertySig(ps.HasThis, Resolve(ps.RetType)); - break; - } - case GenericInstMethodSig gims: - { - ccs = new GenericInstMethodSig(gims.GenericArguments.Select(ga => Resolve(ga)).ToArray()); - break; - } - default: throw new NotSupportedException(cs.ToString()); - } - return new FnPtrSig(ccs); - } - - 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) - { - if (args == null) - { - throw new ArgumentNullException(nameof(args)); - } - return args[(int)number]; - } - } - -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/GenericArgumentContext.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/GenericArgumentContext.cs.meta deleted file mode 100644 index fd13834f..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/GenericArgumentContext.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: cdefb4e144f6a98418c7bd02eab51039 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/HashUtil.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/HashUtil.cs deleted file mode 100644 index 3e128292..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/HashUtil.cs +++ /dev/null @@ -1,67 +0,0 @@ -using dnlib.DotNet; -using System.Collections; -using System.Collections.Generic; - -namespace Obfuz.Utils -{ - public static class HashUtil - { - public static int CombineHash(int hash1, int hash2) - { - return hash1 * 1566083941 + hash2; - } - - public static int ComputeHash(TypeSig sig) - { - return TypeEqualityComparer.Instance.GetHashCode(sig); - } - - public static int ComputeHash(IList sigs) - { - int hash = 135781321; - TypeEqualityComparer tc = TypeEqualityComparer.Instance; - foreach (var sig in sigs) - { - hash = hash * 1566083941 + tc.GetHashCode(sig); - } - return hash; - } - - public static unsafe int ComputeHash(string s) - { - fixed (char* ptr = s) - { - int num = 352654597; - int num2 = num; - int* ptr2 = (int*)ptr; - int num3; - for (num3 = s.Length; num3 > 2; num3 -= 4) - { - num = ((num << 5) + num + (num >> 27)) ^ *ptr2; - num2 = ((num2 << 5) + num2 + (num2 >> 27)) ^ ptr2[1]; - ptr2 += 2; - } - - if (num3 > 0) - { - num = ((num << 5) + num + (num >> 27)) ^ *ptr2; - } - - return num + num2 * 1566083941; - } - } - - public static int ComputePrimitiveOrStringOrBytesHashCode(object obj) - { - if (obj is byte[] bytes) - { - return StructuralComparisons.StructuralEqualityComparer.GetHashCode(bytes); - } - if (obj is string s) - { - return HashUtil.ComputeHash(s); - } - return obj.GetHashCode(); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/HashUtil.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/HashUtil.cs.meta deleted file mode 100644 index d89f8f0d..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/HashUtil.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 0b4cd05dd413bfa4ebb9fcbe591b1486 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/IAssemblyResolver.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/IAssemblyResolver.cs deleted file mode 100644 index 9e048793..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/IAssemblyResolver.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace Obfuz.Utils -{ - public interface IAssemblyResolver - { - string ResolveAssembly(string assemblyName); - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/IAssemblyResolver.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/IAssemblyResolver.cs.meta deleted file mode 100644 index 917a107e..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/IAssemblyResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: e0254d9726a78e146af99a61641b47d3 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/IRandom.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/IRandom.cs deleted file mode 100644 index e37ca145..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/IRandom.cs +++ /dev/null @@ -1,17 +0,0 @@ -namespace Obfuz.Utils -{ - public interface IRandom - { - int NextInt(int min, int max); - - int NextInt(int max); - - int NextInt(); - - long NextLong(); - - float NextFloat(); - - bool NextInPercentage(float percentage); - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/IRandom.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/IRandom.cs.meta deleted file mode 100644 index 086b0737..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/IRandom.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 959c821ff51056c4ebca3f89aeeff03d -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/KeyGenerator.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/KeyGenerator.cs deleted file mode 100644 index ea5a6816..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/KeyGenerator.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System; -using System.Security.Cryptography; -using System.Text; - -namespace Obfuz.Utils -{ - public static class KeyGenerator - { - public static byte[] GenerateKey(string initialString, int keyLength) - { - byte[] initialBytes = Encoding.UTF8.GetBytes(initialString); - using (var sha512 = SHA512.Create()) - { - byte[] hash = sha512.ComputeHash(initialBytes); - byte[] key = new byte[keyLength]; - int bytesCopied = 0; - while (bytesCopied < key.Length) - { - if (bytesCopied > 0) - { - // 再次哈希之前的哈希值以生成更多数据 - hash = sha512.ComputeHash(hash); - } - int bytesToCopy = Math.Min(hash.Length, key.Length - bytesCopied); - Buffer.BlockCopy(hash, 0, key, bytesCopied, bytesToCopy); - bytesCopied += bytesToCopy; - } - return key; - } - } - - public static int[] ConvertToIntKey(byte[] key) - { - return EncryptorBase.ConvertToIntKey(key); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/KeyGenerator.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/KeyGenerator.cs.meta deleted file mode 100644 index 7d11ff06..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/KeyGenerator.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 5441ac16fd88a8848af862be23bd2ecb -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/MathUtil.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/MathUtil.cs deleted file mode 100644 index dad6d2ef..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/MathUtil.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System; - -namespace Obfuz.Utils -{ - - internal static class MathUtil - { - //public static int ModInverseOdd32(int sa) - //{ - // uint a = (uint)sa; - // if (a % 2 == 0) - // throw new ArgumentException("Input must be an odd number.", nameof(a)); - - // uint x = 1; // 初始解:x₀ = 1 (mod 2) - // for (int i = 0; i < 5; i++) // 迭代5次(2^1 → 2^32) - // { - // int shift = 2 << i; // 当前模数为 2^(2^(i+1)) - // ulong mod = 1UL << shift; // 使用 ulong 避免溢出 - // ulong ax = (ulong)a * x; // 计算 a*x(64位避免截断) - // ulong term = (2 - ax) % mod; - // x = (uint)((x * term) % mod); // 更新 x,结果截断为 uint - // } - // return (int)x; // 最终解为 x₅ mod 2^32 - //} - - public static int ModInverse32(int sa) - { - uint x = (uint)sa; - if ((x & 1) == 0) - throw new ArgumentException("x must be odd (coprime with 2^32)"); - - uint inv = x; - inv = inv * (2 - x * inv); // 1 - inv = inv * (2 - x * inv); // 2 - inv = inv * (2 - x * inv); // 3 - inv = inv * (2 - x * inv); // 4 - inv = inv * (2 - x * inv); // 5 - return (int)inv; - } - - public static long ModInverse64(long sx) - { - ulong x = (ulong)sx; - if ((x & 1) == 0) - throw new ArgumentException("x must be odd (coprime with 2^64)"); - - ulong inv = x; - inv *= 2 - x * inv; // 1 - inv *= 2 - x * inv; // 2 - inv *= 2 - x * inv; // 3 - inv *= 2 - x * inv; // 4 - inv *= 2 - x * inv; // 5 - inv *= 2 - x * inv; // 6 - - return (long)inv; - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/MathUtil.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/MathUtil.cs.meta deleted file mode 100644 index 4dc5598c..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/MathUtil.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 8d5962b5e88adac40a2b1c65a8d304bc -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/MetaUtil.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/MetaUtil.cs deleted file mode 100644 index ac48fcac..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/MetaUtil.cs +++ /dev/null @@ -1,922 +0,0 @@ -using dnlib.DotNet; -using Obfuz.Editor; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using UnityEngine.Assertions; - -namespace Obfuz.Utils -{ - - public static class MetaUtil - { - public static string GetModuleNameWithoutExt(string moduleName) - { - return Path.GetFileNameWithoutExtension(moduleName); - } - - public static (string, string) SplitNamespaceAndName(string fullName) - { - int index = fullName.LastIndexOf('/'); - if (index == -1) - { - int index2 = fullName.IndexOf('.'); - return index2 >= 0 ? (fullName.Substring(0, index2), fullName.Substring(index2 + 1)) : ("", fullName); - } - return ("", fullName.Substring(index + 1)); - } - - public static bool IsVoidType(TypeSig type) - { - return type.RemovePinnedAndModifiers().ElementType == ElementType.Void; - } - - public static TypeDef GetBaseTypeDef(TypeDef type) - { - ITypeDefOrRef baseType = type.BaseType; - if (baseType == null) - { - return null; - } - TypeDef baseTypeDef = baseType.ResolveTypeDef(); - if (baseTypeDef != null) - { - return baseTypeDef; - } - if (baseType is TypeSpec baseTypeSpec) - { - GenericInstSig genericIns = baseTypeSpec.TypeSig.ToGenericInstSig(); - return genericIns.GenericType.TypeDefOrRef.ResolveTypeDefThrow(); - } - else - { - throw new Exception($"GetBaseTypeDef: {type} fail"); - } - } - - public static TypeDef GetTypeDefOrGenericTypeBaseThrowException(ITypeDefOrRef type) - { - if (type.IsTypeDef) - { - return (TypeDef)type; - } - if (type.IsTypeRef) - { - return type.ResolveTypeDefThrow(); - } - if (type.IsTypeSpec) - { - GenericInstSig gis = type.TryGetGenericInstSig(); - return gis.GenericType.ToTypeDefOrRef().ResolveTypeDefThrow(); - } - throw new NotSupportedException($"{type}"); - } - - public static TypeDef GetTypeDefOrGenericTypeBaseOrNull(ITypeDefOrRef type) - { - if (type.IsTypeDef) - { - return (TypeDef)type; - } - if (type.IsTypeRef) - { - return type.ResolveTypeDefThrow(); - } - if (type.IsTypeSpec) - { - GenericInstSig gis = type.TryGetGenericInstSig(); - if (gis == null) - { - return null; - } - return gis.GenericType.ToTypeDefOrRef().ResolveTypeDefThrow(); - } - return null; - } - - public static TypeDef GetMemberRefTypeDefParentOrNull(IMemberRefParent parent) - { - if (parent is TypeDef typeDef) - { - return typeDef; - } - if (parent is TypeRef typeRef) - { - return typeRef.ResolveTypeDefThrow(); - } - if (parent is TypeSpec typeSpec) - { - GenericInstSig gis = typeSpec.TryGetGenericInstSig(); - if (gis == null) - { - return null; - } - return gis.GenericType.TypeDefOrRef.ResolveTypeDefThrow(); - } - return null; - } - - public static bool IsInheritFromDOTSTypes(TypeDef typeDef) - { - TypeDef cur = typeDef; - while (true) - { - if (cur.Namespace.StartsWith("Unity.Entities") || - //cur.Namespace.StartsWith("Unity.Jobs") || - cur.Namespace.StartsWith("Unity.Burst")) - { - return true; - } - foreach (var interfaceType in cur.Interfaces) - { - TypeDef interfaceTypeDef = interfaceType.Interface.ResolveTypeDef(); - if (interfaceTypeDef != null && (interfaceTypeDef.Namespace.StartsWith("Unity.Entities") || - //interfaceTypeDef.Namespace.StartsWith("Unity.Jobs") || - interfaceTypeDef.Namespace.StartsWith("Unity.Burst"))) - { - return true; - } - } - - cur = GetBaseTypeDef(cur); - if (cur == null) - { - return false; - } - } - } - - public static bool IsInheritFromMonoBehaviour(TypeDef typeDef) - { - TypeDef cur = typeDef; - while (true) - { - cur = GetBaseTypeDef(cur); - if (cur == null) - { - return false; - } - if (cur.Name == "MonoBehaviour" && cur.Namespace == "UnityEngine" && cur.Module.Name == "UnityEngine.CoreModule.dll") - { - return true; - } - } - } - - - public static bool IsScriptType(TypeDef type) - { - for (TypeDef parentType = GetBaseTypeDef(type); parentType != null; parentType = GetBaseTypeDef(parentType)) - { - if ((parentType.Name == "MonoBehaviour" || parentType.Name == "ScriptableObject") - && parentType.Namespace == "UnityEngine" - && parentType.Module.Assembly.Name == "UnityEngine.CoreModule") - { - return true; - } - } - - return false; - } - - public static bool IsSerializableType(TypeDef type) - { - return type.IsSerializable; - } - - public static bool IsScriptOrSerializableType(TypeDef type) - { - return type.IsSerializable || IsScriptType(type); - } - - public static bool IsSerializableTypeSig(TypeSig typeSig) - { - typeSig = typeSig.RemovePinnedAndModifiers(); - switch (typeSig.ElementType) - { - case ElementType.Boolean: - case ElementType.Char: - case ElementType.I1: - case ElementType.U1: - case ElementType.I2: - case ElementType.U2: - case ElementType.I4: - case ElementType.U4: - case ElementType.I8: - case ElementType.U8: - case ElementType.R4: - case ElementType.R8: - case ElementType.String: - return true; - case ElementType.Class: - return IsScriptOrSerializableType(typeSig.ToTypeDefOrRef().ResolveTypeDefThrow()); - case ElementType.ValueType: - { - TypeDef typeDef = typeSig.ToTypeDefOrRef().ResolveTypeDefThrow(); - if (typeDef.IsEnum) - { - return true; - } - return typeDef.IsSerializable; - } - case ElementType.GenericInst: - { - GenericInstSig genericIns = typeSig.ToGenericInstSig(); - TypeDef typeDef = genericIns.GenericType.ToTypeDefOrRef().ResolveTypeDefThrow(); - return typeDef.FullName == "System.Collections.Generic.List`1" && IsSerializableTypeSig(genericIns.GenericArguments[0]); - } - case ElementType.SZArray: - { - return IsSerializableTypeSig(typeSig.RemovePinnedAndModifiers().Next); - } - default: - return false; - } - } - - public static bool IsSerializableField(FieldDef field) - { - if (field.IsStatic) - { - return false; - } - var fieldSig = field.FieldSig.Type; - if (field.IsPublic) - { - return IsSerializableTypeSig(fieldSig); - } - if (field.CustomAttributes.Any(c => c.TypeFullName == "UnityEngine.SerializeField")) - { - //UnityEngine.Debug.Assert(IsSerializableTypeSig(fieldSig)); - return true; - } - return false; - } - - public static bool MayRenameCustomDataType(ElementType type) - { - return type == ElementType.Class || type == ElementType.ValueType || type == ElementType.Object || type == ElementType.SZArray; - } - - public static TypeSig RetargetTypeRefInTypeSig(TypeSig type) - { - TypeSig next = type.Next; - TypeSig newNext = next != null ? RetargetTypeRefInTypeSig(next) : null; - if (type.IsModifier || type.IsPinned) - { - if (next == newNext) - { - return type; - } - if (type is CModReqdSig cmrs) - { - return new CModReqdSig(cmrs.Modifier, newNext); - } - if (type is CModOptSig cmos) - { - return new CModOptSig(cmos.Modifier, newNext); - } - if (type is PinnedSig ps) - { - return new PinnedSig(newNext); - } - throw new System.NotSupportedException(type.ToString()); - } - switch (type.ElementType) - { - case ElementType.Ptr: - { - if (next == newNext) - { - return type; - } - return new PtrSig(newNext); - } - case ElementType.ValueType: - case ElementType.Class: - { - var vts = type as ClassOrValueTypeSig; - if (vts.TypeDefOrRef is TypeDef typeDef) - { - return type; - } - TypeRef typeRef = (TypeRef)vts.TypeDefOrRef; - if (typeRef.DefinitionAssembly.IsCorLib()) - { - return type; - } - typeDef = typeRef.ResolveTypeDefThrow(); - return type.IsClassSig ? (TypeSig)new ClassSig(typeDef) : new ValueTypeSig(typeDef); - } - case ElementType.Array: - { - if (next == newNext) - { - return type; - } - return new ArraySig(newNext); - } - case ElementType.SZArray: - { - if (next == newNext) - { - return type; - } - return new SZArraySig(newNext); - } - case ElementType.GenericInst: - { - var gis = type as GenericInstSig; - ClassOrValueTypeSig genericType = gis.GenericType; - ClassOrValueTypeSig newGenericType = (ClassOrValueTypeSig)RetargetTypeRefInTypeSig(genericType); - bool anyChange = genericType != newGenericType; - var genericArgs = new List(); - foreach (var arg in gis.GenericArguments) - { - TypeSig newArg = RetargetTypeRefInTypeSig(arg); - anyChange |= newArg != arg; - genericArgs.Add(newArg); - } - if (!anyChange) - { - return type; - } - return new GenericInstSig(newGenericType, genericArgs); - } - case ElementType.FnPtr: - { - var fp = type as FnPtrSig; - MethodSig methodSig = fp.MethodSig; - TypeSig newReturnType = RetargetTypeRefInTypeSig(methodSig.RetType); - bool anyChange = newReturnType != methodSig.RetType; - var newArgs = new List(); - foreach (TypeSig arg in methodSig.Params) - { - TypeSig newArg = RetargetTypeRefInTypeSig(arg); - anyChange |= newArg != newReturnType; - } - if (!anyChange) - { - return type; - } - var newParamsAfterSentinel = new List(); - foreach (TypeSig arg in methodSig.ParamsAfterSentinel) - { - TypeSig newArg = RetargetTypeRefInTypeSig(arg); - anyChange |= newArg != arg; - newParamsAfterSentinel.Add(newArg); - } - - var newMethodSig = new MethodSig(methodSig.CallingConvention, methodSig.GenParamCount, newReturnType, newArgs, newParamsAfterSentinel); - return new FnPtrSig(newMethodSig); - } - case ElementType.ByRef: - { - if (next == newNext) - { - return type; - } - return new ByRefSig(newNext); - } - default: - { - return type; - } - } - } - - - public static object RetargetTypeRefInTypeSigOfValue(object oldValue) - { - if (oldValue == null) - { - return null; - } - string typeName = oldValue.GetType().FullName; - if (oldValue.GetType().IsPrimitive) - { - return oldValue; - } - if (oldValue is string || oldValue is UTF8String) - { - return oldValue; - } - if (oldValue is TypeSig typeSig) - { - return RetargetTypeRefInTypeSig(typeSig); - } - if (oldValue is CAArgument caValue) - { - TypeSig newType = RetargetTypeRefInTypeSig(caValue.Type); - object newValue = RetargetTypeRefInTypeSigOfValue(caValue.Value); - if (newType != caValue.Type || newValue != caValue.Value) - { - return new CAArgument(newType, newValue); - } - return oldValue; - } - if (oldValue is List oldArr) - { - bool anyChange = false; - var newArr = new List(); - foreach (CAArgument oldArg in oldArr) - { - if (TryRetargetTypeRefInArgument(oldArg, out var newArg)) - { - anyChange = true; - newArr.Add(newArg); - } - else - { - newArr.Add(oldArg); - } - } - return anyChange ? newArr : oldArr; - } - throw new NotSupportedException($"type:{oldValue.GetType()} value:{oldValue}"); - } - - - - public static bool TryRetargetTypeRefInArgument(CAArgument oldArg, out CAArgument newArg) - { - TypeSig newType = RetargetTypeRefInTypeSig(oldArg.Type); - object newValue = RetargetTypeRefInTypeSigOfValue(oldArg.Value); - if (newType != oldArg.Type || oldArg.Value != newValue) - { - newArg = new CAArgument(newType, newValue); - return true; - } - newArg = default; - return false; - } - - public static bool TryRetargetTypeRefInNamedArgument(CANamedArgument arg) - { - bool anyChange = false; - TypeSig newType = RetargetTypeRefInTypeSig(arg.Type); - if (newType != arg.Type) - { - anyChange = true; - arg.Type = newType; - } - if (TryRetargetTypeRefInArgument(arg.Argument, out var newArg)) - { - arg.Argument = newArg; - anyChange = true; - } - return anyChange; - } - - //public static bool ContainsContainsGenericParameter1(MethodDef method) - //{ - // Assert.IsTrue(!(method.DeclaringType.ContainsGenericParameter || method.MethodSig.ContainsGenericParameter)); - // return false; - //} - - public static bool ContainsContainsGenericParameter1(MethodSpec methodSpec) - { - if (methodSpec.GenericInstMethodSig.ContainsGenericParameter) - { - return true; - } - IMethodDefOrRef method = methodSpec.Method; - if (method.IsMethodDef) - { - return false;// ContainsContainsGenericParameter1((MethodDef)method); - } - if (method.IsMemberRef) - { - return ContainsContainsGenericParameter1((MemberRef)method); - } - throw new Exception($"unknown method: {method}"); - } - - public static bool ContainsContainsGenericParameter1(MemberRef memberRef) - { - IMemberRefParent parent = memberRef.Class; - if (parent is TypeSpec typeSpec) - { - return typeSpec.ContainsGenericParameter; - } - return false; - } - - public static bool ContainsContainsGenericParameter(IMethod method) - { - Assert.IsTrue(method.IsMethod); - if (method is MethodDef methodDef) - { - return false; - } - - if (method is MethodSpec methodSpec) - { - return ContainsContainsGenericParameter1(methodSpec); - } - if (method is MemberRef memberRef) - { - return ContainsContainsGenericParameter1(memberRef); - } - throw new Exception($"unknown method: {method}"); - } - - - - public static TypeSig Inflate(TypeSig sig, GenericArgumentContext ctx) - { - if (ctx == null || !sig.ContainsGenericParameter) - { - return sig; - } - return ctx.Resolve(sig); - } - - public static IList TryInflate(IList sig, GenericArgumentContext ctx) - { - if (sig == null || ctx == null) - { - return sig; - } - return sig.Select(s => Inflate(s, ctx)).ToList() ?? null; - } - - - public static MethodSig InflateMethodSig(MethodSig methodSig, GenericArgumentContext genericArgumentContext) - { - var newReturnType = Inflate(methodSig.RetType, genericArgumentContext); - var newParams = new List(); - foreach (var param in methodSig.Params) - { - newParams.Add(Inflate(param, genericArgumentContext)); - } - var newParamsAfterSentinel = new List(); - if (methodSig.ParamsAfterSentinel != null) - { - throw new NotSupportedException($"methodSig.ParamsAfterSentinel is not supported: {methodSig}"); - //foreach (var param in methodSig.ParamsAfterSentinel) - //{ - // newParamsAfterSentinel.Add(Inflate(param, genericArgumentContext)); - //} - } - return new MethodSig(methodSig.CallingConvention, methodSig.GenParamCount, newReturnType, newParams, null); - } - - public static IList GetGenericArguments(IMemberRefParent type) - { - if (type is TypeDef typeDef) - { - return null; - } - if (type is TypeRef typeRef) - { - return null; - } - if (type is TypeSpec typeSpec) - { - GenericInstSig genericInstSig = typeSpec.TypeSig.ToGenericInstSig(); - return genericInstSig?.GenericArguments; - } - throw new NotSupportedException($"type:{type}"); - } - - public static GenericArgumentContext GetInflatedMemberRefGenericArgument(IMemberRefParent type, GenericArgumentContext ctx) - { - if (type is TypeDef typeDef) - { - return null; - } - if (type is TypeRef typeRef) - { - return null; - } - if (type is TypeSpec typeSpec) - { - GenericInstSig genericInstSig = typeSpec.TypeSig.ToGenericInstSig(); - if (genericInstSig == null) - { - return ctx; - } - return new GenericArgumentContext(TryInflate(genericInstSig.GenericArguments, ctx), null); - } - throw new NotSupportedException($"type:{type}"); - } - - public static MethodSig GetInflatedMethodSig(IMethod method, GenericArgumentContext ctx) - { - if (method is MethodDef methodDef) - { - return methodDef.MethodSig; - } - if (method is MemberRef memberRef) - { - return InflateMethodSig(memberRef.MethodSig, GetInflatedMemberRefGenericArgument(memberRef.Class, ctx)); - } - if (method is MethodSpec methodSpec) - { - var genericInstMethodSig = methodSpec.GenericInstMethodSig; - if (methodSpec.Method is MethodDef methodDef2) - { - return InflateMethodSig(methodDef2.MethodSig, new GenericArgumentContext(null, TryInflate(genericInstMethodSig.GenericArguments, ctx))); - } - if (methodSpec.Method is MemberRef memberRef2) - { - return InflateMethodSig(memberRef2.MethodSig, new GenericArgumentContext( - GetInflatedMemberRefGenericArgument(memberRef2.Class, ctx)?.typeArgsStack, - TryInflate(genericInstMethodSig.GenericArguments, ctx))); - } - - } - throw new NotSupportedException($" method: {method}"); - } - - public static TypeSig InflateFieldSig(IField field, GenericArgumentContext ctx) - { - if (field is FieldDef fieldDef) - { - return fieldDef.FieldType; - } - if (field is MemberRef memberRef) - { - return Inflate(memberRef.FieldSig.Type, new GenericArgumentContext(TryInflate(GetGenericArguments(memberRef.Class), ctx), null)); - } - - throw new Exception($"unknown field:{field}"); - } - - public static ThisArgType GetThisArgType(IMethod method) - { - if (!method.MethodSig.HasThis) - { - return ThisArgType.None; - } - if (method is MethodDef methodDef) - { - return methodDef.DeclaringType.IsValueType ? ThisArgType.ValueType : ThisArgType.Class; - } - if (method is MemberRef memberRef) - { - TypeDef typeDef = MetaUtil.GetMemberRefTypeDefParentOrNull(memberRef.Class); - if (typeDef == null) - { - return ThisArgType.Class; - } - return typeDef.IsValueType ? ThisArgType.ValueType : ThisArgType.Class; - } - if (method is MethodSpec methodSpec) - { - return GetThisArgType(methodSpec.Method); - } - throw new NotSupportedException($" method: {method}"); - } - - public static MethodSig ToSharedMethodSig(ICorLibTypes corTypes, MethodSig methodSig) - { - var newReturnType = methodSig.RetType; - var newParams = new List(); - foreach (var param in methodSig.Params) - { - newParams.Add(ToShareTypeSig(corTypes, param)); - } - if (methodSig.ParamsAfterSentinel != null) - { - //foreach (var param in methodSig.ParamsAfterSentinel) - //{ - // newParamsAfterSentinel.Add(ToShareTypeSig(corTypes, param)); - //} - throw new NotSupportedException($"methodSig.ParamsAfterSentinel is not supported: {methodSig}"); - } - return new MethodSig(methodSig.CallingConvention, methodSig.GenParamCount, newReturnType, newParams, null); - } - - 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 typeSig; - case ElementType.Array: return typeSig; - 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; - } - // il2cpp will raise error when try to share generic value type - return typeSig; - //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 void AppendIl2CppStackTraceNameOfTypeSig(StringBuilder sb, TypeSig typeSig) - { - typeSig = typeSig.RemovePinnedAndModifiers(); - - switch (typeSig.ElementType) - { - case ElementType.Void: sb.Append("Void"); break; - case ElementType.Boolean: sb.Append("Boolean"); break; - case ElementType.Char: sb.Append("Char"); break; - case ElementType.I1: sb.Append("SByte"); break; - case ElementType.U1: sb.Append("Byte"); break; - case ElementType.I2: sb.Append("Int16"); break; - case ElementType.U2: sb.Append("UInt16"); break; - case ElementType.I4: sb.Append("Int32"); break; - case ElementType.U4: sb.Append("UInt32"); break; - case ElementType.I8: sb.Append("Int64"); break; - case ElementType.U8: sb.Append("UInt64"); break; - case ElementType.R4: sb.Append("Single"); break; - case ElementType.R8: sb.Append("Double"); break; - case ElementType.String: sb.Append("String"); break; - case ElementType.Ptr: AppendIl2CppStackTraceNameOfTypeSig(sb, typeSig.Next); sb.Append("*"); break; - case ElementType.ByRef: AppendIl2CppStackTraceNameOfTypeSig(sb, typeSig.Next); sb.Append("&"); break; - case ElementType.ValueType: - case ElementType.Class: - { - var classOrValueTypeSig = (ClassOrValueTypeSig)typeSig; - TypeDef typeDef = classOrValueTypeSig.TypeDefOrRef.ResolveTypeDef(); - if (typeDef == null) - { - throw new Exception($"type:{classOrValueTypeSig} definition could not be found"); - } - sb.Append(typeDef.Name); - break; - } - case ElementType.GenericInst: - { - var genericInstSig = (GenericInstSig)typeSig; - AppendIl2CppStackTraceNameOfTypeSig(sb, genericInstSig.GenericType); - break; - } - case ElementType.Var: - case ElementType.MVar: - { - var varSig = (GenericSig)typeSig; - sb.Append(varSig.GenericParam.Name); - break; - } - case ElementType.I: sb.Append("IntPtr"); break; - case ElementType.U: sb.Append("UIntPtr"); break; - case ElementType.FnPtr: sb.Append("IntPtr"); break; - case ElementType.Object: sb.Append("Object"); break; - case ElementType.SZArray: - { - var szArraySig = (SZArraySig)typeSig; - AppendIl2CppStackTraceNameOfTypeSig(sb, szArraySig.Next); - sb.Append("[]"); - break; - } - case ElementType.Array: - { - var arraySig = (ArraySig)typeSig; - AppendIl2CppStackTraceNameOfTypeSig(sb, arraySig.Next); - sb.Append("["); - for (int i = 0; i < arraySig.Rank - 1; i++) - { - sb.Append(","); - } - sb.Append("]"); - break; - } - case ElementType.TypedByRef: sb.Append("TypedReference"); break; - default: - throw new NotSupportedException(typeSig.ToString()); - } - } - - public static TypeDef GetRootDeclaringType(TypeDef type) - { - TypeDef cur = type; - while (true) - { - TypeDef declaringType = cur.DeclaringType; - if (declaringType == null) - { - return cur; - } - cur = declaringType; - } - } - - public static string CreateMethodDefIl2CppStackTraceSignature(MethodDef method) - { - var result = new StringBuilder(); - TypeDef declaringType = method.DeclaringType; - - string namespaze = GetRootDeclaringType(declaringType).Namespace; - if (!string.IsNullOrEmpty(namespaze)) - { - result.Append(namespaze); - result.Append("."); - } - result.Append(declaringType.Name); - result.Append(":"); - result.Append(method.Name); - result.Append("("); - - int index = 0; - foreach (TypeSig p in method.GetParams()) - { - if (index > 0) - { - result.Append(", "); - } - AppendIl2CppStackTraceNameOfTypeSig(result, p); - ++index; - } - result.Append(")"); - return result.ToString(); - } - - public static bool HasCompilerGeneratedAttribute(IHasCustomAttribute obj) - { - return obj.CustomAttributes.Find(ConstValues.CompilerGeneratedAttributeFullName) != null; - } - - public static bool HasEncryptFieldAttribute(IHasCustomAttribute obj) - { - return obj.CustomAttributes.Find(ConstValues.EncryptFieldAttributeFullName) != null; - } - - public static bool HasRuntimeInitializeOnLoadMethodAttribute(MethodDef method) - { - return method.CustomAttributes.Find(ConstValues.RuntimeInitializedOnLoadMethodAttributeFullName) != null; - } - - public static bool HasBlackboardEnumAttribute(TypeDef typeDef) - { - return typeDef.CustomAttributes.Find(ConstValues.BlackboardEnumAttributeFullName) != null; - } - - public static bool HasBurstCompileAttribute(IHasCustomAttribute obj) - { - return obj.CustomAttributes.Find(ConstValues.BurstCompileFullName) != null; - } - - public static bool HasDOTSCompilerGeneratedAttribute(IHasCustomAttribute obj) - { - return obj.CustomAttributes.Find(ConstValues.DOTSCompilerGeneratedAttributeFullName) != null; - } - - public static bool HasMicrosoftCodeAnalysisEmbeddedAttribute(IHasCustomAttribute obj) - { - return obj.CustomAttributes.Find(ConstValues.EmbeddedAttributeFullName) != null; - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/MetaUtil.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/MetaUtil.cs.meta deleted file mode 100644 index 9ebbd424..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/MetaUtil.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ded544371a7eb524caa1ccef3daebe55 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/NameMatcher.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/NameMatcher.cs deleted file mode 100644 index 8f6d5d68..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/NameMatcher.cs +++ /dev/null @@ -1,43 +0,0 @@ -using System.Text.RegularExpressions; - -namespace Obfuz.Utils -{ - public class NameMatcher - { - private readonly string _str; - private readonly Regex _regex; - - public string NameOrPattern => _str; - - public bool IsWildcardPattern => _regex != null; - - public NameMatcher(string nameOrPattern) - { - if (string.IsNullOrEmpty(nameOrPattern)) - { - nameOrPattern = "*"; - } - _str = nameOrPattern; - _regex = nameOrPattern.Contains("*") || nameOrPattern.Contains("?") ? new Regex(WildcardToRegex(nameOrPattern)) : null; - } - - public static string WildcardToRegex(string pattern) - { - return "^" + Regex.Escape(pattern). - Replace("\\*", ".*"). - Replace("\\?", ".") + "$"; - } - - public bool IsMatch(string name) - { - if (_regex != null) - { - return _regex.IsMatch(name); - } - else - { - return _str == name; - } - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/NameMatcher.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/NameMatcher.cs.meta deleted file mode 100644 index 6abe4e16..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/NameMatcher.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: c3a646fe086ecbd4a8dbf36a395ada71 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/NumberRange.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/NumberRange.cs deleted file mode 100644 index 90d55e0b..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/NumberRange.cs +++ /dev/null @@ -1,14 +0,0 @@ -namespace Obfuz.Utils -{ - public class NumberRange where T : struct - { - public readonly T? min; - public readonly T? max; - - public NumberRange(T? min, T? max) - { - this.min = min; - this.max = max; - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/NumberRange.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/NumberRange.cs.meta deleted file mode 100644 index f1b17e16..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/NumberRange.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 4d147a6853ce57c4d88529fb73823435 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/ObfuzIgnoreScopeComputeCache.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/ObfuzIgnoreScopeComputeCache.cs deleted file mode 100644 index 162cfdeb..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/ObfuzIgnoreScopeComputeCache.cs +++ /dev/null @@ -1,243 +0,0 @@ -using dnlib.DotNet; -using Obfuz.Editor; -using System.Linq; - -namespace Obfuz.Utils -{ - public class ObfuzIgnoreScopeComputeCache - { - private readonly CachedDictionary _selfObfuzIgnoreScopeCache; - private readonly CachedDictionary _enclosingObfuzIgnoreScopeCache; - private readonly CachedDictionary _selfObfuzIgnoreApplyToChildTypesScopeCache; - private readonly CachedDictionary _inheritedObfuzIgnoreScopeCache; - - public ObfuzIgnoreScopeComputeCache() - { - _selfObfuzIgnoreScopeCache = new CachedDictionary(GetObfuzIgnoreScope); - _enclosingObfuzIgnoreScopeCache = new CachedDictionary(GetEnclosingObfuzIgnoreScope); - _selfObfuzIgnoreApplyToChildTypesScopeCache = new CachedDictionary(GetObfuzIgnoreScopeApplyToChildTypes); - _inheritedObfuzIgnoreScopeCache = new CachedDictionary(GetInheritObfuzIgnoreScope); - } - - private ObfuzScope? GetObfuzIgnoreScope(IHasCustomAttribute obj) - { - var ca = obj.CustomAttributes.FirstOrDefault(c => c.AttributeType.FullName == ConstValues.ObfuzIgnoreAttributeFullName); - if (ca == null) - { - return null; - } - var scope = (ObfuzScope)ca.ConstructorArguments[0].Value; - return scope; - } - - private ObfuzScope? GetEnclosingObfuzIgnoreScope(TypeDef typeDef) - { - TypeDef cur = typeDef.DeclaringType; - while (cur != null) - { - var ca = cur.CustomAttributes?.FirstOrDefault(c => c.AttributeType.FullName == ConstValues.ObfuzIgnoreAttributeFullName); - if (ca != null) - { - var scope = (ObfuzScope)ca.ConstructorArguments[0].Value; - CANamedArgument inheritByNestedTypesArg = ca.GetNamedArgument("ApplyToNestedTypes", false); - bool inheritByNestedTypes = inheritByNestedTypesArg == null || (bool)inheritByNestedTypesArg.Value; - return inheritByNestedTypes ? (ObfuzScope?)scope : null; - } - cur = cur.DeclaringType; - } - return null; - } - - private ObfuzScope? GetObfuzIgnoreScopeApplyToChildTypes(TypeDef cur) - { - if (cur.Module.IsCoreLibraryModule == true) - { - return null; - } - var ca = cur.CustomAttributes?.FirstOrDefault(c => c.AttributeType.FullName == ConstValues.ObfuzIgnoreAttributeFullName); - if (ca != null) - { - var scope = (ObfuzScope)ca.ConstructorArguments[0].Value; - CANamedArgument inheritByChildTypesArg = ca.GetNamedArgument("ApplyToChildTypes", false); - bool inheritByChildTypes = inheritByChildTypesArg != null && (bool)inheritByChildTypesArg.Value; - if (inheritByChildTypes) - { - return scope; - } - } - return null; - } - - private ObfuzScope? GetInheritObfuzIgnoreScope(TypeDef typeDef) - { - TypeDef cur = typeDef; - for (; cur != null; cur = MetaUtil.GetBaseTypeDef(cur)) - { - ObfuzScope? scope = _selfObfuzIgnoreApplyToChildTypesScopeCache.GetValue(cur); - if (scope != null) - { - return scope; - } - foreach (var interfaceType in cur.Interfaces) - { - TypeDef interfaceTypeDef = interfaceType.Interface.ResolveTypeDef(); - if (interfaceTypeDef != null) - { - ObfuzScope? interfaceScope = _selfObfuzIgnoreApplyToChildTypesScopeCache.GetValue(interfaceTypeDef); - if (interfaceScope != null) - { - return interfaceScope; - } - } - } - } - return null; - } - - //private ObfuzScope? GetSelfOrDeclaringOrEnclosingOrInheritObfuzIgnoreScope((IHasCustomAttribute obj, TypeDef declaringType) objAndDeclaringType, ObfuzScope targetScope) - //{ - // ObfuzScope? scope = _selfObfuzIgnoreScopeCache.GetValue(objAndDeclaringType.obj); - // if (scope != null) - // { - // return scope; - // } - // if (objAndDeclaringType.declaringType == null) - // { - // return null; - // } - // ObfuzScope? declaringOrEnclosingScope = _selfObfuzIgnoreScopeCache.GetValue(declaringType) ?? _enclosingObfuzIgnoreScopeCache.GetValue(declaringType) ?? _inheritedObfuzIgnoreScopeCache.GetValue(declaringType); - // return declaringOrEnclosingScope != null && (declaringOrEnclosingScope & targetScope) != 0; - //} - - //private bool HasObfuzIgnoreScope(IHasCustomAttribute obj, ObfuzScope targetScope) - //{ - // ObfuzScope? objScope = _selfObfuzIgnoreScopeCache.GetValue(obj); - // return objScope != null && (objScope & targetScope) != 0; - //} - - //private bool HasDeclaringOrEnclosingOrInheritObfuzIgnoreScope(TypeDef typeDef, ObfuzScope targetScope) - //{ - // if (typeDef == null) - // { - // return false; - // } - // ObfuzScope? declaringOrEnclosingScope = _selfObfuzIgnoreScopeCache.GetValue(typeDef) ?? _enclosingObfuzIgnoreScopeCache.GetValue(typeDef) ?? _inheritedObfuzIgnoreScopeCache.GetValue(typeDef); - // return declaringOrEnclosingScope != null && (declaringOrEnclosingScope & targetScope) != 0; - //} - - public ObfuzScope? GetSelfOrDeclaringOrEnclosingOrInheritObfuzIgnoreScope(IHasCustomAttribute obj, TypeDef declaringType) - { - ObfuzScope? scope = _selfObfuzIgnoreScopeCache.GetValue(obj); - if (scope != null) - { - return scope; - } - if (declaringType == null) - { - return null; - } - ObfuzScope? declaringOrEnclosingScope = _selfObfuzIgnoreScopeCache.GetValue(declaringType) ?? _enclosingObfuzIgnoreScopeCache.GetValue(declaringType) ?? _inheritedObfuzIgnoreScopeCache.GetValue(declaringType); - return declaringOrEnclosingScope; - } - - public bool HasSelfOrEnclosingOrInheritObfuzIgnoreScope(TypeDef typeDef, ObfuzScope targetScope) - { - ObfuzScope? scope = _selfObfuzIgnoreScopeCache.GetValue(typeDef) ?? _enclosingObfuzIgnoreScopeCache.GetValue(typeDef) ?? _inheritedObfuzIgnoreScopeCache.GetValue(typeDef); - return scope != null && (scope & targetScope) != 0; - } - - public bool HasSelfOrDeclaringOrEnclosingOrInheritObfuzIgnoreScope(IHasCustomAttribute obj, TypeDef declaringType, ObfuzScope targetScope) - { - ObfuzScope? scope = _selfObfuzIgnoreScopeCache.GetValue(obj); - if (scope != null) - { - return (scope & targetScope) != 0; - } - if (declaringType == null) - { - return false; - } - ObfuzScope? declaringOrEnclosingScope = _selfObfuzIgnoreScopeCache.GetValue(declaringType) ?? _enclosingObfuzIgnoreScopeCache.GetValue(declaringType) ?? _inheritedObfuzIgnoreScopeCache.GetValue(declaringType); - return declaringOrEnclosingScope != null && (declaringOrEnclosingScope & targetScope) != 0; - } - - public bool HasSelfOrInheritPropertyOrEventOrOrTypeDefObfuzIgnoreScope(MethodDef obj, ObfuzScope targetScope) - { - ObfuzScope? scope = _selfObfuzIgnoreScopeCache.GetValue(obj); - if (scope != null && (scope & targetScope) != 0) - { - return true; - } - - TypeDef declaringType = obj.DeclaringType; - ObfuzScope? declaringOrEnclosingScope = _selfObfuzIgnoreScopeCache.GetValue(declaringType) ?? _enclosingObfuzIgnoreScopeCache.GetValue(declaringType) ?? _inheritedObfuzIgnoreScopeCache.GetValue(declaringType); - - foreach (var propertyDef in declaringType.Properties) - { - if (propertyDef.GetMethod == obj || propertyDef.SetMethod == obj) - { - ObfuzScope? finalScope = _selfObfuzIgnoreScopeCache.GetValue(propertyDef); - if (finalScope != null && (finalScope & targetScope) != 0) - { - return true; - } - break; - } - } - - foreach (var eventDef in declaringType.Events) - { - if (eventDef.AddMethod == obj || eventDef.RemoveMethod == obj) - { - ObfuzScope? finalScope = _selfObfuzIgnoreScopeCache.GetValue(eventDef); - if (finalScope != null && (finalScope & targetScope) != 0) - { - return true; - } - break; - } - } - - return declaringOrEnclosingScope != null && (declaringOrEnclosingScope & targetScope) != 0; - } - - public bool HasSelfOrInheritPropertyOrEventOrOrTypeDefIgnoreMethodName(MethodDef obj) - { - ObfuzScope? scope = _selfObfuzIgnoreScopeCache.GetValue(obj); - if (scope != null && (scope & ObfuzScope.MethodName) != 0) - { - return true; - } - - TypeDef declaringType = obj.DeclaringType; - - foreach (var propertyDef in declaringType.Properties) - { - if (propertyDef.GetMethod == obj || propertyDef.SetMethod == obj) - { - ObfuzScope? finalScope = GetObfuzIgnoreScope(propertyDef); - if (finalScope != null && (finalScope & ObfuzScope.PropertyGetterSetterName) != 0) - { - return true; - } - break; - } - } - - foreach (var eventDef in declaringType.Events) - { - if (eventDef.AddMethod == obj || eventDef.RemoveMethod == obj) - { - ObfuzScope? finalScope = GetObfuzIgnoreScope(eventDef); - if (finalScope != null && (finalScope & ObfuzScope.EventAddRemoveFireName) != 0) - { - return true; - } - break; - } - } - - return HasSelfOrEnclosingOrInheritObfuzIgnoreScope(declaringType, ObfuzScope.MethodName | ObfuzScope.PropertyGetterSetterName | ObfuzScope.EventAddRemoveFireName); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/ObfuzIgnoreScopeComputeCache.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/ObfuzIgnoreScopeComputeCache.cs.meta deleted file mode 100644 index fdc7e014..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/ObfuzIgnoreScopeComputeCache.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 2f64b9a72981c0e45a03501db02e6538 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/PathAssemblyResolver.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/PathAssemblyResolver.cs deleted file mode 100644 index d2e02e8f..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/PathAssemblyResolver.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System.IO; - -namespace Obfuz.Utils -{ - public class PathAssemblyResolver : AssemblyResolverBase - { - private readonly string[] _searchPaths; - - public PathAssemblyResolver(params string[] searchPaths) - { - _searchPaths = searchPaths; - } - - public override string ResolveAssembly(string assemblyName) - { - foreach (var path in _searchPaths) - { - string assPath = Path.Combine(path, assemblyName + ".dll"); - if (File.Exists(assPath)) - { - //Debug.Log($"resolve {assemblyName} at {assPath}"); - return assPath; - } - } - return null; - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/PathAssemblyResolver.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/PathAssemblyResolver.cs.meta deleted file mode 100644 index 1ae9c58f..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/PathAssemblyResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 5a7681737885f604e885ee39d0bedd74 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/PlatformUtil.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/PlatformUtil.cs deleted file mode 100644 index 94f41e75..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/PlatformUtil.cs +++ /dev/null @@ -1,13 +0,0 @@ -using UnityEditor; - -namespace Obfuz.Utils -{ - public static class PlatformUtil - { - public static bool IsMonoBackend() - { - return PlayerSettings.GetScriptingBackend(EditorUserBuildSettings.selectedBuildTargetGroup) - == ScriptingImplementation.Mono2x; - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/PlatformUtil.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/PlatformUtil.cs.meta deleted file mode 100644 index ec195e6d..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/PlatformUtil.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 85d01014c084c56498d292d3b16351d2 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/RandomUtil.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/RandomUtil.cs deleted file mode 100644 index 0f542995..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/RandomUtil.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System.Collections.Generic; - -namespace Obfuz.Utils -{ - static class RandomUtil - { - public static void ShuffleList(List list, IRandom random) - { - int n = list.Count; - for (int i = n - 1; i > 0; i--) - { - int j = random.NextInt(i + 1); - T temp = list[i]; - list[i] = list[j]; - list[j] = temp; - } - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/RandomUtil.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/RandomUtil.cs.meta deleted file mode 100644 index 961f1be9..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/RandomUtil.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: d482c078394711d428e627843d2481d7 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/RandomWithKey.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/RandomWithKey.cs deleted file mode 100644 index e66bfc64..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/RandomWithKey.cs +++ /dev/null @@ -1,63 +0,0 @@ -namespace Obfuz.Utils -{ - public class RandomWithKey : IRandom - { - private const long a = 1664525; - private const long c = 1013904223; - private const long m = 4294967296; // 2^32 - - private readonly int[] _key; - - private int _nextIndex; - - private int _seed; - - public RandomWithKey(int[] key, int seed) - { - _key = key; - _seed = seed; - } - - public int[] Key => _key; - - public int NextInt(int min, int max) - { - return min + NextInt(max - min); - } - - public int NextInt(int max) - { - return (int)((uint)NextInt() % (uint)max); - } - - private int GetNextSalt() - { - if (_nextIndex >= _key.Length) - { - _nextIndex = 0; - } - return _key[_nextIndex++]; - } - - public int NextInt() - { - _seed = (int)((a * _seed + c) % m); - return _seed ^ GetNextSalt(); - } - - public long NextLong() - { - return ((long)NextInt() << 32) | (uint)NextInt(); - } - - public float NextFloat() - { - return (float)((double)(uint)NextInt() / uint.MaxValue); - } - - public bool NextInPercentage(float percentage) - { - return NextFloat() < percentage; - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/RandomWithKey.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/RandomWithKey.cs.meta deleted file mode 100644 index 41b7f75e..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/RandomWithKey.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 6e16d7eb75fe2354d96eca5bb01358a4 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/ReflectionUtil.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/ReflectionUtil.cs deleted file mode 100644 index f15140da..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/ReflectionUtil.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Obfuz.Utils -{ - public static class ReflectionUtil - { - public static List FindTypesInCurrentAppDomain(string fullName) - { - return AppDomain.CurrentDomain.GetAssemblies() - .Select(assembly => assembly.GetType(fullName)) - .Where(type => type != null) - .ToList(); - } - - public static Type FindUniqueTypeInCurrentAppDomain(string fullName) - { - var foundTypes = FindTypesInCurrentAppDomain(fullName); - if (foundTypes.Count == 0) - { - throw new Exception($"class {fullName} not found in any assembly!"); - } - if (foundTypes.Count > 1) - { - throw new Exception($"class {fullName} found in multiple assemblies! Please retain only one!"); - } - return foundTypes[0]; - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/ReflectionUtil.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/ReflectionUtil.cs.meta deleted file mode 100644 index 05d723b9..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/ReflectionUtil.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 6fac8216afeffb746b1b67d1f16883b8 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/ThisArgType.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/ThisArgType.cs deleted file mode 100644 index 3f008ccc..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/ThisArgType.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace Obfuz.Utils -{ - public enum ThisArgType - { - None, - ValueType, - Class, - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/ThisArgType.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/ThisArgType.cs.meta deleted file mode 100644 index c73587a7..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/ThisArgType.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 5d5a6303cdb66374f95187ca31b5e82f -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/TypeSigUtil.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/TypeSigUtil.cs deleted file mode 100644 index 5b80674f..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/TypeSigUtil.cs +++ /dev/null @@ -1,219 +0,0 @@ -using dnlib.DotNet; -using System; -using System.Collections.Generic; -using System.Text; - -namespace Obfuz.Utils -{ - public static class TypeSigUtil - { - public static string ComputeTypeDefSignature(TypeDef type) - { - return type.FullName; - } - - public static string ComputeMethodDefSignature(MethodDef method) - { - var result = new StringBuilder(); - ComputeTypeSigName(method.MethodSig.RetType, result); - result.Append(" "); - result.Append(method.DeclaringType.FullName); - result.Append("::"); - if (method.IsStatic) - { - result.Append("@"); - } - result.Append(method.Name); - if (method.HasGenericParameters) - { - result.Append($"`{method.GenericParameters.Count}"); - } - result.Append("("); - for (int i = 0; i < method.Parameters.Count; i++) - { - if (i > 0) - { - result.Append(", "); - } - ComputeTypeSigName(method.Parameters[i].Type, result); - } - result.Append(")"); - return result.ToString(); - } - - public static string ComputeFieldDefSignature(FieldDef field) - { - var result = new StringBuilder(); - ComputeTypeSigName(field.FieldSig.Type, result); - result.Append(" "); - result.Append(field.Name); - return result.ToString(); - } - - public static string ComputePropertyDefSignature(PropertyDef property) - { - var result = new StringBuilder(); - - PropertySig propertySig = property.PropertySig; - ComputeTypeSigName(propertySig.RetType, result); - result.Append(" "); - result.Append(property.Name); - - IList parameters = propertySig.Params; - if (parameters.Count > 0) - { - result.Append("("); - - for (int i = 0; i < parameters.Count; i++) - { - if (i > 0) - { - result.Append(", "); - } - ComputeTypeSigName(parameters[i], result); - } - result.Append(")"); - } - - return result.ToString(); - } - - public static string ComputeEventDefSignature(EventDef eventDef) - { - var result = new StringBuilder(); - ComputeTypeSigName(eventDef.EventType.ToTypeSig(), result); - result.Append(" "); - result.Append(eventDef.Name); - return result.ToString(); - } - - public static string ComputeMethodSpecSignature(TypeSig type) - { - var sb = new StringBuilder(); - ComputeTypeSigName(type, sb); - return sb.ToString(); - } - - public static void ComputeTypeSigName(TypeSig type, StringBuilder result) - { - type = type.RemovePinnedAndModifiers(); - switch (type.ElementType) - { - case ElementType.Void: result.Append("void"); break; - case ElementType.Boolean: result.Append("bool"); break; - case ElementType.Char: result.Append("char"); break; - case ElementType.I1: result.Append("sbyte"); break; - case ElementType.U1: result.Append("byte"); break; - case ElementType.I2: result.Append("short"); break; - case ElementType.U2: result.Append("ushort"); break; - case ElementType.I4: result.Append("int"); break; - case ElementType.U4: result.Append("uint"); break; - case ElementType.I8: result.Append("long"); break; - case ElementType.U8: result.Append("ulong"); break; - case ElementType.R4: result.Append("float"); break; - case ElementType.R8: result.Append("double"); break; - case ElementType.String: result.Append("string"); break; - case ElementType.Ptr: - ComputeTypeSigName(((PtrSig)type).Next, result); - result.Append("*"); - break; - case ElementType.ByRef: - ComputeTypeSigName(((ByRefSig)type).Next, result); - result.Append("&"); - break; - case ElementType.ValueType: - case ElementType.Class: - { - var valueOrClassType = type.ToClassOrValueTypeSig(); - var typeDef = valueOrClassType.ToTypeDefOrRef().ResolveTypeDefThrow(); - if (typeDef.Module.IsCoreLibraryModule != true) - { - result.Append($"[{typeDef.Module.Assembly.Name}]"); - } - result.Append(typeDef.FullName); - break; - } - case ElementType.GenericInst: - { - var genInst = (GenericInstSig)type; - ComputeTypeSigName(genInst.GenericType, result); - result.Append("<"); - for (int i = 0; i < genInst.GenericArguments.Count; i++) - { - if (i > 0) - { - result.Append(","); - } - ComputeTypeSigName(genInst.GenericArguments[i], result); - } - result.Append(">"); - break; - } - case ElementType.SZArray: - ComputeTypeSigName(((SZArraySig)type).Next, result); - result.Append("[]"); - break; - case ElementType.Array: - { - var arraySig = (ArraySig)type; - ComputeTypeSigName(arraySig.Next, result); - result.Append("["); - for (int i = 0; i < arraySig.Rank; i++) - { - if (i > 0) - { - result.Append(","); - } - //result.Append(arraySig.Sizes[i]); - } - result.Append("]"); - break; - } - case ElementType.FnPtr: - { - var fnPtr = (FnPtrSig)type; - result.Append("("); - MethodSig ms = fnPtr.MethodSig; - ComputeTypeSigName(ms.RetType, result); - result.Append("("); - for (int i = 0; i < ms.Params.Count; i++) - { - if (i > 0) - { - result.Append(","); - } - ComputeTypeSigName(ms.Params[i], result); - } - result.Append(")*"); - break; - } - case ElementType.TypedByRef: - result.Append("typedref"); - break; - case ElementType.I: - result.Append("nint"); - break; - case ElementType.U: - result.Append("nuint"); - break; - case ElementType.Object: - result.Append("object"); - break; - case ElementType.Var: - { - var var = (GenericVar)type; - result.Append($"!{var.Number}"); - break; - } - case ElementType.MVar: - { - var mvar = (GenericMVar)type; - result.Append($"!!{mvar.Number}"); - break; - } - default: throw new NotSupportedException($"[ComputeTypeSigName] not support :{type}"); - - } - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/TypeSigUtil.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/TypeSigUtil.cs.meta deleted file mode 100644 index fd925122..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Editor/Utils/TypeSigUtil.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 83e1214102577b449a933438c41c97bf -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/LICENSE b/UnityProject/Packages/com.code-philosophy.obfuz/LICENSE deleted file mode 100644 index 093e5999..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2025 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. diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/LICENSE.meta b/UnityProject/Packages/com.code-philosophy.obfuz/LICENSE.meta deleted file mode 100644 index 3bb31e64..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/LICENSE.meta +++ /dev/null @@ -1,7 +0,0 @@ -fileFormatVersion: 2 -guid: 4431597180c05fb46839ded925d40a19 -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Plugins.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Plugins.meta deleted file mode 100644 index 074840ee..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Plugins.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: f8b2842c597aa4249b275ef7cb2200ec -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Plugins/dnlib.dll b/UnityProject/Packages/com.code-philosophy.obfuz/Plugins/dnlib.dll deleted file mode 100644 index d6c2fd99..00000000 Binary files a/UnityProject/Packages/com.code-philosophy.obfuz/Plugins/dnlib.dll and /dev/null differ diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Plugins/dnlib.dll.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Plugins/dnlib.dll.meta deleted file mode 100644 index 54427da9..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Plugins/dnlib.dll.meta +++ /dev/null @@ -1,69 +0,0 @@ -fileFormatVersion: 2 -guid: 355f9a0beb9535e4792b15e532d17460 -PluginImporter: - externalObjects: {} - serializedVersion: 2 - iconMap: {} - executionOrder: {} - defineConstraints: [] - isPreloaded: 0 - isOverridable: 1 - isExplicitlyReferenced: 0 - validateReferences: 1 - platformData: - - first: - : Any - second: - enabled: 0 - settings: - Exclude Editor: 0 - Exclude Linux64: 1 - Exclude OSXUniversal: 1 - Exclude Win: 1 - Exclude Win64: 1 - - 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 - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/README.md b/UnityProject/Packages/com.code-philosophy.obfuz/README.md deleted file mode 100644 index 805be5dd..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/README.md +++ /dev/null @@ -1,73 +0,0 @@ -# Obfuz - -[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) -[![Unity Version](https://img.shields.io/badge/Unity-2019%2B-blue)](https://unity.com/) - -Obfuz 是一款开源、强大、易用及稳定可靠的充分满足商业化游戏项目需求的Unity代码混淆和加固解决方案。 - -[English](./README-EN.md) | [中文](./README.md) - -[Github](https://github.com/focus-creative-games/obfuz) | [Gitee](https://gitee.com/focus-creative-games/obfuz) - ---- - -## 为什么选择 Obfuz? - -- **开源免费**:基于 MIT 协议,免费使用和修改。 -- **功能强大**:提供媲美商业工具的强大混淆和代码加固功能。 -- **专为 Unity 设计**:为Unity工作流深度优化,自动化处理除了反射以外所有需要特殊处理的情况(如MonoBehaviour名不能混淆),几乎零配置即可集成代码混淆功能。 -- **稳定可靠**:有全面的自动化测试项目,成功通过3000个多个测试用例,几乎覆盖所有常见的代码用例 -- **支持热更新**:支持HybridCLR、xlua之类最流行的代码热更新方案 -- **敏捷开发**:快速响应开发者需求、迅速修复bug,及时跟进Unity及团结引擎的最新改动 - -## 功能特性 - -- **符号混淆**:支持丰富的配置规则和增量混淆,灵活高效地保护代码。 -- **常量混淆**:混淆 `int`、`long`、`float`、`double`、`string`、数组 等常量,防止逆向工程。 -- **变量内存加密**:加密内存中的变量,提升运行时安全。 -- **执行栈混淆**:混淆执行栈中变量,提高逆向难度。 -- **表达式混淆**:混淆add、sub之类的绝大多数常见运算。 -- **函数调用混淆**:打乱函数调用结构,增加破解难度。 -- **控制流混淆**:控制流平坦化,打乱代码执行流程,显著增加逆向难度。 -- **随机加密虚拟机**:生成随机化虚拟机,有效抵御反编译和破解工具。 -- **静态与动态解密**:结合静态和动态解密,防止离线静态分析。 -- **混淆多态化**:通过配置不同的生成密钥和随机化种子,生成不同的混淆代码。 -- **垃圾代码生成**:支持多种垃圾代码生成,提高App Store和Google Play审核通过率。 -- **深度 Unity 集成**:与 Unity 工作流无缝衔接,简单配置即可使用。 -- **热更新支持**:全面兼容 HybridCLR、xLua 等热更新框架,确保动态代码更新顺畅。 -- **兼容DOTS**:兼容DOTS各个版本,无需配置即可正常工作。 - -## 支持的Unity版本与平台 - -- 支持Unity 2019+ -- 支持团结引擎 -- 支持Unity和团结引擎支持的所有平台 -- 支持il2cpp和mono backend - -## 文档 - -- [文档](https://www.obfuz.com/) -- [快速上手](https://www.obfuz.com/docs/beginner/quick-start) -- [示例项目](https://github.com/focus-creative-games/obfuz-samples) - -## 未来计划 - -Obfuz 正在持续开发中,即将推出的功能包括: - -- **代码水印**:嵌入可追踪的水印。 -- **反内存转储与反调试**:防止内存转储和调试行为。 -- **DLL 文件结构加密**:保护 DLL 文件结构免受篡改。 -- **代码虚拟化**:将代码转化为虚拟化指令,提供最高级别安全。 - -## 许可证 - -Obfuz 采用 MIT 许可证发布,欢迎自由使用、修改和分发。 - -## 联系我们 - -如有问题、建议或错误报告,请在用以下方式联系我们: - -- GitHub 上提交 Issue -- 邮件联系维护者:`obfuz#code-philosophy.com` -- QQ群 **Obfuz交流群**: 1048396510 -- discord频道 `https://discord.gg/bFXhmrUw8c` diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/README.md.meta b/UnityProject/Packages/com.code-philosophy.obfuz/README.md.meta deleted file mode 100644 index a62041b5..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/README.md.meta +++ /dev/null @@ -1,7 +0,0 @@ -fileFormatVersion: 2 -guid: 4a7745e765ea87042b47ad24b6516c57 -TextScriptImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/REAME-EN.md b/UnityProject/Packages/com.code-philosophy.obfuz/REAME-EN.md deleted file mode 100644 index 2b6e77d0..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/REAME-EN.md +++ /dev/null @@ -1,73 +0,0 @@ -# Obfuz - -[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) -[![Unity Version](https://img.shields.io/badge/Unity-2019%2B-blue)](https://unity.com/) - -**Obfuz** is an open-source, powerful, easy-to-use, and highly reliable Unity code obfuscation and protection solution that fully meets the demands of commercial game projects. - -[English](./README-EN.md) | [中文](./README.md) - -[Github](https://github.com/focus-creative-games/obfuz) | [Gitee](https://gitee.com/focus-creative-games/obfuz) - ---- - -## Why Choose Obfuz? - -- **Open Source & Free**: Licensed under MIT, free to use and modify. -- **Powerful Features**: Delivers obfuscation and code protection comparable to commercial tools. -- **Unity-First Design**: Deeply optimized for Unity workflows. Automatically handles all edge cases (e.g., preserving `MonoBehaviour` names) except reflection (due to technical limitations). Near-zero configuration required. -- **Battle-Tested**: Verified by 3,000+ automated test cases covering virtually all common code patterns. -- **Hot Reload Ready**: Fully compatible with leading hot-reload solutions like HybridCLR and xLua. -- **Agile Development**: Rapid bug fixes, prompt feature updates, and immediate support for the latest Unity/Unity Engine changes. - -## Features - -- **Symbol Obfuscation**: Supports comprehensive configuration rules and incremental obfuscation for flexible and efficient code protection. -- **Constant Obfuscation**: Obfuscates constants such as `int`, `long`, `float`, `double`, `string` and `array` to prevent reverse engineering. -- **Variable Memory Encryption**: Encrypts variables in memory to enhance runtime security. -- **Eval stack Obfuscation**: Obfuscates eval stack variable to prevent reverse engineering. -- **Expression Obfuscation**: Obfuscate complex expressions for enhanced protection. -- **Function Call Obfuscation**: Scrambles function call structures to increase cracking difficulty. -- **Control Flow Obfuscation**: Disrupt code flow to deter reverse engineering. -- **Randomized Encryption VM**: Generates randomized virtual machines to thwart decompilation and cracking tools. -- **Static and Dynamic Decryption**: Combines static and dynamic decryption to resist offline static analysis. - **Obfuscation Polymorphism**: Generates different obfuscated code by configuring different generation keys and randomization seeds. -- **Garbage Code Generation**​​: Supports various types of low-quality code generation to improve App Store and Google Play review pass rates -- **Seamless Unity Integration**: Deeply integrated with Unity workflows, requiring minimal configuration to get started. -- **Hot Update Compatibility**: Fully supports hot update frameworks like HybridCLR, xLua, and Puerts, ensuring compatibility with dynamic code updates. -- **DOTS Compatibility**: Works seamlessly across all DOTS versions with zero configuration required. - -## Supported Unity Versions & Platforms - -- Unity 2019 and later versions -- Tuanjie 1.0.0 and later versions -- All platforms supported by Unity and Tuanjie -- il2cpp and mono backend - -## Planned Features - -Obfuz is actively evolving. Upcoming features include: - -- **Code Watermarking**: Embed traceable watermarks in your code. -- **Anti-Memory Dumping and Anti-Debugging**: Prevent memory dumps and debugging attempts. -- **DLL Structure Encryption**: Secure DLL file structures against tampering. -- **Code Virtualization**: Transform code into virtualized instructions for maximum security. - -## Documentation - -- [Document](https://www.obfuz.com/) -- [Quick Start](https://www.obfuz.com/docs/beginner/quick-start) -- [Samples](https://github.com/focus-creative-games/obfuz-samples) - -## License - -Obfuz is released under the MIT License. Feel free to use, modify, and distribute it as needed. - -## Contact - -For questions, suggestions, or bug reports, please reach us through: - -- Submit an Issue on GitHub -- Email the maintainer: `obfuz#code-philosophy.com` -- Obfuz QQ Group: 1048396510 -- Discord channel: `https://discord.gg/bFXhmrUw8c` diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/REAME-EN.md.meta b/UnityProject/Packages/com.code-philosophy.obfuz/REAME-EN.md.meta deleted file mode 100644 index 263850d6..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/REAME-EN.md.meta +++ /dev/null @@ -1,7 +0,0 @@ -fileFormatVersion: 2 -guid: 462f7b98432032e4ba509274c1e90b1d -TextScriptImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Runtime.meta deleted file mode 100644 index a93405fa..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: cd1451b864839ad41b5463274b1d171c -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/AssetUtility.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/AssetUtility.cs deleted file mode 100644 index e3f5fd61..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/AssetUtility.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; - -namespace Obfuz -{ - public static class AssetUtility - { - public static void VerifySecretKey(int expectedValue, int actualValue) - { - if (expectedValue != actualValue) - { - throw new Exception($"VerifySecretKey failed. Your secret key is unmatched with secret key used by current assembly in obfuscation"); - } - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/AssetUtility.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/AssetUtility.cs.meta deleted file mode 100644 index 8b17ab24..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/AssetUtility.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 72fb691c46a883f4ea3b3dfe7d2280f3 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/ConstUtility.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/ConstUtility.cs deleted file mode 100644 index 81918a4d..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/ConstUtility.cs +++ /dev/null @@ -1,78 +0,0 @@ -using System; -using System.Text; -using UnityEngine.Assertions; - -namespace Obfuz -{ - public static class ConstUtility - { - public static int GetInt(byte[] data, int offset) - { - return BitConverter.ToInt32(data, offset); - } - - public static long GetLong(byte[] data, int offset) - { - return BitConverter.ToInt64(data, offset); - } - - public static float GetFloat(byte[] data, int offset) - { - return BitConverter.ToSingle(data, offset); - } - - public static double GetDouble(byte[] data, int offset) - { - return BitConverter.ToDouble(data, offset); - } - - public static string GetString(byte[] data, int offset, int length) - { - return Encoding.UTF8.GetString(data, offset, length); - } - - public static byte[] GetBytes(byte[] data, int offset, int length) - { - byte[] result = new byte[length]; - Array.Copy(data, offset, result, 0, length); - return result; - } - - public static int[] GetInts(byte[] data, int offset, int byteLength) - { - Assert.IsTrue(byteLength % 4 == 0); - int[] result = new int[byteLength >> 2]; - Buffer.BlockCopy(data, offset, result, 0, byteLength); - return result; - } - - public static void InitializeArray(Array array, byte[] data, int offset, int length) - { - Buffer.BlockCopy(data, offset, array, 0, length); - } - - public static unsafe int CastFloatAsInt(float value) - { - int* intValue = (int*)&value; - return *intValue; - } - - public static unsafe float CastIntAsFloat(int value) - { - float* floatValue = (float*)&value; - return *floatValue; - } - - public static unsafe long CastDoubleAsLong(double value) - { - long* longValue = (long*)&value; - return *longValue; - } - - public static unsafe double CastLongAsDouble(long value) - { - double* doubleValue = (double*)&value; - return *doubleValue; - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/ConstUtility.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/ConstUtility.cs.meta deleted file mode 100644 index f474205a..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/ConstUtility.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 48bd592d1a1339643be1fafe4b97c941 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/EncryptFieldAttribute.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/EncryptFieldAttribute.cs deleted file mode 100644 index 715853e6..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/EncryptFieldAttribute.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System; - -namespace Obfuz -{ - [AttributeUsage(AttributeTargets.Field, Inherited = false, AllowMultiple = false)] - public class EncryptFieldAttribute : Attribute - { - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/EncryptFieldAttribute.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/EncryptFieldAttribute.cs.meta deleted file mode 100644 index a76ea9d1..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/EncryptFieldAttribute.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 30f22110938816d4cb7e9cc9a176fd1e -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/EncryptionScope.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/EncryptionScope.cs deleted file mode 100644 index 9e50ae8a..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/EncryptionScope.cs +++ /dev/null @@ -1,31 +0,0 @@ -namespace Obfuz -{ - public interface IEncryptionScope - { - - } - - public abstract class EncryptionScopeBase : IEncryptionScope - { - public void ForcePreserveAOT() - { - EncryptionService.Encrypt(0, 0, 0); - } - } - - public struct DefaultDynamicEncryptionScope : IEncryptionScope - { - public void ForcePreserveAOT() - { - EncryptionService.Encrypt(0, 0, 0); - } - } - - public struct DefaultStaticEncryptionScope : IEncryptionScope - { - public void ForcePreserveAOT() - { - EncryptionService.Encrypt(0, 0, 0); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/EncryptionScope.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/EncryptionScope.cs.meta deleted file mode 100644 index 064f8750..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/EncryptionScope.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 1d729fe7cb7d0bc43a69f1ba09f99061 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/EncryptionService.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/EncryptionService.cs deleted file mode 100644 index 546b05ed..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/EncryptionService.cs +++ /dev/null @@ -1,127 +0,0 @@ -using System; - -namespace Obfuz -{ - - public static class EncryptionService where T : IEncryptionScope - { - // for compatibility with Mono because Mono will raise FieldAccessException when try access private field - public static IEncryptor _encryptor; - - public static IEncryptor Encryptor - { - get => _encryptor; - set { _encryptor = value; } - } - - public static void EncryptBlock(byte[] data, int ops, int salt) - { - _encryptor.EncryptBlock(data, ops, salt); - } - - public static void DecryptBlock(byte[] data, int ops, int salt) - { - _encryptor.DecryptBlock(data, ops, salt); - } - - public static int Encrypt(int value, int opts, int salt) - { - return _encryptor.Encrypt(value, opts, salt); - } - - public static int Decrypt(int value, int opts, int salt) - { - return _encryptor.Decrypt(value, opts, salt); - } - - public static long Encrypt(long value, int opts, int salt) - { - return _encryptor.Encrypt(value, opts, salt); - } - - public static long Decrypt(long value, int opts, int salt) - { - return _encryptor.Decrypt(value, opts, salt); - } - - public static float Encrypt(float value, int opts, int salt) - { - return _encryptor.Encrypt(value, opts, salt); - } - - public static float Decrypt(float value, int opts, int salt) - { - return _encryptor.Decrypt(value, opts, salt); - } - - public static double Encrypt(double value, int opts, int salt) - { - return _encryptor.Encrypt(value, opts, salt); - } - - public static double Decrypt(double value, int opts, int salt) - { - return _encryptor.Decrypt(value, opts, salt); - } - - public static byte[] Encrypt(byte[] value, int offset, int length, int opts, int salt) - { - return _encryptor.Encrypt(value, offset, length, opts, salt); - } - - public static byte[] Decrypt(byte[] value, int offset, int byteLength, int ops, int salt) - { - return _encryptor.Decrypt(value, offset, byteLength, ops, salt); - } - - public static byte[] Encrypt(string value, int ops, int salt) - { - return _encryptor.Encrypt(value, ops, salt); - } - - public static string DecryptString(byte[] value, int offset, int stringBytesLength, int ops, int salt) - { - return _encryptor.DecryptString(value, offset, stringBytesLength, ops, salt); - } - - - public static int DecryptFromRvaInt(byte[] data, int offset, int ops, int salt) - { - int encryptedValue = BitConverter.ToInt32(data, offset); - return Decrypt(encryptedValue, ops, salt); - } - - public static long DecryptFromRvaLong(byte[] data, int offset, int ops, int salt) - { - long encryptedValue = BitConverter.ToInt64(data, offset); - return Decrypt(encryptedValue, ops, salt); - } - - public static float DecryptFromRvaFloat(byte[] data, int offset, int ops, int salt) - { - float encryptedValue = BitConverter.ToSingle(data, offset); - return Decrypt(encryptedValue, ops, salt); - } - - public static double DecryptFromRvaDouble(byte[] data, int offset, int ops, int salt) - { - double encryptedValue = BitConverter.ToDouble(data, offset); - return Decrypt(encryptedValue, ops, salt); - } - - public static string DecryptFromRvaString(byte[] data, int offset, int length, int ops, int salt) - { - return DecryptString(data, offset, length, ops, salt); - } - - public static byte[] DecryptFromRvaBytes(byte[] data, int offset, int bytesLength, int ops, int salt) - { - return Decrypt(data, offset, bytesLength, ops, salt); - } - - public static void DecryptInitializeArray(System.Array arr, System.RuntimeFieldHandle field, int length, int ops, int salt) - { - _encryptor.DecryptInitializeArray(arr, field, length, ops, salt); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/EncryptionService.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/EncryptionService.cs.meta deleted file mode 100644 index d7364ef7..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/EncryptionService.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: bbbeb7501a0d84542828cb1aa7103d1b -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/EncryptorBase.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/EncryptorBase.cs deleted file mode 100644 index 3fe2b305..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/EncryptorBase.cs +++ /dev/null @@ -1,362 +0,0 @@ -using System; -using System.Runtime.CompilerServices; -using System.Text; -using Unity.Collections.LowLevel.Unsafe; -using UnityEngine.Assertions; - -namespace Obfuz -{ - public abstract class EncryptorBase : IEncryptor - { - public abstract int OpCodeCount { get; } - - public static int[] ConvertToIntKey(byte[] key) - { - Assert.AreEqual(0, key.Length % 4); - int align4Length = key.Length / 4; - int[] intKey = new int[align4Length]; - Buffer.BlockCopy(key, 0, intKey, 0, key.Length); - return intKey; - } - - public abstract int Encrypt(int value, int opts, int salt); - public abstract int Decrypt(int value, int opts, int salt); - - public virtual long Encrypt(long value, int opts, int salt) - { - int low = (int)value; - int high = (int)(value >> 32); - int encryptedLow = Encrypt(low, opts, salt); - int encryptedHigh = Encrypt(high, opts, salt); - return ((long)encryptedHigh << 32) | (uint)encryptedLow; - } - - public virtual long Decrypt(long value, int opts, int salt) - { - int low = (int)value; - int high = (int)(value >> 32); - int decryptedLow = Decrypt(low, opts, salt); - int decryptedHigh = Decrypt(high, opts, salt); - return ((long)decryptedHigh << 32) | (uint)decryptedLow; - } - - public virtual unsafe float Encrypt(float value, int opts, int salt) - { - if (float.IsNaN(value) || float.IsInfinity(value)) - { - return value; - } - ref int intValue = ref *(int*)&value; - int xorValue = ((1 << 23) - 1) & Decrypt(0xABCD, opts, salt); - intValue ^= xorValue; - return value; - } - - public virtual unsafe float Decrypt(float value, int opts, int salt) - { - if (float.IsNaN(value) || float.IsInfinity(value)) - { - return value; - } - ref int intValue = ref *(int*)&value; - int xorValue = ((1 << 23) - 1) & Decrypt(0xABCD, opts, salt); - intValue ^= xorValue; - return value; - } - - public virtual unsafe double Encrypt(double value, int opts, int salt) - { - if (double.IsNaN(value) || double.IsInfinity(value)) - { - return value; - } - ref long longValue = ref *(long*)&value; - long xorValue = ((1L << 52) - 1) & Decrypt(0xAABBCCDDL, opts, salt); - longValue ^= xorValue; - return value; - } - - public virtual unsafe double Decrypt(double value, int opts, int salt) - { - if (double.IsNaN(value) || double.IsInfinity(value)) - { - return value; - } - ref long longValue = ref *(long*)&value; - long xorValue = ((1L << 52) - 1) & Decrypt(0xAABBCCDDL, opts, salt); - longValue ^= xorValue; - return value; - } - - public virtual unsafe byte[] Encrypt(byte[] value, int offset, int length, int ops, int salt) - { - if (length == 0) - { - return Array.Empty(); - } - - var encryptedBytes = new byte[length]; - int intArrLength = length >> 2; - - // align to 4 - if ((offset & 0x3) != 0) - { - Buffer.BlockCopy(value, offset, encryptedBytes, 0, length); - - // encrypt int - - fixed (byte* dstBytePtr = &encryptedBytes[0]) - { - int* dstIntPtr = (int*)dstBytePtr; - int last = 0; - for (int i = 0; i < intArrLength; i++) - { - last ^= Encrypt(dstIntPtr[i], ops, salt); - dstIntPtr[i] = last; - } - } - for (int i = intArrLength * 4; i < length; i++) - { - encryptedBytes[i] = (byte)(encryptedBytes[i] ^ salt); - } - } - else - { - // encrypt int - fixed (byte* srcBytePtr = &value[offset]) - { - fixed (byte* dstBytePtr = &encryptedBytes[0]) - { - int* srcIntPtr = (int*)srcBytePtr; - int* dstIntPtr = (int*)dstBytePtr; - - int last = 0; - for (int i = 0; i < intArrLength; i++) - { - last ^= Encrypt(srcIntPtr[i], ops, salt); - dstIntPtr[i] = last; - } - } - } - for (int i = intArrLength * 4; i < length; i++) - { - encryptedBytes[i] = (byte)(value[offset + i] ^ salt); - } - } - return encryptedBytes; - } - - public unsafe virtual byte[] Decrypt(byte[] value, int offset, int length, int ops, int salt) - { - if (length == 0) - { - return Array.Empty(); - } - var decryptedBytes = new byte[length]; - int intArrLength = length >> 2; - - // align to 4 - if ((offset & 0x3) != 0) - { - Buffer.BlockCopy(value, offset, decryptedBytes, 0, length); - - // encrypt int - - fixed (byte* dstBytePtr = &decryptedBytes[0]) - { - int* dstIntPtr = (int*)dstBytePtr; - int last = 0; - for (int i = 0; i < intArrLength; i++) - { - int oldLast = last; - last = dstIntPtr[i]; - dstIntPtr[i] = Decrypt(last ^ oldLast, ops, salt); - } - } - for (int i = intArrLength * 4; i < length; i++) - { - decryptedBytes[i] = (byte)(decryptedBytes[i] ^ salt); - } - } - else - { - // encrypt int - fixed (byte* srcBytePtr = &value[offset]) - { - fixed (byte* dstBytePtr = &decryptedBytes[0]) - { - int* srcIntPtr = (int*)srcBytePtr; - int* dstIntPtr = (int*)dstBytePtr; - int last = 0; - for (int i = 0; i < intArrLength; i++) - { - int oldLast = last; - last = srcIntPtr[i]; - dstIntPtr[i] = Decrypt(last ^ oldLast, ops, salt); - } - } - } - for (int i = intArrLength * 4; i < length; i++) - { - decryptedBytes[i] = (byte)(value[offset + i] ^ salt); - } - } - return decryptedBytes; - } - - public virtual byte[] Encrypt(string value, int ops, int salt) - { - if (value.Length == 0) - { - return Array.Empty(); - } - byte[] bytes = Encoding.UTF8.GetBytes(value); - return Encrypt(bytes, 0, bytes.Length, ops, salt); - } - - public virtual string DecryptString(byte[] value, int offset, int length, int ops, int salt) - { - if (length == 0) - { - return string.Empty; - } - byte[] bytes = Decrypt(value, offset, length, ops, salt); - return Encoding.UTF8.GetString(bytes); - } - - public virtual unsafe void EncryptBlock(byte[] data, int ops, int salt) - { - int length = data.Length; - int intArrLength = length >> 2; - - fixed (byte* dstBytePtr = &data[0]) - { - int* dstIntPtr = (int*)dstBytePtr; - int last = 0; - for (int i = 0; i < intArrLength; i++) - { - last ^= Encrypt(dstIntPtr[i], ops, salt); - dstIntPtr[i] = last; - } - } - for (int i = intArrLength * 4; i < length; i++) - { - data[i] = (byte)(data[i] ^ salt); - } - } - - public virtual unsafe void DecryptBlock(byte[] data, int ops, int salt) - { - fixed (byte* dataPtr = &data[0]) - { - DecryptBlock(dataPtr, data.Length, ops, salt); - } - } - - private unsafe void DecryptBlock(byte* data, int length, int ops, int salt) - { - int intArrLength = length >> 2; - - int* dstIntPtr = (int*)data; - int last = 0; - for (int i = 0; i < intArrLength; i++) - { - int oldLast = last; - last = dstIntPtr[i]; - dstIntPtr[i] = Decrypt(oldLast ^ last, ops, salt); - } - for (int i = intArrLength * 4; i < length; i++) - { - data[i] = (byte)(data[i] ^ salt); - } - } - - public virtual unsafe void DecryptInitializeArray(System.Array arr, System.RuntimeFieldHandle field, int length, int ops, int salt) - { - //Assert.AreEqual(Marshal.SizeOf(arr.GetType().GetElementType()), arr.Length); - RuntimeHelpers.InitializeArray(arr, field); - if (arr is byte[] byteArr) - { - fixed (byte* dataPtr = &byteArr[0]) - { - DecryptBlock(dataPtr, length, ops, salt); - } - } - else if (arr is int[] intArr) - { - fixed (int* dataPtr = &intArr[0]) - { - DecryptBlock((byte*)dataPtr, length, ops, salt); - } - } - else if (arr is long[] longArr) - { - fixed (long* dataPtr = &longArr[0]) - { - DecryptBlock((byte*)dataPtr, length, ops, salt); - } - } - else if (arr is sbyte[] sbyteArr) - { - fixed (sbyte* dataPtr = &sbyteArr[0]) - { - DecryptBlock((byte*)dataPtr, length, ops, salt); - } - } - else if (arr is short[] shortArr) - { - fixed (short* dataPtr = &shortArr[0]) - { - DecryptBlock((byte*)dataPtr, length, ops, salt); - } - } - else if (arr is ushort[] ushortArr) - { - fixed (ushort* dataPtr = &ushortArr[0]) - { - DecryptBlock((byte*)dataPtr, length, ops, salt); - } - } - else if (arr is uint[] uintArr) - { - fixed (uint* dataPtr = &uintArr[0]) - { - DecryptBlock((byte*)dataPtr, length, ops, salt); - } - } - else if (arr is ulong[] ulongArr) - { - fixed (ulong* dataPtr = &ulongArr[0]) - { - DecryptBlock((byte*)dataPtr, length, ops, salt); - } - } - else if (arr is float[] floatArr) - { - fixed (float* dataPtr = &floatArr[0]) - { - DecryptBlock((byte*)dataPtr, length, ops, salt); - } - } - else if (arr is double[] doubleArr) - { - fixed (double* dataPtr = &doubleArr[0]) - { - DecryptBlock((byte*)dataPtr, length, ops, salt); - } - } - else - { - void* dataPtr = UnsafeUtility.PinGCArrayAndGetDataAddress(arr, out ulong handle); - try - { - DecryptBlock((byte*)dataPtr, length, ops, salt); - } - finally - { - UnsafeUtility.ReleaseGCObject(handle); - } - } - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/EncryptorBase.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/EncryptorBase.cs.meta deleted file mode 100644 index e81d5219..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/EncryptorBase.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: d1d4c5725e7ad624ba8e55ecb63bb440 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/ExprUtility.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/ExprUtility.cs deleted file mode 100644 index ff037e00..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/ExprUtility.cs +++ /dev/null @@ -1,247 +0,0 @@ -using System; - -namespace Obfuz -{ - public static class ExprUtility - { - public static int Add(int a, int b) - { - return a + b; - } - - public static long Add(long a, long b) - { - return a + b; - } - - public static float Add(float a, float b) - { - return a + b; - } - - public static double Add(double a, double b) - { - return a + b; - } - - public static IntPtr Add(IntPtr a, IntPtr b) - { - return (IntPtr)((long)a + (long)b); - } - - public static IntPtr Add(IntPtr a, int b) - { - return a + b; - } - - public static int Subtract(int a, int b) - { - return a - b; - } - - public static long Subtract(long a, long b) - { - return a - b; - } - - public static float Subtract(float a, float b) - { - return a - b; - } - - public static double Subtract(double a, double b) - { - return a - b; - } - - public static IntPtr Subtract(IntPtr a, IntPtr b) - { - return (IntPtr)((long)a - (long)b); - } - - public static IntPtr Subtract(IntPtr a, int b) - { - return a - b; - } - - public static int Multiply(int a, int b) - { - return a * b; - } - - public static long Multiply(long a, long b) - { - return a * b; - } - - public static float Multiply(float a, float b) - { - return a * b; - } - - public static double Multiply(double a, double b) - { - return a * b; - } - - public static IntPtr Multiply(IntPtr a, IntPtr b) - { - return (IntPtr)((long)a * (long)b); - } - - public static IntPtr Multiply(IntPtr a, int b) - { - return (IntPtr)((long)a * b); - } - - public static int Divide(int a, int b) - { - return a / b; - } - - public static long Divide(long a, long b) - { - return a / b; - } - - public static float Divide(float a, float b) - { - return a / b; - } - - public static double Divide(double a, double b) - { - return a / b; - } - - public static int DivideUn(int a, int b) - { - return (int)((uint)a / (uint)b); - } - - public static long DivideUn(long a, long b) - { - return (long)((ulong)a / (ulong)b); - } - - public static int Rem(int a, int b) - { - return a % b; - } - - public static long Rem(long a, long b) - { - return a % b; - } - - public static float Rem(float a, float b) - { - return a % b; - } - - public static double Rem(double a, double b) - { - return a % b; - } - - public static int RemUn(int a, int b) - { - return (int)((uint)a % (uint)b); - } - - public static long RemUn(long a, long b) - { - return (long)((ulong)a % (ulong)b); - } - - public static int Negate(int a) - { - return -a; - } - - public static long Negate(long a) - { - return -a; - } - - public static float Negate(float a) - { - return -a; - } - - public static double Negate(double a) - { - return -a; - } - - public static int And(int a, int b) - { - return a & b; - } - - public static long And(long a, long b) - { - return a & b; - } - - public static int Or(int a, int b) - { - return a | b; - } - - public static long Or(long a, long b) - { - return a | b; - } - - public static int Xor(int a, int b) - { - return a ^ b; - } - - public static long Xor(long a, long b) - { - return a ^ b; - } - - public static int Not(int a) - { - return ~a; - } - - public static long Not(long a) - { - return ~a; - } - - public static int ShiftLeft(int a, int b) - { - return a << b; - } - - public static long ShiftLeft(long a, int b) - { - return a << b; - } - - public static int ShiftRight(int a, int b) - { - return a >> b; - } - - public static long ShiftRight(long a, int b) - { - return a >> b; - } - - public static int ShiftRightUn(int a, int b) - { - return (int)((uint)a >> b); - } - - public static long ShiftRightUn(long a, int b) - { - return (long)((ulong)a >> b); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/ExprUtility.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/ExprUtility.cs.meta deleted file mode 100644 index 4f7c95b8..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/ExprUtility.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 9aba5050818a0224696fcf73752fb225 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/IEncryptor.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/IEncryptor.cs deleted file mode 100644 index 63a609e9..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/IEncryptor.cs +++ /dev/null @@ -1,30 +0,0 @@ -namespace Obfuz -{ - public interface IEncryptor - { - int OpCodeCount { get; } - - void EncryptBlock(byte[] data, int ops, int salt); - void DecryptBlock(byte[] data, int ops, int salt); - - int Encrypt(int value, int opts, int salt); - int Decrypt(int value, int opts, int salt); - - long Encrypt(long value, int opts, int salt); - long Decrypt(long value, int opts, int salt); - - float Encrypt(float value, int opts, int salt); - float Decrypt(float value, int opts, int salt); - - double Encrypt(double value, int opts, int salt); - double Decrypt(double value, int opts, int salt); - - byte[] Encrypt(byte[] value, int offset, int length, int opts, int salt); - byte[] Decrypt(byte[] value, int offset, int byteLength, int ops, int salt); - - byte[] Encrypt(string value, int ops, int salt); - string DecryptString(byte[] value, int offset, int stringBytesLength, int ops, int salt); - - void DecryptInitializeArray(System.Array arr, System.RuntimeFieldHandle field, int length, int ops, int salt); - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/IEncryptor.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/IEncryptor.cs.meta deleted file mode 100644 index 41418218..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/IEncryptor.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 3078fa59ff0af6b4cbbee25e20bc41c1 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/NullEncryptor.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/NullEncryptor.cs deleted file mode 100644 index 20dca52c..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/NullEncryptor.cs +++ /dev/null @@ -1,89 +0,0 @@ -using System; -using System.Text; - -namespace Obfuz -{ - public class NullEncryptor : EncryptorBase - { - private readonly byte[] _key; - - public override int OpCodeCount => 256; - - public NullEncryptor(byte[] key) - { - _key = key; - } - - public override int Encrypt(int value, int opts, int salt) - { - return value; - } - - public override int Decrypt(int value, int opts, int salt) - { - return value; - } - - public override long Encrypt(long value, int opts, int salt) - { - return value; - } - - public override long Decrypt(long value, int opts, int salt) - { - return value; - } - - public override float Encrypt(float value, int opts, int salt) - { - return value; - } - - public override float Decrypt(float value, int opts, int salt) - { - return value; - } - - public override double Encrypt(double value, int opts, int salt) - { - return value; - } - - public override double Decrypt(double value, int opts, int salt) - { - return value; - } - - public override byte[] Encrypt(byte[] value, int offset, int length, int opts, int salt) - { - if (length == 0) - { - return Array.Empty(); - } - var encryptedBytes = new byte[length]; - Buffer.BlockCopy(value, offset, encryptedBytes, 0, length); - return encryptedBytes; - } - - public override byte[] Decrypt(byte[] value, int offset, int length, int ops, int salt) - { - if (length == 0) - { - return Array.Empty(); - } - byte[] byteArr = new byte[length]; - Buffer.BlockCopy(value, 0, byteArr, 0, length); - return byteArr; - } - - public override byte[] Encrypt(string value, int ops, int salt) - { - return Encoding.UTF8.GetBytes(value); - } - - public override string DecryptString(byte[] value, int offset, int length, int ops, int salt) - { - return Encoding.UTF8.GetString(value, offset, length); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/NullEncryptor.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/NullEncryptor.cs.meta deleted file mode 100644 index b490d290..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/NullEncryptor.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: c53481f2ec513be4783a5ae2f76dc6e7 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/ObfuscationInstincts.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/ObfuscationInstincts.cs deleted file mode 100644 index 45641f0a..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/ObfuscationInstincts.cs +++ /dev/null @@ -1,34 +0,0 @@ -namespace Obfuz -{ - public static class ObfuscationInstincts - { - /// - /// Returns the original full name before obfuscated of the type T - /// - /// - /// - public static string FullNameOf() - { - return typeof(T).FullName; - } - - /// - /// Returns the original name before obfuscated of the type T - /// - /// - /// - public static string NameOf() - { - return typeof(T).Name; - } - - /// - /// register original type name to type mapping. - /// - /// - public static void RegisterReflectionType() - { - ObfuscationTypeMapper.RegisterType(typeof(T).FullName); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/ObfuscationInstincts.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/ObfuscationInstincts.cs.meta deleted file mode 100644 index 48d653ff..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/ObfuscationInstincts.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 84320ab4adc4cbc49bf5e8f4009b4a96 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/ObfuscationTypeMapper.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/ObfuscationTypeMapper.cs deleted file mode 100644 index a85927ca..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/ObfuscationTypeMapper.cs +++ /dev/null @@ -1,72 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Reflection; - -namespace Obfuz -{ - public static class ObfuscationTypeMapper - { - private static readonly Dictionary _type2OriginalFullName = new Dictionary(); - private static readonly Dictionary> _originalFullName2Types = new Dictionary>(); - - internal static void RegisterType(string originalFullName) - { - RegisterType(typeof(T), originalFullName); - } - - internal static void RegisterType(Type type, string originalFullName) - { - if (_type2OriginalFullName.ContainsKey(type)) - { - throw new ArgumentException($"Type '{type.FullName}' is already registered with original name '{_type2OriginalFullName[type]}'."); - } - _type2OriginalFullName.Add(type, originalFullName); - Assembly assembly = type.Assembly; - if (!_originalFullName2Types.TryGetValue(assembly, out var originalFullName2Types)) - { - originalFullName2Types = new Dictionary(); - _originalFullName2Types[assembly] = originalFullName2Types; - } - if (originalFullName2Types.ContainsKey(originalFullName)) - { - throw new ArgumentException($"Original full name '{originalFullName}' is already registered with type '{originalFullName2Types[originalFullName].FullName}'."); - } - originalFullName2Types.Add(originalFullName, type); - } - - public static string GetOriginalTypeFullName(Type type) - { - return _type2OriginalFullName.TryGetValue(type, out string originalFullName) - ? originalFullName - : throw new KeyNotFoundException($"Type '{type.FullName}' not found in the obfuscation mapping."); - } - - public static string GetOriginalTypeFullNameOrCurrent(Type type) - { - if (_type2OriginalFullName.TryGetValue(type, out string originalFullName)) - { - return originalFullName; - } - return type.FullName; - } - - public static Type GetTypeByOriginalFullName(Assembly assembly, string originalFullName) - { - if (_originalFullName2Types.TryGetValue(assembly, out var n2t)) - { - if (n2t.TryGetValue(originalFullName, out Type type)) - { - return type; - } - } - return null; - } - - public static void Clear() - { - _type2OriginalFullName.Clear(); - _originalFullName2Types.Clear(); - } - } - -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/ObfuscationTypeMapper.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/ObfuscationTypeMapper.cs.meta deleted file mode 100644 index f496249d..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/ObfuscationTypeMapper.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: db6168acedd85984fa2c197fee1b0c15 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/Obfuz.Runtime.asmdef b/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/Obfuz.Runtime.asmdef deleted file mode 100644 index 4ee1d16d..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/Obfuz.Runtime.asmdef +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "Obfuz.Runtime", - "rootNamespace": "", - "references": [], - "includePlatforms": [], - "excludePlatforms": [], - "allowUnsafeCode": true, - "overrideReferences": false, - "precompiledReferences": [], - "autoReferenced": true, - "defineConstraints": [], - "versionDefines": [], - "noEngineReferences": false -} \ No newline at end of file diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/Obfuz.Runtime.asmdef.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/Obfuz.Runtime.asmdef.meta deleted file mode 100644 index 4868da27..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/Obfuz.Runtime.asmdef.meta +++ /dev/null @@ -1,7 +0,0 @@ -fileFormatVersion: 2 -guid: 4140bd2e2764f1f47ab93125ecb61942 -AssemblyDefinitionImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/ObfuzIgnoreAttribute.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/ObfuzIgnoreAttribute.cs deleted file mode 100644 index 4aac1b88..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/ObfuzIgnoreAttribute.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; - -namespace Obfuz -{ - - [AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = false)] - public class ObfuzIgnoreAttribute : Attribute - { - public ObfuzScope Scope { get; set; } - - public bool ApplyToNestedTypes { get; set; } = true; - - public bool ApplyToChildTypes { get; set; } = false; - - public ObfuzIgnoreAttribute(ObfuzScope scope = ObfuzScope.All) - { - this.Scope = scope; - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/ObfuzIgnoreAttribute.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/ObfuzIgnoreAttribute.cs.meta deleted file mode 100644 index bc8fb89b..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/ObfuzIgnoreAttribute.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: c2b4cf04729157b4dab504167ab5f703 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/ObfuzScope.cs b/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/ObfuzScope.cs deleted file mode 100644 index e3079900..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/ObfuzScope.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; - -namespace Obfuz -{ - [Flags] - public enum ObfuzScope - { - None = 0x0, - TypeName = 0x1, - Field = 0x2, - MethodName = 0x4, - MethodParameter = 0x8, - MethodBody = 0x10, - Method = MethodName | MethodParameter | MethodBody, - PropertyName = 0x20, - PropertyGetterSetterName = 0x40, - Property = PropertyName | PropertyGetterSetterName, - EventName = 0x100, - EventAddRemoveFireName = 0x200, - Event = EventName | PropertyGetterSetterName, - Module = 0x1000, - All = TypeName | Field | Method | Property | Event, - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/ObfuzScope.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/ObfuzScope.cs.meta deleted file mode 100644 index 1fec67df..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/Runtime/ObfuzScope.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 3c7e51fe12f206347b08a4b0be48605d -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/package.json b/UnityProject/Packages/com.code-philosophy.obfuz/package.json deleted file mode 100644 index 28a66a96..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/package.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "name": "com.code-philosophy.obfuz", - "version": "2.0.0", - "displayName": "Obfuz", - "description": "Obfuz is an open-source Unity code obfuscation tool designed to provide Unity developers with a powerful, secure, and user-friendly code protection solution.", - "category": "Scripting", - "documentationUrl": "https://www.obfuz.com", - "changelogUrl": "https://github.com/focus-creative-games/obfuz/commits/main/", - "licensesUrl": "https://github.com/focus-creative-games/obfuz/blob/main/com.code-philosophy.obfuz/LICENSE", - "keywords": [ - "obfuz", - "obfuscation", - "obfuscator", - "confuser", - "code-philosophy" - ], - "author": { - "name": "Code Philosophy", - "email": "obfuz@code-philosophy.com", - "url": "https://code-philosophy.com" - } -} \ No newline at end of file diff --git a/UnityProject/Packages/com.code-philosophy.obfuz/package.json.meta b/UnityProject/Packages/com.code-philosophy.obfuz/package.json.meta deleted file mode 100644 index 74168f7e..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz/package.json.meta +++ /dev/null @@ -1,7 +0,0 @@ -fileFormatVersion: 2 -guid: 63433d029d2e08c46abd56175e308a15 -PackageManifestImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Editor.meta b/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Editor.meta deleted file mode 100644 index ec942396..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Editor.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 067341936b8cb2242be3bdc83f3ca3cd -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Editor/ObfuscateUtil.cs b/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Editor/ObfuscateUtil.cs deleted file mode 100644 index c68a9237..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Editor/ObfuscateUtil.cs +++ /dev/null @@ -1,118 +0,0 @@ -using dnlib.DotNet; -using dnlib.DotNet.PolymorphicWriter; -using HybridCLR.Editor; -using Obfuz; -using Obfuz.Settings; -using Obfuz.Unity; -using System; -using System.Collections.Generic; -using System.IO; -using UnityEditor; -using UnityEngine; - -namespace Obfuz4HybridCLR -{ - public static class ObfuscateUtil - { - public static string PackageName { get; } = "com.code-philosophy.obfuz4hybridclr"; - - public static string TemplatePathInPackage => $"Packages/{PackageName}/Templates~"; - - public static bool AreSameDirectory(string path1, string path2) - { - try - { - var dir1 = new DirectoryInfo(path1); - var dir2 = new DirectoryInfo(path2); - - return dir1.FullName.TrimEnd('\\') == dir2.FullName.TrimEnd('\\'); - } - catch - { - return false; - } - } - - public static void ObfuscateHotUpdateAssemblies(BuildTarget target, string outputDir) - { - string hotUpdateDllPath = SettingsUtil.GetHotUpdateDllsOutputDirByTarget(target); - - AssemblySettings assemblySettings = ObfuzSettings.Instance.assemblySettings; - ObfuscationProcess.ValidateReferences(hotUpdateDllPath, new HashSet(assemblySettings.GetAssembliesToObfuscate()), new HashSet(assemblySettings.GetObfuscationRelativeAssemblyNames())); - var assemblySearchPaths = new List - { - hotUpdateDllPath, - }; - if (AreSameDirectory(hotUpdateDllPath, outputDir)) - { - throw new Exception($"hotUpdateDllPath:{hotUpdateDllPath} can't be same to outputDir:{outputDir}"); - } - Obfuscate(target, assemblySearchPaths, outputDir); - foreach (string hotUpdateAssemblyName in SettingsUtil.HotUpdateAssemblyNamesExcludePreserved) - { - string srcFile = $"{hotUpdateDllPath}/{hotUpdateAssemblyName}.dll"; - string dstFile = $"{outputDir}/{hotUpdateAssemblyName}.dll"; - // only copy non obfuscated assemblies - if (File.Exists(srcFile) && !File.Exists(dstFile)) - { - File.Copy(srcFile, dstFile, true); - Debug.Log($"[CompileAndObfuscateDll] Copy nonObfuscated assembly {srcFile} to {dstFile}"); - } - } - } - - public static void Obfuscate(BuildTarget target, List assemblySearchPaths, string obfuscatedAssemblyOutputPath) - { - var obfuzSettings = ObfuzSettings.Instance; - - var assemblySearchDirs = assemblySearchPaths; - ObfuscatorBuilder builder = ObfuscatorBuilder.FromObfuzSettings(obfuzSettings, target, true); - builder.InsertTopPriorityAssemblySearchPaths(assemblySearchDirs); - builder.CoreSettingsFacade.obfuscatedAssemblyOutputPath = obfuscatedAssemblyOutputPath; - - foreach (var assemblySearchDir in builder.CoreSettingsFacade.assemblySearchPaths) - { - if (AreSameDirectory(assemblySearchDir, obfuscatedAssemblyOutputPath)) - { - throw new Exception($"assemblySearchDir:{assemblySearchDir} can't be same to ObfuscatedAssemblyOutputPath:{obfuscatedAssemblyOutputPath}"); - } - } - - Obfuscator obfuz = builder.Build(); - obfuz.Run(); - } - - public static void GeneratePolymorphicDll(string originalDllPath, string outputDllPath) - { - ModuleDef oldMod = ModuleDefMD.Load(originalDllPath); - var obfuzSettings = ObfuzSettings.Instance; - - var opt = new NewDllModuleWriterOptions(oldMod) - { - MetadataWriter = new PolymorphicMetadataWriter(obfuzSettings.polymorphicDllSettings.codeGenerationSecretKey), - }; - PolymorphicModuleWriter writer = new PolymorphicModuleWriter(oldMod, opt); - writer.Write(outputDllPath); - Debug.Log($"GeneratePolymorphicDll {originalDllPath} => {outputDllPath}"); - } - - public static void GeneratePolymorphicCodes(string libil2cppDir) - { - PolymorphicDllSettings settings = ObfuzSettings.Instance.polymorphicDllSettings; - if (!settings.enable) - { - UnityEngine.Debug.LogWarning("Polymorphic code generation is disabled in Obfuz settings."); - return; - } - var options = new PolymorphicCodeGenerator.Options - { - GenerationSecretKey = settings.codeGenerationSecretKey, - Libil2cppDir = libil2cppDir, - TemplateDir = ObfuscateUtil.TemplatePathInPackage, - DisableLoadStandardDll = settings.disableLoadStandardDll, - }; - var generator = new PolymorphicCodeGenerator(options); - generator.Generate(); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Editor/ObfuscateUtil.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Editor/ObfuscateUtil.cs.meta deleted file mode 100644 index 3702fddd..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Editor/ObfuscateUtil.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: b7f5fe18513bcdd4c8960d908e88402e -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Editor/Obfuz4HybridCLR.asmdef b/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Editor/Obfuz4HybridCLR.asmdef deleted file mode 100644 index 2af5cd54..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Editor/Obfuz4HybridCLR.asmdef +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "Obfuz4HybridCLR.Editor", - "rootNamespace": "", - "references": [ - "GUID:2373f786d14518f44b0f475db77ba4de", - "GUID:66e09fc524ec6594b8d6ca1d91aa1a41" - ], - "includePlatforms": [ - "Editor" - ], - "excludePlatforms": [], - "allowUnsafeCode": false, - "overrideReferences": false, - "precompiledReferences": [], - "autoReferenced": true, - "defineConstraints": [], - "versionDefines": [], - "noEngineReferences": false -} \ No newline at end of file diff --git a/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Editor/Obfuz4HybridCLR.asmdef.meta b/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Editor/Obfuz4HybridCLR.asmdef.meta deleted file mode 100644 index cc375a6e..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Editor/Obfuz4HybridCLR.asmdef.meta +++ /dev/null @@ -1,7 +0,0 @@ -fileFormatVersion: 2 -guid: 3743e71edcd5bd8499007797ef02cbfb -AssemblyDefinitionImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Editor/Polymorphic.meta b/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Editor/Polymorphic.meta deleted file mode 100644 index 6a8a5899..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Editor/Polymorphic.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 52d353fb8d6d94c4aa03452a2cd9773f -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Editor/Polymorphic/PolymorphicCodeGenerator.cs b/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Editor/Polymorphic/PolymorphicCodeGenerator.cs deleted file mode 100644 index 23d9c225..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Editor/Polymorphic/PolymorphicCodeGenerator.cs +++ /dev/null @@ -1,224 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using dnlib.DotNet.PolymorphicWriter; -using HybridCLR.Editor.Template; - -public class PolymorphicCodeGenerator -{ - public class Options - { - public string GenerationSecretKey { get; set; } - - public string Libil2cppDir { get; set; } - - public string TemplateDir { get; set; } - - public bool DisableLoadStandardDll { get; set; } = true; - } - - private readonly string _libil2cppDir; - private readonly string _metadataDir; - private readonly string _templateDir; - - private readonly string _generationSecretKey; - private readonly bool _disableLoadStandardImage; - - private readonly PolymorphicMetadataWriter writer; - - public PolymorphicCodeGenerator(Options options) - { - _libil2cppDir = options.Libil2cppDir; - _metadataDir = Path.Combine(_libil2cppDir, "hybridclr", "metadata"); - _templateDir = options.TemplateDir; - - _generationSecretKey = options.GenerationSecretKey; - _disableLoadStandardImage = options.DisableLoadStandardDll; - - writer = new PolymorphicMetadataWriter(_generationSecretKey); - } - - private void CopyMetadataReaderHeader() - { - string srcFile = $"{_templateDir}/MetadataReader.h.tpl"; - string dstFile = $"{_metadataDir}/MetadataReader.h"; - File.Copy(srcFile, dstFile, true); - UnityEngine.Debug.Log($"Copy MetadataReader header from {srcFile} to {dstFile}"); - } - - private void GeneratePolymorphicDefs() - { - string tplFile = $"{_templateDir}/PolymorphicDefs.h.tpl"; - var frr = new FileRegionReplace(File.ReadAllText(tplFile, Encoding.UTF8)); - var lines = new List(); - lines.Add($"#define POLYMORPHIC_IMAGE_SIGNATURE \"{writer.ImageSignature}\""); - lines.Add($"\tconstexpr uint32_t kPolymorphicImageVersion = {writer.FormatVersion};"); - lines.Add($"\tconstexpr uint32_t kFormatVariantVersion = {writer.FormatVariant};"); - string codes = string.Join("\n", lines); - frr.Replace("POLYMORPHIC_DEFINES", codes); - - string outputFile = $"{_metadataDir}/PolymorphicDefs.h"; - frr.Commit(outputFile); - } - - private void GeneratePolymorphicDatas() - { - string tplFile = $"{_templateDir}/PolymorphicDatas.h.tpl"; - var frr = new FileRegionReplace(File.ReadAllText(tplFile, Encoding.UTF8)); - List lines = new List(); - var sb = new StringBuilder(); - foreach (var type in writer.GetPolymorphicTypes()) - { - var polymorphicType = writer.GetPolymorphicClassDef(type); - lines.Add($"\tstruct {type.Name}"); - lines.Add("\t{"); - foreach (var field in polymorphicType.Fields) - { - lines.Add($"\t\t{field.fieldWriter.CppTypeName} {field.name};"); - } - - lines.Add("\t\tvoid Read(MetadataReader& reader)"); - lines.Add("\t\t{"); - - foreach (var field in polymorphicType.Fields) - { - lines.Add($"\t\t\t{field.fieldWriter.GetMarshalCode(field.name, "reader")};"); - } - lines.Add("\t\t}"); - lines.Add("\t};"); - lines.Add(""); - } - - string codes = string.Join("\n", lines); - frr.Replace("POLYMORPHIC_DATA", codes); - - - string outputFile = $"{_metadataDir}/PolymorphicDatas.h"; - frr.Commit(outputFile); - } - - private void GeneratePolymorphicRawImageHeader() - { - string tplFile = $"{_templateDir}/PolymorphicRawImage.h.tpl"; - var frr = new FileRegionReplace(File.ReadAllText(tplFile, Encoding.UTF8)); - - - var tableMetaInfoMap = TableMetaInfos.tableMetaInfos.ToDictionary(t => "Raw" + t.csharpTypeName + "Row"); - List lines = new List(); - foreach (Type rowType in writer.GetPolymorphicTableRowTypes()) - { - TableMetaInfo table = tableMetaInfoMap[rowType.Name]; - - lines.Add($"\t\tvirtual Tb{table.cppTypeName} Read{table.cppTypeName}(uint32_t rawIndex) override;"); - } - - frr.Replace("READ_TABLES_OVERRIDES", string.Join("\n", lines)); - - string outputFile = $"{_metadataDir}/PolymorphicRawImage.h"; - frr.Commit(outputFile); - } - - private void GeneratePolymorphicRawImageSource() - { - string tplFile = $"{_templateDir}/PolymorphicRawImage.cpp.tpl"; - var frr = new FileRegionReplace(File.ReadAllText(tplFile, Encoding.UTF8)); - - var tableMetaInfoMap = TableMetaInfos.tableMetaInfos.ToDictionary(t => "Raw" + t.csharpTypeName + "Row"); - { - List lines = new List(); - - foreach (Type rowType in writer.GetAllTableRowTypes()) - { - TableMetaInfo table = tableMetaInfoMap[rowType.Name]; - PolymorphicClassDef polymorphicClassDef = writer.CreateTableRowClassDefForCodeGeneration(rowType); - lines.Add("\t\t{"); - lines.Add($"\t\t\tauto& table = _tableRowMetas[(int)TableType::{table.cppEnumName}];"); - foreach (var fieldDef in polymorphicClassDef.Fields) - { - FieldMetaInfo field = table.fields.First(f => f.csharpName == fieldDef.name); - lines.Add($"\t\t\ttable.push_back({{{field.cppRowSize}}});"); - } - lines.Add("\t\t}"); - } - string codes = string.Join("\n", lines); - frr.Replace("TABLE_ROW_METADS", codes); - } - { - List lines = new List(); - foreach (Type rowType in writer.GetPolymorphicTableRowTypes()) - { - TableMetaInfo table = tableMetaInfoMap[rowType.Name]; - PolymorphicClassDef polymorphicClassDef = writer.CreateTableRowClassDefForCodeGeneration(rowType); - - lines.Add($"\tTb{table.cppTypeName} PolymorphicRawImage::Read{table.cppTypeName}(uint32_t rawIndex)"); - lines.Add("\t{"); - lines.Add($"\t\tIL2CPP_ASSERT(rawIndex > 0 && rawIndex <= GetTable(TableType::{table.cppEnumName}).rowNum);"); - lines.Add($"\t\tconst byte* rowPtr = GetTableRowPtr(TableType::{table.cppEnumName}, rawIndex);"); - lines.Add($"\t\tauto& rowSchema = GetRowSchema(TableType::{table.cppEnumName});"); - lines.Add($"\t\tTb{table.cppTypeName} data;"); - for (int i = 0; i < polymorphicClassDef.Fields.Count; i++) - { - var fieldDef = polymorphicClassDef.Fields[i]; - FieldMetaInfo field = table.fields.First(f => f.csharpName == fieldDef.name); - lines.Add($"\t\tdata.{field.cppName} = ReadColumn(rowPtr, rowSchema[{i}]);"); - } - lines.Add("\t\treturn data;"); - lines.Add("\t}"); - } - - frr.Replace("READ_TABLES_IMPLEMENTATIONS", string.Join("\n", lines)); - } - string outputFile = $"{_metadataDir}/PolymorphicRawImage.cpp"; - frr.Commit(outputFile); - } - - private void GenerateRawImageInit() - { - string tplFile = $"{_metadataDir}/Image.cpp"; - var frr = new FileRegionReplace(File.ReadAllText(tplFile, Encoding.UTF8)); - - { - List lines = new List(); - lines.Add(@"#include ""PolymorphicRawImage.h"""); - - frr.Replace("INCLUDE_RAW_IMAGE_HEADERS", string.Join("\n", lines)); - } - { - List lines = new List(); - - lines.Add("\t\tif (std::strncmp((const char*)imageData, \"CODEPHPY\", 8) == 0)"); - lines.Add("\t\t{"); - lines.Add("\t\t\t_rawImage = new PolymorphicRawImage();"); - lines.Add("\t\t}"); - lines.Add("\t\telse"); - lines.Add("\t\t{"); - if (_disableLoadStandardImage) - { - lines.Add("\t\t\treturn LoadImageErrorCode::UNKNOWN_IMAGE_FORMAT;"); - } - else - { - lines.Add("\t\t\t_rawImage = new RawImage();"); - } - lines.Add("\t\t}"); - lines.Add("\t\treturn LoadImageErrorCode::OK;"); - - frr.Replace("INIT_RAW_IMAGE", string.Join("\n", lines)); - } - - - frr.Commit(tplFile); - } - - public void Generate() - { - CopyMetadataReaderHeader(); - GeneratePolymorphicDefs(); - GeneratePolymorphicDatas(); - GeneratePolymorphicRawImageHeader(); - GeneratePolymorphicRawImageSource(); - GenerateRawImageInit(); - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Editor/Polymorphic/PolymorphicCodeGenerator.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Editor/Polymorphic/PolymorphicCodeGenerator.cs.meta deleted file mode 100644 index 6d7baece..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Editor/Polymorphic/PolymorphicCodeGenerator.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: b66b21680bfc8744682ea6536aa2ec77 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Editor/Polymorphic/TableMetaInfos.cs b/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Editor/Polymorphic/TableMetaInfos.cs deleted file mode 100644 index 440cb7b8..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Editor/Polymorphic/TableMetaInfos.cs +++ /dev/null @@ -1,300 +0,0 @@ -using System.Collections.Generic; - -class FieldMetaInfo { - public readonly string csharpName; - public readonly string cppName; - public readonly string cppRowSize; - public FieldMetaInfo(string csharpName, string cppName, string cppRowSize) { - this.csharpName = csharpName; - this.cppName = cppName; - this.cppRowSize = cppRowSize; - } - - public FieldMetaInfo(string csharpName, string cppRowSize) : this(csharpName, csharpName.Substring(0, 1).ToLower() + csharpName.Substring(1), cppRowSize) { - } -} - -class TableMetaInfo { - public readonly string csharpTypeName; - public readonly string cppTypeName; - public readonly string cppEnumName; - public readonly List fields; - - public TableMetaInfo(string csharpTypeName, string cppTypeName, string cppEnumName, List fields) { - this.csharpTypeName = csharpTypeName; - this.cppTypeName = cppTypeName; - this.cppEnumName = cppEnumName; - this.fields = fields; - } - - - public TableMetaInfo(string csharpTypeName, List fields) : this(csharpTypeName, csharpTypeName, csharpTypeName.ToUpper(), fields) { - } -} - -class TableMetaInfos { - public static readonly List tableMetaInfos = new List { - new TableMetaInfo("Module", new List { - new FieldMetaInfo("Generation", "2"), - new FieldMetaInfo("Name", "ComputStringIndexByte()"), - new FieldMetaInfo("Mvid", "ComputGUIDIndexByte()"), - new FieldMetaInfo("EncId", "ComputGUIDIndexByte()"), - new FieldMetaInfo("EncBaseId", "ComputGUIDIndexByte()"), - }), - new TableMetaInfo("TypeRef", new List { - new FieldMetaInfo("ResolutionScope", "ComputTableIndexByte(TableType::MODULE, TableType::MODULEREF, TableType::ASSEMBLYREF, TableType::TYPEREF, TagBits::ResoulutionScope)"), - new FieldMetaInfo("Name", "typeName", "ComputStringIndexByte()"), - new FieldMetaInfo("Namespace", "typeNamespace", "ComputStringIndexByte()"), - }), - new TableMetaInfo("TypeDef", new List { - new FieldMetaInfo("Flags", "4"), - new FieldMetaInfo("Name", "typeName", "ComputStringIndexByte()"), - new FieldMetaInfo("Namespace", "typeNamespace", "ComputStringIndexByte()"), - new FieldMetaInfo("Extends", "ComputTableIndexByte(TableType::TYPEDEF, TableType::TYPEREF, TableType::TYPESPEC, TagBits::TypeDefOrRef)"), - new FieldMetaInfo("FieldList", "ComputTableIndexByte(TableType::FIELD)"), - new FieldMetaInfo("MethodList", "ComputTableIndexByte(TableType::METHOD)"), - }), - new TableMetaInfo("FieldPtr", new List { - new FieldMetaInfo("Field", "ComputTableIndexByte(TableType::FIELD)"), - }), - new TableMetaInfo("Field", new List { - new FieldMetaInfo("Flags", "2"), - new FieldMetaInfo("Name", "ComputStringIndexByte()"), - new FieldMetaInfo("Signature", "ComputBlobIndexByte()"), - }), - new TableMetaInfo("MethodPtr", new List { - new FieldMetaInfo("Method", "ComputTableIndexByte(TableType::METHOD)"), - }), - new TableMetaInfo("Method", new List { - new FieldMetaInfo("RVA", "rva", "4"), - new FieldMetaInfo("ImplFlags", "2"), - new FieldMetaInfo("Flags", "2"), - new FieldMetaInfo("Name", "ComputStringIndexByte()"), - new FieldMetaInfo("Signature", "ComputBlobIndexByte()"), - new FieldMetaInfo("ParamList", "ComputTableIndexByte(TableType::PARAM)"), - }), - new TableMetaInfo("ParamPtr", new List { - new FieldMetaInfo("Param", "ComputTableIndexByte(TableType::PARAM)"), - }), - new TableMetaInfo("Param", new List { - new FieldMetaInfo("Flags", "2"), - new FieldMetaInfo("Sequence", "2"), - new FieldMetaInfo("Name", "ComputStringIndexByte()"), - }), - new TableMetaInfo("InterfaceImpl", new List { - new FieldMetaInfo("Class", "classIdx", "ComputTableIndexByte(TableType::TYPEDEF)"), - new FieldMetaInfo("Interface", "interfaceIdx", "ComputTableIndexByte(TableType::TYPEDEF, TableType::TYPEREF, TableType::TYPESPEC, TagBits::TypeDefOrRef)"), - }), - new TableMetaInfo("MemberRef", new List { - new FieldMetaInfo("Class", "classIdx", "ComputTableIndexByte(TableType::METHOD, TableType::MODULEREF, TableType::TYPEDEF, TableType::TYPEREF, TagBits::MemberRefParent)"), - new FieldMetaInfo("Name", "ComputStringIndexByte()"), - new FieldMetaInfo("Signature", "ComputBlobIndexByte()"), - }), - new TableMetaInfo("Constant", new List { - new FieldMetaInfo("Type", "1"), - new FieldMetaInfo("Padding", "1"), - new FieldMetaInfo("Parent", "ComputTableIndexByte(TableType::PARAM, TableType::FIELD, TableType::PROPERTY, TagBits::HasConstant)"), - new FieldMetaInfo("Value", "ComputBlobIndexByte()"), - }), - new TableMetaInfo("CustomAttribute", new List { - new FieldMetaInfo("Parent", "ComputTableIndexByte(HasCustomAttributeAssociateTables, sizeof(HasCustomAttributeAssociateTables) / sizeof(TableType), TagBits::HasCustomAttribute)"), - new FieldMetaInfo("Type", "ComputTableIndexByte(TableType::METHOD, TableType::MEMBERREF, TagBits::CustomAttributeType)"), - new FieldMetaInfo("Value", "ComputBlobIndexByte()"), - }), - new TableMetaInfo("FieldMarshal", new List { - new FieldMetaInfo("Parent", "ComputTableIndexByte(TableType::FIELD, TableType::PARAM, TagBits::HasFieldMarshal)"), - new FieldMetaInfo("NativeType", "ComputBlobIndexByte()"), - }), - new TableMetaInfo("DeclSecurity", new List { - new FieldMetaInfo("Action", "2"), - new FieldMetaInfo("Parent", "ComputTableIndexByte(TableType::TYPEDEF, TableType::METHOD, TableType::ASSEMBLY, TagBits::HasDeclSecurity)"), - new FieldMetaInfo("PermissionSet", "ComputBlobIndexByte()"), - }), - new TableMetaInfo("ClassLayout", new List { - new FieldMetaInfo("PackingSize", "2"), - new FieldMetaInfo("ClassSize", "4"), - new FieldMetaInfo("Parent", "ComputTableIndexByte(TableType::TYPEDEF)"), - }), - new TableMetaInfo("FieldLayout", new List { - new FieldMetaInfo("OffSet", "offset", "4"), - new FieldMetaInfo("Field", "ComputTableIndexByte(TableType::FIELD)"), - }), - new TableMetaInfo("StandAloneSig", new List { - new FieldMetaInfo("Signature", "ComputBlobIndexByte()"), - }), - new TableMetaInfo("EventMap", new List { - new FieldMetaInfo("Parent", "ComputTableIndexByte(TableType::TYPEDEF)"), - new FieldMetaInfo("EventList", "ComputTableIndexByte(TableType::EVENT)"), - }), - new TableMetaInfo("EventPtr", new List { - new FieldMetaInfo("Event", "ComputTableIndexByte(TableType::EVENT)"), - }), - new TableMetaInfo("Event", new List { - new FieldMetaInfo("EventFlags", "2"), - new FieldMetaInfo("Name", "ComputStringIndexByte()"), - new FieldMetaInfo("EventType", "ComputTableIndexByte(TableType::TYPEDEF, TableType::TYPEREF, TableType::TYPESPEC, TagBits::TypeDefOrRef)"), - }), - new TableMetaInfo("PropertyMap", new List { - new FieldMetaInfo("Parent", "ComputTableIndexByte(TableType::TYPEDEF)"), - new FieldMetaInfo("PropertyList", "ComputTableIndexByte(TableType::PROPERTY)"), - }), - new TableMetaInfo("PropertyPtr", new List { - new FieldMetaInfo("Property", "ComputTableIndexByte(TableType::PROPERTY)"), - }), - new TableMetaInfo("Property", new List { - new FieldMetaInfo("PropFlags", "flags", "2"), - new FieldMetaInfo("Name", "ComputStringIndexByte()"), - new FieldMetaInfo("Type", "ComputBlobIndexByte()"), - }), - new TableMetaInfo("MethodSemantics", new List { - new FieldMetaInfo("Semantic", "semantics", "2"), - new FieldMetaInfo("Method", "ComputTableIndexByte(TableType::METHOD)"), - new FieldMetaInfo("Association", "ComputTableIndexByte(TableType::EVENT, TableType::PROPERTY, TagBits::HasSemantics)"), - }), - new TableMetaInfo("MethodImpl", new List { - new FieldMetaInfo("Class", "classIdx", "ComputTableIndexByte(TableType::TYPEDEF)"), - new FieldMetaInfo("MethodBody", "ComputTableIndexByte(TableType::METHOD, TableType::MEMBERREF, TagBits::MethodDefOrRef)"), - new FieldMetaInfo("MethodDeclaration", "ComputTableIndexByte(TableType::METHOD, TableType::MEMBERREF, TagBits::MethodDefOrRef)"), - }), - new TableMetaInfo("ModuleRef", new List { - new FieldMetaInfo("Name", "ComputStringIndexByte()"), - }), - new TableMetaInfo("TypeSpec", new List { - new FieldMetaInfo("Signature", "ComputBlobIndexByte()"), - }), - new TableMetaInfo("ImplMap", new List { - new FieldMetaInfo("MappingFlags", "2"), - new FieldMetaInfo("MemberForwarded", "ComputTableIndexByte(TableType::FIELD, TableType::METHOD, TagBits::MemberForwarded)"), - new FieldMetaInfo("ImportName", "ComputStringIndexByte()"), - new FieldMetaInfo("ImportScope", "ComputTableIndexByte(TableType::MODULEREF)"), - }), - new TableMetaInfo("FieldRVA", new List { - new FieldMetaInfo("RVA", "rva", "4"), - new FieldMetaInfo("Field", "ComputTableIndexByte(TableType::FIELD)"), - }), - new TableMetaInfo("ENCLog","EncLog", "ENCLOG", new List { - new FieldMetaInfo("Token", "4"), - new FieldMetaInfo("FuncCode", "4"), - }), - new TableMetaInfo("ENCMap", "EncMap", "ENCMAP", new List { - new FieldMetaInfo("Token", "4"), - }), - new TableMetaInfo("Assembly", new List { - new FieldMetaInfo("HashAlgId", "4"), - new FieldMetaInfo("MajorVersion", "2"), - new FieldMetaInfo("MinorVersion", "2"), - new FieldMetaInfo("BuildNumber", "2"), - new FieldMetaInfo("RevisionNumber", "2"), - new FieldMetaInfo("Flags", "4"), - new FieldMetaInfo("PublicKey", "ComputBlobIndexByte()"), - new FieldMetaInfo("Name", "ComputStringIndexByte()"), - new FieldMetaInfo("Locale", "ComputStringIndexByte()"), - }), - new TableMetaInfo("AssemblyProcessor", new List { - new FieldMetaInfo("Processor", "4"), - }), - new TableMetaInfo("AssemblyOS", new List { - new FieldMetaInfo("OSPlatformId", "osPlatformId", "4"), - new FieldMetaInfo("OSMajorVersion", "osMajorVersion", "4"), - new FieldMetaInfo("OSMinorVersion", "osMinorVersion", "4"), - }), - new TableMetaInfo("AssemblyRef", new List { - new FieldMetaInfo("MajorVersion", "2"), - new FieldMetaInfo("MinorVersion", "2"), - new FieldMetaInfo("BuildNumber", "2"), - new FieldMetaInfo("RevisionNumber", "2"), - new FieldMetaInfo("Flags", "4"), - new FieldMetaInfo("PublicKeyOrToken", "ComputBlobIndexByte()"), - new FieldMetaInfo("Name", "ComputStringIndexByte()"), - new FieldMetaInfo("Locale", "ComputStringIndexByte()"), - new FieldMetaInfo("HashValue", "ComputBlobIndexByte()"), - }), - new TableMetaInfo("AssemblyRefProcessor", new List { - new FieldMetaInfo("AssemblyRef", "4"), - new FieldMetaInfo("Processor", "ComputTableIndexByte(TableType::ASSEMBLYREF)"), - }), - new TableMetaInfo("AssemblyRefOS", new List { - new FieldMetaInfo("OSPlatformId", "osPlatformId", "4"), - new FieldMetaInfo("OSMajorVersion", "osMajorVersion", "4"), - new FieldMetaInfo("OSMinorVersion", "osMinorVersion", "4"), - new FieldMetaInfo("AssemblyRef", "ComputTableIndexByte(TableType::ASSEMBLYREF)"), - }), - new TableMetaInfo("File", new List { - new FieldMetaInfo("Flags", "4"), - new FieldMetaInfo("Name", "ComputStringIndexByte()"), - new FieldMetaInfo("HashValue", "ComputBlobIndexByte()"), - }), - new TableMetaInfo("ExportedType", new List { - new FieldMetaInfo("Flags", "4"), - new FieldMetaInfo("TypeDefId", "4"), - new FieldMetaInfo("TypeName", "ComputStringIndexByte()"), - new FieldMetaInfo("TypeNamespace", "ComputStringIndexByte()"), - new FieldMetaInfo("Implementation", "ComputTableIndexByte(TableType::FILE, TableType::EXPORTEDTYPE, TableType::ASSEMBLY, TagBits::Implementation)"), - }), - new TableMetaInfo("ManifestResource", new List { - new FieldMetaInfo("Offset", "4"), - new FieldMetaInfo("Flags", "4"), - new FieldMetaInfo("Name", "ComputStringIndexByte()"), - new FieldMetaInfo("Implementation", "ComputTableIndexByte(TableType::FILE, TableType::ASSEMBLYREF, TagBits::Implementation)"), - }), - new TableMetaInfo("NestedClass", new List { - new FieldMetaInfo("NestedClass", "ComputTableIndexByte(TableType::TYPEDEF)"), - new FieldMetaInfo("EnclosingClass", "ComputTableIndexByte(TableType::TYPEDEF)"), - }), - new TableMetaInfo("GenericParam", new List { - new FieldMetaInfo("Number", "2"), - new FieldMetaInfo("Flags", "2"), - new FieldMetaInfo("Owner", "ComputTableIndexByte(TableType::TYPEDEF, TableType::METHOD, TagBits::TypeOrMethodDef)"), - new FieldMetaInfo("Name", "ComputStringIndexByte()"), - }), - new TableMetaInfo("MethodSpec", new List { - new FieldMetaInfo("Method", "ComputTableIndexByte(TableType::METHOD, TableType::MEMBERREF, TagBits::MethodDefOrRef)"), - new FieldMetaInfo("Instantiation", "ComputBlobIndexByte()"), - }), - new TableMetaInfo("GenericParamConstraint", new List { - new FieldMetaInfo("Owner", "ComputTableIndexByte(TableType::GENERICPARAM)"), - new FieldMetaInfo("Constraint", "ComputTableIndexByte(TableType::TYPEDEF, TableType::TYPEREF, TableType::TYPESPEC, TagBits::TypeDefOrRef)"), - }), - - new TableMetaInfo("Document", new List { - new FieldMetaInfo("Name", "ComputBlobIndexByte()"), - new FieldMetaInfo("HashAlgorithm", "ComputGUIDIndexByte()"), - new FieldMetaInfo("Hash", "ComputBlobIndexByte()"), - new FieldMetaInfo("Language", "ComputGUIDIndexByte()"), - }), - new TableMetaInfo("MethodDebugInformation", new List { - new FieldMetaInfo("Document", "ComputTableIndexByte(TableType::DOCUMENT)"), - new FieldMetaInfo("SequencePoints", "ComputBlobIndexByte()"), - }), - new TableMetaInfo("LocalScope", new List { - new FieldMetaInfo("Method", "ComputTableIndexByte(TableType::METHOD)"), - new FieldMetaInfo("ImportScope", "ComputTableIndexByte(TableType::IMPORTSCOPE)"), - new FieldMetaInfo("VariableList", "variables", "ComputTableIndexByte(TableType::LOCALVARIABLE)"), - new FieldMetaInfo("ConstantList", "constants", "ComputTableIndexByte(TableType::LOCALCONSTANT)"), - new FieldMetaInfo("StartOffset", "4"), - new FieldMetaInfo("Length", "4"), - }), - new TableMetaInfo("LocalVariable", new List { - new FieldMetaInfo("Attributes", "2"), - new FieldMetaInfo("Index", "2"), - new FieldMetaInfo("Name", "ComputStringIndexByte()"), - }), - new TableMetaInfo("LocalConstant", new List { - new FieldMetaInfo("Name", "ComputStringIndexByte()"), - new FieldMetaInfo("Signature", "ComputBlobIndexByte()"), - }), - new TableMetaInfo("ImportScope", new List { - new FieldMetaInfo("Parent", "ComputTableIndexByte(TableType::IMPORTSCOPE)"), - new FieldMetaInfo("Imports", "ComputBlobIndexByte()"), - }), - new TableMetaInfo("StateMachineMethod", new List { - new FieldMetaInfo("MoveNextMethod", "ComputTableIndexByte(TableType::METHOD)"), - new FieldMetaInfo("KickoffMethod", "ComputTableIndexByte(TableType::METHOD)"), - }), - new TableMetaInfo("CustomDebugInformation", new List { - new FieldMetaInfo("Parent", "ComputTableIndexByte(HasCustomDebugInformation, sizeof(HasCustomDebugInformation) / sizeof(TableType), TagBits::HasCustomDebugInformation)"), - new FieldMetaInfo("Kind", "ComputGUIDIndexByte()"), - new FieldMetaInfo("Value", "ComputBlobIndexByte()"), - }), - }; -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Editor/Polymorphic/TableMetaInfos.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Editor/Polymorphic/TableMetaInfos.cs.meta deleted file mode 100644 index a3a2a88f..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Editor/Polymorphic/TableMetaInfos.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ef98af767d086bd428f52503188789b1 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Editor/PrebuildCommandExt.cs b/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Editor/PrebuildCommandExt.cs deleted file mode 100644 index 85ce25b5..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Editor/PrebuildCommandExt.cs +++ /dev/null @@ -1,164 +0,0 @@ -using HybridCLR.Editor.Commands; -using HybridCLR.Editor; -using Obfuz.Settings; -using Obfuz; -using System.Collections; -using System.Collections.Generic; -using UnityEditor; -using UnityEngine; -using System.Reflection; -using System; -using System.IO; -using HybridCLR.Editor.Link; -using HybridCLR.Editor.Meta; -using UnityEditor.Build; -using HybridCLR.Editor.Installer; -using HybridCLR.Editor.MethodBridge; -using System.Linq; -using Analyzer = HybridCLR.Editor.MethodBridge.Analyzer; -using HybridCLR.Editor.Settings; -using Obfuz.Utils; -using FileUtil = Obfuz.Utils.FileUtil; -using IAssemblyResolver = HybridCLR.Editor.Meta.IAssemblyResolver; -using CombinedAssemblyResolver = HybridCLR.Editor.Meta.CombinedAssemblyResolver; -using MetaUtil = HybridCLR.Editor.Meta.MetaUtil; -using AssemblyCache = HybridCLR.Editor.Meta.AssemblyCache; -using HybridCLR.Editor.AOT; -using Analyzer2 = HybridCLR.Editor.AOT.Analyzer; - -namespace Obfuz4HybridCLR -{ - public static class PrebuildCommandExt - { - public static string GetObfuscatedHotUpdateAssemblyOutputPath(BuildTarget target) - { - return $"{ObfuzSettings.Instance.ObfuzRootDir}/{target}/ObfuscatedHotUpdateAssemblies"; - } - - - [MenuItem("HybridCLR/ObfuzExtension/GenerateAll")] - public static void GenerateAll() - { - var installer = new InstallerController(); - if (!installer.HasInstalledHybridCLR()) - { - throw new BuildFailedException($"You have not initialized HybridCLR, please install it via menu 'HybridCLR/Installer'"); - } - BuildTarget target = EditorUserBuildSettings.activeBuildTarget; - CompileDllCommand.CompileDll(target); - Il2CppDefGeneratorCommand.GenerateIl2CppDef(); - GeneratePolymorphicCodesWhenEnable(); - LinkGeneratorCommand.GenerateLinkXml(target); - StripAOTDllCommand.GenerateStripedAOTDlls(target); - - string obfuscatedHotUpdateDllPath = GetObfuscatedHotUpdateAssemblyOutputPath(target); - ObfuscateUtil.ObfuscateHotUpdateAssemblies(target, obfuscatedHotUpdateDllPath); - GenerateMethodBridgeAndReversePInvokeWrapper(target, obfuscatedHotUpdateDllPath); - GenerateAOTGenericReference(target, obfuscatedHotUpdateDllPath); - } - - [MenuItem("HybridCLR/ObfuzExtension/CompileAndObfuscateDll")] - public static void CompileAndObfuscateDll() - { - BuildTarget target = EditorUserBuildSettings.activeBuildTarget; - CompileDllCommand.CompileDll(target); - - string obfuscatedHotUpdateDllPath = GetObfuscatedHotUpdateAssemblyOutputPath(target); - ObfuscateUtil.ObfuscateHotUpdateAssemblies(target, obfuscatedHotUpdateDllPath); - } - - [MenuItem("HybridCLR/ObfuzExtension/GeneratePolymorphicCodes")] - public static void GeneratePolymorphicCodes() - { - ObfuscateUtil.GeneratePolymorphicCodes($"{SettingsUtil.LocalIl2CppDir}/libil2cpp"); - } - - private static void GeneratePolymorphicCodesWhenEnable() - { - PolymorphicDllSettings settings = ObfuzSettings.Instance.polymorphicDllSettings; - if (!settings.enable) - { - UnityEngine.Debug.LogWarning("Polymorphic code generation is disabled."); - return; - } - GeneratePolymorphicCodes(); - } - - public static IAssemblyResolver CreateObfuscatedHotUpdateAssemblyResolver(BuildTarget target, List obfuscatedHotUpdateAssemblies, string obfuscatedHotUpdateDllPath) - { - return new FixedSetAssemblyResolver(obfuscatedHotUpdateDllPath, obfuscatedHotUpdateAssemblies); - } - - public static IAssemblyResolver CreateObfuscatedHotUpdateAndAOTAssemblyResolver(BuildTarget target, List hotUpdateAssemblies, List assembliesToObfuscate, string obfuscatedHotUpdateDllPath) - { - return new CombinedAssemblyResolver( - CreateObfuscatedHotUpdateAssemblyResolver(target, hotUpdateAssemblies.Intersect(assembliesToObfuscate).ToList(), obfuscatedHotUpdateDllPath), - MetaUtil.CreateHotUpdateAssemblyResolver(target, hotUpdateAssemblies.Except(assembliesToObfuscate).ToList()), - MetaUtil.CreateAOTAssemblyResolver(target) - ); - } - - public static void GenerateMethodBridgeAndReversePInvokeWrapper(BuildTarget target, string obfuscatedHotUpdateDllPath) - { - string aotDllDir = SettingsUtil.GetAssembliesPostIl2CppStripDir(target); - List aotAssemblyNames = Directory.Exists(aotDllDir) ? - Directory.GetFiles(aotDllDir, "*.dll", SearchOption.TopDirectoryOnly).Select(Path.GetFileNameWithoutExtension).ToList() - : new List(); - if (aotAssemblyNames.Count == 0) - { - throw new Exception($"no aot assembly found. please run `HybridCLR/Generate/All` or `HybridCLR/Generate/AotDlls` to generate aot dlls before runing `HybridCLR/Generate/MethodBridge`"); - } - AssemblyReferenceDeepCollector collector = new AssemblyReferenceDeepCollector(MetaUtil.CreateAOTAssemblyResolver(target), aotAssemblyNames); - - var methodBridgeAnalyzer = new Analyzer(new Analyzer.Options - { - MaxIterationCount = Math.Min(20, SettingsUtil.HybridCLRSettings.maxMethodBridgeGenericIteration), - Collector = collector, - }); - - methodBridgeAnalyzer.Run(); - - List hotUpdateDlls = SettingsUtil.HotUpdateAssemblyNamesExcludePreserved; - var cache = new AssemblyCache(CreateObfuscatedHotUpdateAndAOTAssemblyResolver(target, hotUpdateDlls, ObfuzSettings.Instance.assemblySettings.GetAssembliesToObfuscate(), obfuscatedHotUpdateDllPath)); - - var reversePInvokeAnalyzer = new MonoPInvokeCallbackAnalyzer(cache, hotUpdateDlls); - reversePInvokeAnalyzer.Run(); - - 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"; - - var callNativeMethodSignatures = calliAnalyzer.CalliMethodSignatures.Concat(pinvokeAnalyzer.PInvokeMethodSignatures).ToList(); - - var generateMethodBridgeMethod = typeof(MethodBridgeGeneratorCommand).GetMethod("GenerateMethodBridgeCppFile", BindingFlags.NonPublic | BindingFlags.Static); - generateMethodBridgeMethod.Invoke(null, new object[] { methodBridgeAnalyzer.GenericMethods, reversePInvokeAnalyzer.ReversePInvokeMethods, callNativeMethodSignatures, templateFile, outputFile }); - - MethodBridgeGeneratorCommand.CleanIl2CppBuildCache(); - } - - public static void GenerateAOTGenericReference(BuildTarget target, string obfuscatedHotUpdateDllPath) - { - var gs = SettingsUtil.HybridCLRSettings; - List hotUpdateDllNames = SettingsUtil.HotUpdateAssemblyNamesExcludePreserved; - - AssemblyReferenceDeepCollector collector = new AssemblyReferenceDeepCollector( - CreateObfuscatedHotUpdateAndAOTAssemblyResolver(target, hotUpdateDllNames, ObfuzSettings.Instance.assemblySettings.GetAssembliesToObfuscate(), obfuscatedHotUpdateDllPath), hotUpdateDllNames); - var analyzer = new Analyzer2(new Analyzer2.Options - { - MaxIterationCount = Math.Min(20, gs.maxGenericReferenceIteration), - Collector = collector, - }); - - analyzer.Run(); - - var writer = new GenericReferenceWriter(); - writer.Write(analyzer.AotGenericTypes.ToList(), analyzer.AotGenericMethods.ToList(), $"{Application.dataPath}/{gs.outputAOTGenericReferenceFile}"); - AssetDatabase.Refresh(); - } - } -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Editor/PrebuildCommandExt.cs.meta b/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Editor/PrebuildCommandExt.cs.meta deleted file mode 100644 index 2bcd1c79..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Editor/PrebuildCommandExt.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: afc965e1afdfc8e47b8a70be7a93cf25 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/LICENSE b/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/LICENSE deleted file mode 100644 index 093e5999..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2025 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. diff --git a/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/LICENSE.meta b/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/LICENSE.meta deleted file mode 100644 index dd09461e..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/LICENSE.meta +++ /dev/null @@ -1,7 +0,0 @@ -fileFormatVersion: 2 -guid: 3036602f815e31341b4445f0e331b58e -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/README.md b/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/README.md deleted file mode 100644 index d52e8ba0..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/README.md +++ /dev/null @@ -1,2 +0,0 @@ -# obfuz4hybridclr -obfuz4hybridclr is a obfuz extension for HybridCLR. diff --git a/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/README.md.meta b/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/README.md.meta deleted file mode 100644 index c8633d1e..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/README.md.meta +++ /dev/null @@ -1,7 +0,0 @@ -fileFormatVersion: 2 -guid: 3ab25e7bb5a8e7d4fb3ba4614f2e3822 -TextScriptImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Templates~/MetadataReader.h.tpl b/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Templates~/MetadataReader.h.tpl deleted file mode 100644 index 0a630027..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Templates~/MetadataReader.h.tpl +++ /dev/null @@ -1,96 +0,0 @@ -#pragma once - -#include "MetadataUtil.h" - -namespace hybridclr -{ -namespace metadata -{ - struct ByteSpan - { - const byte* data; - uint32_t length; - ByteSpan() : data(nullptr), length(0) {} - ByteSpan(const byte* data, uint32_t length) : data(data), length(length) {} - }; - - class MetadataReader - { - private: - const byte* _data; - public: - MetadataReader(const byte* data) : _data(data) {} - int16_t ReadInt16() - { - int16_t value = GetI2LittleEndian(_data); - _data += 2; - return value; - } - - bool ReadBool() - { - return *(_data++) != 0; - } - - uint8_t ReadUInt8() - { - return *(_data++); - } - - uint16_t ReadUInt16() - { - uint16_t value = GetU2LittleEndian(_data); - _data += 2; - return value; - } - - int32_t ReadInt32() - { - int32_t value = GetI4LittleEndian(_data); - _data += 4; - return value; - } - - uint32_t ReadUInt32() - { - uint32_t value = GetU4LittleEndian(_data); - _data += 4; - return value; - } - - int64_t ReadInt64() - { - int64_t value = GetI8LittleEndian(_data); - _data += 8; - return value; - } - - uint64_t ReadUInt64() - { - uint64_t value = GetU8LittleEndian(_data); - _data += 8; - return value; - } - - const byte* ReadFixedBytes(int32_t byteCount) - { - const byte* value = _data; - _data += byteCount; - return value; - } - - ByteSpan ReadBytes() - { - uint32_t byteCount = ReadUInt32(); - const byte* buffer = _data; - _data += byteCount; - return ByteSpan(buffer, byteCount); - } - - const byte* CurrentDataPtr() const - { - return _data; - } - }; -} -} \ No newline at end of file diff --git a/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Templates~/PolymorphicDatas.h.tpl b/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Templates~/PolymorphicDatas.h.tpl deleted file mode 100644 index bb91b78b..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Templates~/PolymorphicDatas.h.tpl +++ /dev/null @@ -1,88 +0,0 @@ -#pragma once -#include "MetadataReader.h" - -namespace hybridclr -{ -namespace metadata -{ - //!!!{{POLYMORPHIC_DATA - struct HeaderBaseData - { - uint32_t metadataSize; - uint32_t sectionCount; - const byte* dummyData; - uint32_t metadataRva; - uint32_t entryPointToken; - void Read(MetadataReader& reader) - { - metadataSize = reader.ReadUInt32(); - sectionCount = reader.ReadUInt32(); - dummyData = reader.ReadFixedBytes(8); - metadataRva = reader.ReadUInt32(); - entryPointToken = reader.ReadUInt32(); - } - }; - - struct SectionData - { - uint32_t rva; - uint32_t fileOffset; - uint32_t virtualSize; - uint32_t fileLength; - void Read(MetadataReader& reader) - { - rva = reader.ReadUInt32(); - fileOffset = reader.ReadUInt32(); - virtualSize = reader.ReadUInt32(); - fileLength = reader.ReadUInt32(); - } - }; - - struct MetadataHeaderBaseData - { - uint32_t signature; - uint8_t reserved2; - ByteSpan versionString; - uint16_t majorVersion; - uint16_t heapsCount; - uint32_t reserved1; - uint8_t storageFlags; - uint16_t minorVersion; - void Read(MetadataReader& reader) - { - signature = reader.ReadUInt32(); - reserved2 = reader.ReadUInt8(); - versionString = reader.ReadBytes(); - majorVersion = reader.ReadUInt16(); - heapsCount = reader.ReadUInt16(); - reserved1 = reader.ReadUInt32(); - storageFlags = reader.ReadUInt8(); - minorVersion = reader.ReadUInt16(); - } - }; - - struct TablesHeapHeaderBaseData - { - uint64_t validMask; - uint32_t reserved1; - uint8_t streamFlags; - uint8_t majorVersion; - uint64_t sortedMask; - uint8_t minorVersion; - uint8_t log2Rid; - void Read(MetadataReader& reader) - { - validMask = reader.ReadUInt64(); - reserved1 = reader.ReadUInt32(); - streamFlags = reader.ReadUInt8(); - majorVersion = reader.ReadUInt8(); - sortedMask = reader.ReadUInt64(); - minorVersion = reader.ReadUInt8(); - log2Rid = reader.ReadUInt8(); - } - }; - - - //!!!}}POLYMORPHIC_DATA -} -} \ No newline at end of file diff --git a/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Templates~/PolymorphicDefs.h.tpl b/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Templates~/PolymorphicDefs.h.tpl deleted file mode 100644 index a88b8a7d..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Templates~/PolymorphicDefs.h.tpl +++ /dev/null @@ -1,28 +0,0 @@ -#pragma once -#include "MetadataReader.h" - -namespace hybridclr -{ -namespace metadata -{ - //!!!{{POLYMORPHIC_DEFINES -#define POLYMORPHIC_IMAGE_SIGNATURE "CODEPHPY" - constexpr uint32_t kPolymorphicImageVersion = 1; - constexpr uint32_t kFormatVariantVersion = 0; - - //!!!}}POLYMORPHIC_DEFINES - - struct PolymorphicImageHeaderData - { - const byte* signature; - uint32_t formatVersion; - uint32_t formatVariant; - void Read(MetadataReader& reader) - { - signature = reader.ReadFixedBytes(8); - formatVersion = reader.ReadUInt32(); - formatVariant = reader.ReadUInt32(); - } - }; -} -} \ No newline at end of file diff --git a/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Templates~/PolymorphicRawImage.cpp.tpl b/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Templates~/PolymorphicRawImage.cpp.tpl deleted file mode 100644 index ef091f5c..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Templates~/PolymorphicRawImage.cpp.tpl +++ /dev/null @@ -1,897 +0,0 @@ -#include "PolymorphicRawImage.h" - -#include - -#include "PolymorphicDefs.h" -#include "PolymorphicDatas.h" - -namespace hybridclr -{ -namespace metadata -{ - - struct RawSectionHeader - { - uint32_t fileOffset; - uint32_t fileLength; - uint32_t rva; - uint32_t virtualSize; - }; - - LoadImageErrorCode PolymorphicRawImage::LoadCLIHeader(uint32_t& entryPointToken, uint32_t& metadataRva, uint32_t& metadataSize) - { - if (_imageLength < 0x100) - { - return LoadImageErrorCode::BAD_IMAGE; - } - - MetadataReader reader(_imageData); - - PolymorphicImageHeaderData imageHeaderData = {}; - imageHeaderData.Read(reader); - - const char* sig = (const char*)_imageData; - if (std::strncmp((const char*)imageHeaderData.signature, POLYMORPHIC_IMAGE_SIGNATURE, sizeof(POLYMORPHIC_IMAGE_SIGNATURE) - 1)) - { - return LoadImageErrorCode::BAD_IMAGE; - } - if (imageHeaderData.formatVersion != kPolymorphicImageVersion) - { - return LoadImageErrorCode::UNSUPPORT_FORMAT_VERSION; - } - if (imageHeaderData.formatVariant != kFormatVariantVersion) - { - return LoadImageErrorCode::UNMATCH_FORMAT_VARIANT; - } - - //reader.ReadFixedBytes(polymorphic::kImageHeaderDummyDataSize); // Skip dummy data - - PolymorphicHeaderBaseData headerBaseData = {}; - headerBaseData.Read(reader); - - const size_t kEntryPointTokenOffset = 16; - entryPointToken = headerBaseData.entryPointToken; - metadataRva = headerBaseData.metadataRva; - metadataSize = headerBaseData.metadataSize; - - uint32_t sectionCount = headerBaseData.sectionCount; - for (uint32_t i = 0; i < sectionCount; i++) - { - PolymorphicSectionData sectionData = {}; - sectionData.Read(reader); - _sections.push_back({ sectionData.rva, sectionData.rva + sectionData.virtualSize, sectionData.fileOffset - sectionData.rva }); - } - return LoadImageErrorCode::OK; - } - - LoadImageErrorCode PolymorphicRawImage::LoadStreamHeaders(uint32_t metadataRva, uint32_t metadataSize) - { - uint32_t metaOffset; - if (!TranslateRVAToImageOffset(metadataRva, metaOffset)) - { - return LoadImageErrorCode::BAD_IMAGE; - } - if (metaOffset >= _imageLength) - { - return LoadImageErrorCode::BAD_IMAGE; - } - - const byte* ptrMetaData = _imageData + metaOffset; - MetadataReader reader(ptrMetaData); - - PolymorphicMetadataHeaderBaseData metadataHeader = {}; - metadataHeader.Read(reader); - if (metadataHeader.signature != 0x424A5342) - { - return LoadImageErrorCode::BAD_IMAGE; - } - - uint16_t numStreamHeader = metadataHeader.heapsCount; - const StreamHeader* ptrStreamHeaders = (const StreamHeader*)(reader.CurrentDataPtr()); - - const StreamHeader* curSH = ptrStreamHeaders; - const size_t maxStreamNameSize = 16; - for (int i = 0; i < numStreamHeader; i++) - { - //std::cout << "name:" << (char*)curSH->name << ", offset:" << curSH->offset << ", size:" << curSH->size << std::endl; - - if (curSH->offset >= metadataSize) - { - return LoadImageErrorCode::BAD_IMAGE; - } - CliStream* rs = nullptr; - CliStream nonStandardStream; - CliStream pdbStream; - if (!std::strncmp(curSH->name, "#~", maxStreamNameSize)) - { - rs = &_streamTables; - } - else if (!std::strncmp(curSH->name, "#Strings", maxStreamNameSize)) - { - rs = &_streamStringHeap; - } - else if (!std::strncmp(curSH->name, "#US", maxStreamNameSize)) - { - rs = &_streamUS; - } - else if (!std::strncmp(curSH->name, "#GUID", maxStreamNameSize)) - { - rs = &_streamGuidHeap; - if (curSH->size % 16 != 0) - { - return LoadImageErrorCode::BAD_IMAGE; - } - } - else if (!std::strncmp(curSH->name, "#Blob", maxStreamNameSize)) - { - rs = &_streamBlobHeap; - } - else if (!std::strncmp(curSH->name, "#-", maxStreamNameSize)) - { - rs = &nonStandardStream; - } - else if (!std::strncmp(curSH->name, "#Pdb", maxStreamNameSize)) - { - rs = &pdbStream; - } - else - { - //std::cerr << "unknown stream name:" << curSH->name << std::endl; - return LoadImageErrorCode::BAD_IMAGE; - } - rs->data = ptrMetaData + curSH->offset; - rs->size = curSH->size; - rs->name = curSH->name; - size_t sizeOfStream = 8 + (std::strlen(curSH->name) / 4 + 1) * 4; - curSH = (const StreamHeader*)((byte*)curSH + sizeOfStream); - } - return LoadImageErrorCode::OK; - } - - LoadImageErrorCode PolymorphicRawImage::LoadTables() - { - MetadataReader reader(_streamTables.data); - - PolymorphicTablesHeapHeaderBaseData heapHeader = {}; - heapHeader.Read(reader); - - if (heapHeader.reserved1 != 0 || heapHeader.majorVersion != 2 || heapHeader.minorVersion != 0) - { - return LoadImageErrorCode::BAD_IMAGE; - } - if ((heapHeader.streamFlags & ~0x7)) - { - return LoadImageErrorCode::BAD_IMAGE; - } - _4byteStringIndex = heapHeader.streamFlags & 0x1; - _4byteGUIDIndex = heapHeader.streamFlags & 0x2; - _4byteBlobIndex = heapHeader.streamFlags & 0x4; - - uint64_t validMask = ((uint64_t)1 << TABLE_NUM) - 1; - if (heapHeader.validMask & ~validMask) - { - return LoadImageErrorCode::BAD_IMAGE; - } - // sorted include not exist table, so check is not need. - //if (heapHeader.sorted & ~validMask) - //{ - // return LoadImageErrorCode::BAD_IMAGE; - //} - - uint32_t validTableNum = GetNotZeroBitCount(heapHeader.validMask); - //std::cout << "valid table num:" << validTableNum << std::endl; - //printf("#~ size:%0x\n", _streamTables.size); - const uint32_t* tableRowNums = (uint32_t*)(reader.CurrentDataPtr()); - const byte* tableDataBegin = (const byte*)(tableRowNums + validTableNum); - - { - int curValidTableIndex = 0; - for (int i = 0; i <= MAX_TABLE_INDEX; i++) - { - uint64_t mask = (uint64_t)1 << i; - _tables[i] = {}; - if (heapHeader.validMask & mask) - { - uint32_t rowNum = tableRowNums[curValidTableIndex]; - _tables[i].rowNum = rowNum; - ++curValidTableIndex; - } - } - } - - BuildTableRowMetas(); - - int curValidTableIndex = 0; - const byte* curTableData = tableDataBegin; - for (int i = 0; i <= MAX_TABLE_INDEX; i++) - { - uint64_t mask = (uint64_t)1 << i; - bool sorted = heapHeader.sortedMask & mask; - if (heapHeader.validMask & mask) - { - uint32_t rowNum = tableRowNums[curValidTableIndex]; - uint32_t totalSize = 0; - auto& table = _tableRowMetas[i]; - for (auto& col : table) - { - col.offset = totalSize; - totalSize += col.size; - } - uint32_t metaDataRowSize = totalSize; - //uint64_t offset = curTableData - _imageData; - _tables[i] = { curTableData, metaDataRowSize, rowNum, true, sorted }; - curTableData += metaDataRowSize * rowNum; - //std::cout << "table:" << i << " ," << curValidTableIndex << ", row_size:" << metaDataRowSize << ", row_num:" << rowNum << std::endl; - //printf("table:[%d][%d] offset:%0llx row_size:%d row_count:%d\n", i, curValidTableIndex, offset, metaDataRowSize, rowNum); - ++curValidTableIndex; - } - else - { - _tables[i] = { nullptr, 0, 0, false, sorted }; - } - } - - return LoadImageErrorCode::OK; - } - - void PolymorphicRawImage::BuildTableRowMetas() - { - //!!!{{TABLE_ROW_METADS - { - auto& table = _tableRowMetas[(int)TableType::MODULE]; - table.push_back({2}); - table.push_back({ComputStringIndexByte()}); - table.push_back({ComputGUIDIndexByte()}); - table.push_back({ComputGUIDIndexByte()}); - table.push_back({ComputGUIDIndexByte()}); - } - { - auto& table = _tableRowMetas[(int)TableType::TYPEREF]; - table.push_back({ComputStringIndexByte()}); - table.push_back({ComputStringIndexByte()}); - table.push_back({ComputTableIndexByte(TableType::MODULE, TableType::MODULEREF, TableType::ASSEMBLYREF, TableType::TYPEREF, TagBits::ResoulutionScope)}); - } - { - auto& table = _tableRowMetas[(int)TableType::TYPEDEF]; - table.push_back({ComputStringIndexByte()}); - table.push_back({ComputTableIndexByte(TableType::FIELD)}); - table.push_back({ComputTableIndexByte(TableType::TYPEDEF, TableType::TYPEREF, TableType::TYPESPEC, TagBits::TypeDefOrRef)}); - table.push_back({4}); - table.push_back({ComputStringIndexByte()}); - table.push_back({ComputTableIndexByte(TableType::METHOD)}); - } - { - auto& table = _tableRowMetas[(int)TableType::FIELDPTR]; - table.push_back({ComputTableIndexByte(TableType::FIELD)}); - } - { - auto& table = _tableRowMetas[(int)TableType::FIELD]; - table.push_back({ComputBlobIndexByte()}); - table.push_back({2}); - table.push_back({ComputStringIndexByte()}); - } - { - auto& table = _tableRowMetas[(int)TableType::METHODPTR]; - table.push_back({ComputTableIndexByte(TableType::METHOD)}); - } - { - auto& table = _tableRowMetas[(int)TableType::METHOD]; - table.push_back({ComputBlobIndexByte()}); - table.push_back({2}); - table.push_back({2}); - table.push_back({ComputStringIndexByte()}); - table.push_back({ComputTableIndexByte(TableType::PARAM)}); - table.push_back({4}); - } - { - auto& table = _tableRowMetas[(int)TableType::PARAMPTR]; - table.push_back({ComputTableIndexByte(TableType::PARAM)}); - } - { - auto& table = _tableRowMetas[(int)TableType::PARAM]; - table.push_back({2}); - table.push_back({ComputStringIndexByte()}); - table.push_back({2}); - } - { - auto& table = _tableRowMetas[(int)TableType::INTERFACEIMPL]; - table.push_back({ComputTableIndexByte(TableType::TYPEDEF)}); - table.push_back({ComputTableIndexByte(TableType::TYPEDEF, TableType::TYPEREF, TableType::TYPESPEC, TagBits::TypeDefOrRef)}); - } - { - auto& table = _tableRowMetas[(int)TableType::MEMBERREF]; - table.push_back({ComputStringIndexByte()}); - table.push_back({ComputBlobIndexByte()}); - table.push_back({ComputTableIndexByte(TableType::METHOD, TableType::MODULEREF, TableType::TYPEDEF, TableType::TYPEREF, TagBits::MemberRefParent)}); - } - { - auto& table = _tableRowMetas[(int)TableType::CONSTANT]; - table.push_back({1}); - table.push_back({1}); - table.push_back({ComputTableIndexByte(TableType::PARAM, TableType::FIELD, TableType::PROPERTY, TagBits::HasConstant)}); - table.push_back({ComputBlobIndexByte()}); - } - { - auto& table = _tableRowMetas[(int)TableType::CUSTOMATTRIBUTE]; - table.push_back({ComputTableIndexByte(HasCustomAttributeAssociateTables, sizeof(HasCustomAttributeAssociateTables) / sizeof(TableType), TagBits::HasCustomAttribute)}); - table.push_back({ComputTableIndexByte(TableType::METHOD, TableType::MEMBERREF, TagBits::CustomAttributeType)}); - table.push_back({ComputBlobIndexByte()}); - } - { - auto& table = _tableRowMetas[(int)TableType::FIELDMARSHAL]; - table.push_back({ComputTableIndexByte(TableType::FIELD, TableType::PARAM, TagBits::HasFieldMarshal)}); - table.push_back({ComputBlobIndexByte()}); - } - { - auto& table = _tableRowMetas[(int)TableType::DECLSECURITY]; - table.push_back({2}); - table.push_back({ComputTableIndexByte(TableType::TYPEDEF, TableType::METHOD, TableType::ASSEMBLY, TagBits::HasDeclSecurity)}); - table.push_back({ComputBlobIndexByte()}); - } - { - auto& table = _tableRowMetas[(int)TableType::CLASSLAYOUT]; - table.push_back({4}); - table.push_back({2}); - table.push_back({ComputTableIndexByte(TableType::TYPEDEF)}); - } - { - auto& table = _tableRowMetas[(int)TableType::FIELDLAYOUT]; - table.push_back({ComputTableIndexByte(TableType::FIELD)}); - table.push_back({4}); - } - { - auto& table = _tableRowMetas[(int)TableType::STANDALONESIG]; - table.push_back({ComputBlobIndexByte()}); - } - { - auto& table = _tableRowMetas[(int)TableType::EVENTMAP]; - table.push_back({ComputTableIndexByte(TableType::TYPEDEF)}); - table.push_back({ComputTableIndexByte(TableType::EVENT)}); - } - { - auto& table = _tableRowMetas[(int)TableType::EVENTPTR]; - table.push_back({ComputTableIndexByte(TableType::EVENT)}); - } - { - auto& table = _tableRowMetas[(int)TableType::EVENT]; - table.push_back({ComputTableIndexByte(TableType::TYPEDEF, TableType::TYPEREF, TableType::TYPESPEC, TagBits::TypeDefOrRef)}); - table.push_back({ComputStringIndexByte()}); - table.push_back({2}); - } - { - auto& table = _tableRowMetas[(int)TableType::PROPERTYMAP]; - table.push_back({ComputTableIndexByte(TableType::PROPERTY)}); - table.push_back({ComputTableIndexByte(TableType::TYPEDEF)}); - } - { - auto& table = _tableRowMetas[(int)TableType::PROPERTYPTR]; - table.push_back({ComputTableIndexByte(TableType::PROPERTY)}); - } - { - auto& table = _tableRowMetas[(int)TableType::PROPERTY]; - table.push_back({2}); - table.push_back({ComputStringIndexByte()}); - table.push_back({ComputBlobIndexByte()}); - } - { - auto& table = _tableRowMetas[(int)TableType::METHODSEMANTICS]; - table.push_back({ComputTableIndexByte(TableType::EVENT, TableType::PROPERTY, TagBits::HasSemantics)}); - table.push_back({ComputTableIndexByte(TableType::METHOD)}); - table.push_back({2}); - } - { - auto& table = _tableRowMetas[(int)TableType::METHODIMPL]; - table.push_back({ComputTableIndexByte(TableType::METHOD, TableType::MEMBERREF, TagBits::MethodDefOrRef)}); - table.push_back({ComputTableIndexByte(TableType::METHOD, TableType::MEMBERREF, TagBits::MethodDefOrRef)}); - table.push_back({ComputTableIndexByte(TableType::TYPEDEF)}); - } - { - auto& table = _tableRowMetas[(int)TableType::MODULEREF]; - table.push_back({ComputStringIndexByte()}); - } - { - auto& table = _tableRowMetas[(int)TableType::TYPESPEC]; - table.push_back({ComputBlobIndexByte()}); - } - { - auto& table = _tableRowMetas[(int)TableType::IMPLMAP]; - table.push_back({2}); - table.push_back({ComputTableIndexByte(TableType::MODULEREF)}); - table.push_back({ComputTableIndexByte(TableType::FIELD, TableType::METHOD, TagBits::MemberForwarded)}); - table.push_back({ComputStringIndexByte()}); - } - { - auto& table = _tableRowMetas[(int)TableType::FIELDRVA]; - table.push_back({ComputTableIndexByte(TableType::FIELD)}); - table.push_back({4}); - } - { - auto& table = _tableRowMetas[(int)TableType::ENCLOG]; - table.push_back({4}); - table.push_back({4}); - } - { - auto& table = _tableRowMetas[(int)TableType::ENCMAP]; - table.push_back({4}); - } - { - auto& table = _tableRowMetas[(int)TableType::ASSEMBLY]; - table.push_back({2}); - table.push_back({4}); - table.push_back({2}); - table.push_back({2}); - table.push_back({ComputStringIndexByte()}); - table.push_back({ComputStringIndexByte()}); - table.push_back({ComputBlobIndexByte()}); - table.push_back({2}); - table.push_back({4}); - } - { - auto& table = _tableRowMetas[(int)TableType::ASSEMBLYPROCESSOR]; - table.push_back({4}); - } - { - auto& table = _tableRowMetas[(int)TableType::ASSEMBLYOS]; - table.push_back({4}); - table.push_back({4}); - table.push_back({4}); - } - { - auto& table = _tableRowMetas[(int)TableType::ASSEMBLYREF]; - table.push_back({4}); - table.push_back({2}); - table.push_back({2}); - table.push_back({ComputBlobIndexByte()}); - table.push_back({ComputBlobIndexByte()}); - table.push_back({2}); - table.push_back({2}); - table.push_back({ComputStringIndexByte()}); - table.push_back({ComputStringIndexByte()}); - } - { - auto& table = _tableRowMetas[(int)TableType::ASSEMBLYREFPROCESSOR]; - table.push_back({ComputTableIndexByte(TableType::ASSEMBLYREF)}); - table.push_back({4}); - } - { - auto& table = _tableRowMetas[(int)TableType::ASSEMBLYREFOS]; - table.push_back({4}); - table.push_back({4}); - table.push_back({4}); - table.push_back({ComputTableIndexByte(TableType::ASSEMBLYREF)}); - } - { - auto& table = _tableRowMetas[(int)TableType::FILE]; - table.push_back({4}); - table.push_back({ComputStringIndexByte()}); - table.push_back({ComputBlobIndexByte()}); - } - { - auto& table = _tableRowMetas[(int)TableType::EXPORTEDTYPE]; - table.push_back({4}); - table.push_back({4}); - table.push_back({ComputStringIndexByte()}); - table.push_back({ComputStringIndexByte()}); - table.push_back({ComputTableIndexByte(TableType::FILE, TableType::EXPORTEDTYPE, TableType::ASSEMBLY, TagBits::Implementation)}); - } - { - auto& table = _tableRowMetas[(int)TableType::MANIFESTRESOURCE]; - table.push_back({4}); - table.push_back({4}); - table.push_back({ComputStringIndexByte()}); - table.push_back({ComputTableIndexByte(TableType::FILE, TableType::ASSEMBLYREF, TagBits::Implementation)}); - } - { - auto& table = _tableRowMetas[(int)TableType::NESTEDCLASS]; - table.push_back({ComputTableIndexByte(TableType::TYPEDEF)}); - table.push_back({ComputTableIndexByte(TableType::TYPEDEF)}); - } - { - auto& table = _tableRowMetas[(int)TableType::GENERICPARAM]; - table.push_back({2}); - table.push_back({2}); - table.push_back({ComputTableIndexByte(TableType::TYPEDEF, TableType::METHOD, TagBits::TypeOrMethodDef)}); - table.push_back({ComputStringIndexByte()}); - } - { - auto& table = _tableRowMetas[(int)TableType::METHODSPEC]; - table.push_back({ComputTableIndexByte(TableType::METHOD, TableType::MEMBERREF, TagBits::MethodDefOrRef)}); - table.push_back({ComputBlobIndexByte()}); - } - { - auto& table = _tableRowMetas[(int)TableType::GENERICPARAMCONSTRAINT]; - table.push_back({ComputTableIndexByte(TableType::TYPEDEF, TableType::TYPEREF, TableType::TYPESPEC, TagBits::TypeDefOrRef)}); - table.push_back({ComputTableIndexByte(TableType::GENERICPARAM)}); - } - { - auto& table = _tableRowMetas[(int)TableType::DOCUMENT]; - table.push_back({ComputBlobIndexByte()}); - table.push_back({ComputGUIDIndexByte()}); - table.push_back({ComputBlobIndexByte()}); - table.push_back({ComputGUIDIndexByte()}); - } - { - auto& table = _tableRowMetas[(int)TableType::METHODDEBUGINFORMATION]; - table.push_back({ComputTableIndexByte(TableType::DOCUMENT)}); - table.push_back({ComputBlobIndexByte()}); - } - { - auto& table = _tableRowMetas[(int)TableType::LOCALSCOPE]; - table.push_back({ComputTableIndexByte(TableType::METHOD)}); - table.push_back({ComputTableIndexByte(TableType::IMPORTSCOPE)}); - table.push_back({ComputTableIndexByte(TableType::LOCALVARIABLE)}); - table.push_back({ComputTableIndexByte(TableType::LOCALCONSTANT)}); - table.push_back({4}); - table.push_back({4}); - } - { - auto& table = _tableRowMetas[(int)TableType::LOCALVARIABLE]; - table.push_back({2}); - table.push_back({2}); - table.push_back({ComputStringIndexByte()}); - } - { - auto& table = _tableRowMetas[(int)TableType::LOCALCONSTANT]; - table.push_back({ComputStringIndexByte()}); - table.push_back({ComputBlobIndexByte()}); - } - { - auto& table = _tableRowMetas[(int)TableType::IMPORTSCOPE]; - table.push_back({ComputTableIndexByte(TableType::IMPORTSCOPE)}); - table.push_back({ComputBlobIndexByte()}); - } - { - auto& table = _tableRowMetas[(int)TableType::STATEMACHINEMETHOD]; - table.push_back({ComputTableIndexByte(TableType::METHOD)}); - table.push_back({ComputTableIndexByte(TableType::METHOD)}); - } - { - auto& table = _tableRowMetas[(int)TableType::CUSTOMDEBUGINFORMATION]; - table.push_back({ComputTableIndexByte(HasCustomDebugInformation, sizeof(HasCustomDebugInformation) / sizeof(TableType), TagBits::HasCustomDebugInformation)}); - table.push_back({ComputGUIDIndexByte()}); - table.push_back({ComputBlobIndexByte()}); - } - - //!!!}}TABLE_ROW_METADS - - for (int i = 0; i < TABLE_NUM; i++) - { - auto& table = _tableRowMetas[i]; - if (table.empty()) - { - IL2CPP_ASSERT(_tables[i].rowNum == 0 && _tables[i].rowMetaDataSize == 0); - } - else - { - uint32_t totalSize = 0; - for (auto& col : table) - { - col.offset = totalSize; - totalSize += col.size; - } - uint32_t computSize = ComputTableRowMetaDataSize((TableType)i); - IL2CPP_ASSERT(totalSize == computSize); - } - } - } - - //!!!{{READ_TABLES_IMPLEMENTATIONS - TbTypeRef PolymorphicRawImage::ReadTypeRef(uint32_t rawIndex) - { - IL2CPP_ASSERT(rawIndex > 0 && rawIndex <= GetTable(TableType::TYPEREF).rowNum); - const byte* rowPtr = GetTableRowPtr(TableType::TYPEREF, rawIndex); - auto& rowSchema = GetRowSchema(TableType::TYPEREF); - TbTypeRef data; - data.typeNamespace = ReadColumn(rowPtr, rowSchema[0]); - data.typeName = ReadColumn(rowPtr, rowSchema[1]); - data.resolutionScope = ReadColumn(rowPtr, rowSchema[2]); - return data; - } - TbTypeDef PolymorphicRawImage::ReadTypeDef(uint32_t rawIndex) - { - IL2CPP_ASSERT(rawIndex > 0 && rawIndex <= GetTable(TableType::TYPEDEF).rowNum); - const byte* rowPtr = GetTableRowPtr(TableType::TYPEDEF, rawIndex); - auto& rowSchema = GetRowSchema(TableType::TYPEDEF); - TbTypeDef data; - data.typeName = ReadColumn(rowPtr, rowSchema[0]); - data.fieldList = ReadColumn(rowPtr, rowSchema[1]); - data.extends = ReadColumn(rowPtr, rowSchema[2]); - data.flags = ReadColumn(rowPtr, rowSchema[3]); - data.typeNamespace = ReadColumn(rowPtr, rowSchema[4]); - data.methodList = ReadColumn(rowPtr, rowSchema[5]); - return data; - } - TbField PolymorphicRawImage::ReadField(uint32_t rawIndex) - { - IL2CPP_ASSERT(rawIndex > 0 && rawIndex <= GetTable(TableType::FIELD).rowNum); - const byte* rowPtr = GetTableRowPtr(TableType::FIELD, rawIndex); - auto& rowSchema = GetRowSchema(TableType::FIELD); - TbField data; - data.signature = ReadColumn(rowPtr, rowSchema[0]); - data.flags = ReadColumn(rowPtr, rowSchema[1]); - data.name = ReadColumn(rowPtr, rowSchema[2]); - return data; - } - TbMethod PolymorphicRawImage::ReadMethod(uint32_t rawIndex) - { - IL2CPP_ASSERT(rawIndex > 0 && rawIndex <= GetTable(TableType::METHOD).rowNum); - const byte* rowPtr = GetTableRowPtr(TableType::METHOD, rawIndex); - auto& rowSchema = GetRowSchema(TableType::METHOD); - TbMethod data; - data.signature = ReadColumn(rowPtr, rowSchema[0]); - data.flags = ReadColumn(rowPtr, rowSchema[1]); - data.implFlags = ReadColumn(rowPtr, rowSchema[2]); - data.name = ReadColumn(rowPtr, rowSchema[3]); - data.paramList = ReadColumn(rowPtr, rowSchema[4]); - data.rva = ReadColumn(rowPtr, rowSchema[5]); - return data; - } - TbParam PolymorphicRawImage::ReadParam(uint32_t rawIndex) - { - IL2CPP_ASSERT(rawIndex > 0 && rawIndex <= GetTable(TableType::PARAM).rowNum); - const byte* rowPtr = GetTableRowPtr(TableType::PARAM, rawIndex); - auto& rowSchema = GetRowSchema(TableType::PARAM); - TbParam data; - data.flags = ReadColumn(rowPtr, rowSchema[0]); - data.name = ReadColumn(rowPtr, rowSchema[1]); - data.sequence = ReadColumn(rowPtr, rowSchema[2]); - return data; - } - TbInterfaceImpl PolymorphicRawImage::ReadInterfaceImpl(uint32_t rawIndex) - { - IL2CPP_ASSERT(rawIndex > 0 && rawIndex <= GetTable(TableType::INTERFACEIMPL).rowNum); - const byte* rowPtr = GetTableRowPtr(TableType::INTERFACEIMPL, rawIndex); - auto& rowSchema = GetRowSchema(TableType::INTERFACEIMPL); - TbInterfaceImpl data; - data.classIdx = ReadColumn(rowPtr, rowSchema[0]); - data.interfaceIdx = ReadColumn(rowPtr, rowSchema[1]); - return data; - } - TbMemberRef PolymorphicRawImage::ReadMemberRef(uint32_t rawIndex) - { - IL2CPP_ASSERT(rawIndex > 0 && rawIndex <= GetTable(TableType::MEMBERREF).rowNum); - const byte* rowPtr = GetTableRowPtr(TableType::MEMBERREF, rawIndex); - auto& rowSchema = GetRowSchema(TableType::MEMBERREF); - TbMemberRef data; - data.name = ReadColumn(rowPtr, rowSchema[0]); - data.signature = ReadColumn(rowPtr, rowSchema[1]); - data.classIdx = ReadColumn(rowPtr, rowSchema[2]); - return data; - } - TbConstant PolymorphicRawImage::ReadConstant(uint32_t rawIndex) - { - IL2CPP_ASSERT(rawIndex > 0 && rawIndex <= GetTable(TableType::CONSTANT).rowNum); - const byte* rowPtr = GetTableRowPtr(TableType::CONSTANT, rawIndex); - auto& rowSchema = GetRowSchema(TableType::CONSTANT); - TbConstant data; - data.padding = ReadColumn(rowPtr, rowSchema[0]); - data.type = ReadColumn(rowPtr, rowSchema[1]); - data.parent = ReadColumn(rowPtr, rowSchema[2]); - data.value = ReadColumn(rowPtr, rowSchema[3]); - return data; - } - TbCustomAttribute PolymorphicRawImage::ReadCustomAttribute(uint32_t rawIndex) - { - IL2CPP_ASSERT(rawIndex > 0 && rawIndex <= GetTable(TableType::CUSTOMATTRIBUTE).rowNum); - const byte* rowPtr = GetTableRowPtr(TableType::CUSTOMATTRIBUTE, rawIndex); - auto& rowSchema = GetRowSchema(TableType::CUSTOMATTRIBUTE); - TbCustomAttribute data; - data.parent = ReadColumn(rowPtr, rowSchema[0]); - data.type = ReadColumn(rowPtr, rowSchema[1]); - data.value = ReadColumn(rowPtr, rowSchema[2]); - return data; - } - TbClassLayout PolymorphicRawImage::ReadClassLayout(uint32_t rawIndex) - { - IL2CPP_ASSERT(rawIndex > 0 && rawIndex <= GetTable(TableType::CLASSLAYOUT).rowNum); - const byte* rowPtr = GetTableRowPtr(TableType::CLASSLAYOUT, rawIndex); - auto& rowSchema = GetRowSchema(TableType::CLASSLAYOUT); - TbClassLayout data; - data.classSize = ReadColumn(rowPtr, rowSchema[0]); - data.packingSize = ReadColumn(rowPtr, rowSchema[1]); - data.parent = ReadColumn(rowPtr, rowSchema[2]); - return data; - } - TbFieldLayout PolymorphicRawImage::ReadFieldLayout(uint32_t rawIndex) - { - IL2CPP_ASSERT(rawIndex > 0 && rawIndex <= GetTable(TableType::FIELDLAYOUT).rowNum); - const byte* rowPtr = GetTableRowPtr(TableType::FIELDLAYOUT, rawIndex); - auto& rowSchema = GetRowSchema(TableType::FIELDLAYOUT); - TbFieldLayout data; - data.field = ReadColumn(rowPtr, rowSchema[0]); - data.offset = ReadColumn(rowPtr, rowSchema[1]); - return data; - } - TbStandAloneSig PolymorphicRawImage::ReadStandAloneSig(uint32_t rawIndex) - { - IL2CPP_ASSERT(rawIndex > 0 && rawIndex <= GetTable(TableType::STANDALONESIG).rowNum); - const byte* rowPtr = GetTableRowPtr(TableType::STANDALONESIG, rawIndex); - auto& rowSchema = GetRowSchema(TableType::STANDALONESIG); - TbStandAloneSig data; - data.signature = ReadColumn(rowPtr, rowSchema[0]); - return data; - } - TbEventMap PolymorphicRawImage::ReadEventMap(uint32_t rawIndex) - { - IL2CPP_ASSERT(rawIndex > 0 && rawIndex <= GetTable(TableType::EVENTMAP).rowNum); - const byte* rowPtr = GetTableRowPtr(TableType::EVENTMAP, rawIndex); - auto& rowSchema = GetRowSchema(TableType::EVENTMAP); - TbEventMap data; - data.parent = ReadColumn(rowPtr, rowSchema[0]); - data.eventList = ReadColumn(rowPtr, rowSchema[1]); - return data; - } - TbEvent PolymorphicRawImage::ReadEvent(uint32_t rawIndex) - { - IL2CPP_ASSERT(rawIndex > 0 && rawIndex <= GetTable(TableType::EVENT).rowNum); - const byte* rowPtr = GetTableRowPtr(TableType::EVENT, rawIndex); - auto& rowSchema = GetRowSchema(TableType::EVENT); - TbEvent data; - data.eventType = ReadColumn(rowPtr, rowSchema[0]); - data.name = ReadColumn(rowPtr, rowSchema[1]); - data.eventFlags = ReadColumn(rowPtr, rowSchema[2]); - return data; - } - TbPropertyMap PolymorphicRawImage::ReadPropertyMap(uint32_t rawIndex) - { - IL2CPP_ASSERT(rawIndex > 0 && rawIndex <= GetTable(TableType::PROPERTYMAP).rowNum); - const byte* rowPtr = GetTableRowPtr(TableType::PROPERTYMAP, rawIndex); - auto& rowSchema = GetRowSchema(TableType::PROPERTYMAP); - TbPropertyMap data; - data.propertyList = ReadColumn(rowPtr, rowSchema[0]); - data.parent = ReadColumn(rowPtr, rowSchema[1]); - return data; - } - TbProperty PolymorphicRawImage::ReadProperty(uint32_t rawIndex) - { - IL2CPP_ASSERT(rawIndex > 0 && rawIndex <= GetTable(TableType::PROPERTY).rowNum); - const byte* rowPtr = GetTableRowPtr(TableType::PROPERTY, rawIndex); - auto& rowSchema = GetRowSchema(TableType::PROPERTY); - TbProperty data; - data.flags = ReadColumn(rowPtr, rowSchema[0]); - data.name = ReadColumn(rowPtr, rowSchema[1]); - data.type = ReadColumn(rowPtr, rowSchema[2]); - return data; - } - TbMethodSemantics PolymorphicRawImage::ReadMethodSemantics(uint32_t rawIndex) - { - IL2CPP_ASSERT(rawIndex > 0 && rawIndex <= GetTable(TableType::METHODSEMANTICS).rowNum); - const byte* rowPtr = GetTableRowPtr(TableType::METHODSEMANTICS, rawIndex); - auto& rowSchema = GetRowSchema(TableType::METHODSEMANTICS); - TbMethodSemantics data; - data.association = ReadColumn(rowPtr, rowSchema[0]); - data.method = ReadColumn(rowPtr, rowSchema[1]); - data.semantics = ReadColumn(rowPtr, rowSchema[2]); - return data; - } - TbMethodImpl PolymorphicRawImage::ReadMethodImpl(uint32_t rawIndex) - { - IL2CPP_ASSERT(rawIndex > 0 && rawIndex <= GetTable(TableType::METHODIMPL).rowNum); - const byte* rowPtr = GetTableRowPtr(TableType::METHODIMPL, rawIndex); - auto& rowSchema = GetRowSchema(TableType::METHODIMPL); - TbMethodImpl data; - data.methodDeclaration = ReadColumn(rowPtr, rowSchema[0]); - data.methodBody = ReadColumn(rowPtr, rowSchema[1]); - data.classIdx = ReadColumn(rowPtr, rowSchema[2]); - return data; - } - TbModuleRef PolymorphicRawImage::ReadModuleRef(uint32_t rawIndex) - { - IL2CPP_ASSERT(rawIndex > 0 && rawIndex <= GetTable(TableType::MODULEREF).rowNum); - const byte* rowPtr = GetTableRowPtr(TableType::MODULEREF, rawIndex); - auto& rowSchema = GetRowSchema(TableType::MODULEREF); - TbModuleRef data; - data.name = ReadColumn(rowPtr, rowSchema[0]); - return data; - } - TbTypeSpec PolymorphicRawImage::ReadTypeSpec(uint32_t rawIndex) - { - IL2CPP_ASSERT(rawIndex > 0 && rawIndex <= GetTable(TableType::TYPESPEC).rowNum); - const byte* rowPtr = GetTableRowPtr(TableType::TYPESPEC, rawIndex); - auto& rowSchema = GetRowSchema(TableType::TYPESPEC); - TbTypeSpec data; - data.signature = ReadColumn(rowPtr, rowSchema[0]); - return data; - } - TbImplMap PolymorphicRawImage::ReadImplMap(uint32_t rawIndex) - { - IL2CPP_ASSERT(rawIndex > 0 && rawIndex <= GetTable(TableType::IMPLMAP).rowNum); - const byte* rowPtr = GetTableRowPtr(TableType::IMPLMAP, rawIndex); - auto& rowSchema = GetRowSchema(TableType::IMPLMAP); - TbImplMap data; - data.mappingFlags = ReadColumn(rowPtr, rowSchema[0]); - data.importScope = ReadColumn(rowPtr, rowSchema[1]); - data.memberForwarded = ReadColumn(rowPtr, rowSchema[2]); - data.importName = ReadColumn(rowPtr, rowSchema[3]); - return data; - } - TbFieldRVA PolymorphicRawImage::ReadFieldRVA(uint32_t rawIndex) - { - IL2CPP_ASSERT(rawIndex > 0 && rawIndex <= GetTable(TableType::FIELDRVA).rowNum); - const byte* rowPtr = GetTableRowPtr(TableType::FIELDRVA, rawIndex); - auto& rowSchema = GetRowSchema(TableType::FIELDRVA); - TbFieldRVA data; - data.field = ReadColumn(rowPtr, rowSchema[0]); - data.rva = ReadColumn(rowPtr, rowSchema[1]); - return data; - } - TbAssembly PolymorphicRawImage::ReadAssembly(uint32_t rawIndex) - { - IL2CPP_ASSERT(rawIndex > 0 && rawIndex <= GetTable(TableType::ASSEMBLY).rowNum); - const byte* rowPtr = GetTableRowPtr(TableType::ASSEMBLY, rawIndex); - auto& rowSchema = GetRowSchema(TableType::ASSEMBLY); - TbAssembly data; - data.minorVersion = ReadColumn(rowPtr, rowSchema[0]); - data.hashAlgId = ReadColumn(rowPtr, rowSchema[1]); - data.buildNumber = ReadColumn(rowPtr, rowSchema[2]); - data.revisionNumber = ReadColumn(rowPtr, rowSchema[3]); - data.locale = ReadColumn(rowPtr, rowSchema[4]); - data.name = ReadColumn(rowPtr, rowSchema[5]); - data.publicKey = ReadColumn(rowPtr, rowSchema[6]); - data.majorVersion = ReadColumn(rowPtr, rowSchema[7]); - data.flags = ReadColumn(rowPtr, rowSchema[8]); - return data; - } - TbAssemblyRef PolymorphicRawImage::ReadAssemblyRef(uint32_t rawIndex) - { - IL2CPP_ASSERT(rawIndex > 0 && rawIndex <= GetTable(TableType::ASSEMBLYREF).rowNum); - const byte* rowPtr = GetTableRowPtr(TableType::ASSEMBLYREF, rawIndex); - auto& rowSchema = GetRowSchema(TableType::ASSEMBLYREF); - TbAssemblyRef data; - data.flags = ReadColumn(rowPtr, rowSchema[0]); - data.majorVersion = ReadColumn(rowPtr, rowSchema[1]); - data.buildNumber = ReadColumn(rowPtr, rowSchema[2]); - data.publicKeyOrToken = ReadColumn(rowPtr, rowSchema[3]); - data.hashValue = ReadColumn(rowPtr, rowSchema[4]); - data.revisionNumber = ReadColumn(rowPtr, rowSchema[5]); - data.minorVersion = ReadColumn(rowPtr, rowSchema[6]); - data.locale = ReadColumn(rowPtr, rowSchema[7]); - data.name = ReadColumn(rowPtr, rowSchema[8]); - return data; - } - TbNestedClass PolymorphicRawImage::ReadNestedClass(uint32_t rawIndex) - { - IL2CPP_ASSERT(rawIndex > 0 && rawIndex <= GetTable(TableType::NESTEDCLASS).rowNum); - const byte* rowPtr = GetTableRowPtr(TableType::NESTEDCLASS, rawIndex); - auto& rowSchema = GetRowSchema(TableType::NESTEDCLASS); - TbNestedClass data; - data.enclosingClass = ReadColumn(rowPtr, rowSchema[0]); - data.nestedClass = ReadColumn(rowPtr, rowSchema[1]); - return data; - } - TbGenericParam PolymorphicRawImage::ReadGenericParam(uint32_t rawIndex) - { - IL2CPP_ASSERT(rawIndex > 0 && rawIndex <= GetTable(TableType::GENERICPARAM).rowNum); - const byte* rowPtr = GetTableRowPtr(TableType::GENERICPARAM, rawIndex); - auto& rowSchema = GetRowSchema(TableType::GENERICPARAM); - TbGenericParam data; - data.flags = ReadColumn(rowPtr, rowSchema[0]); - data.number = ReadColumn(rowPtr, rowSchema[1]); - data.owner = ReadColumn(rowPtr, rowSchema[2]); - data.name = ReadColumn(rowPtr, rowSchema[3]); - return data; - } - TbMethodSpec PolymorphicRawImage::ReadMethodSpec(uint32_t rawIndex) - { - IL2CPP_ASSERT(rawIndex > 0 && rawIndex <= GetTable(TableType::METHODSPEC).rowNum); - const byte* rowPtr = GetTableRowPtr(TableType::METHODSPEC, rawIndex); - auto& rowSchema = GetRowSchema(TableType::METHODSPEC); - TbMethodSpec data; - data.method = ReadColumn(rowPtr, rowSchema[0]); - data.instantiation = ReadColumn(rowPtr, rowSchema[1]); - return data; - } - TbGenericParamConstraint PolymorphicRawImage::ReadGenericParamConstraint(uint32_t rawIndex) - { - IL2CPP_ASSERT(rawIndex > 0 && rawIndex <= GetTable(TableType::GENERICPARAMCONSTRAINT).rowNum); - const byte* rowPtr = GetTableRowPtr(TableType::GENERICPARAMCONSTRAINT, rawIndex); - auto& rowSchema = GetRowSchema(TableType::GENERICPARAMCONSTRAINT); - TbGenericParamConstraint data; - data.constraint = ReadColumn(rowPtr, rowSchema[0]); - data.owner = ReadColumn(rowPtr, rowSchema[1]); - return data; - } - - //!!!}}READ_TABLES_IMPLEMENTATIONS -} -} \ No newline at end of file diff --git a/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Templates~/PolymorphicRawImage.h.tpl b/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Templates~/PolymorphicRawImage.h.tpl deleted file mode 100644 index a48517b5..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/Templates~/PolymorphicRawImage.h.tpl +++ /dev/null @@ -1,58 +0,0 @@ -#pragma once - -#include "DotNetRawImageBase.h" - -namespace hybridclr -{ -namespace metadata -{ - - class PolymorphicRawImage : public DotNetRawImageBase - { - public: - PolymorphicRawImage() : DotNetRawImageBase() - { - - } - - LoadImageErrorCode LoadCLIHeader(uint32_t& entryPointToken, uint32_t& metadataRva, uint32_t& metadataSize) override; - virtual LoadImageErrorCode LoadStreamHeaders(uint32_t metadataRva, uint32_t metadataSize) override; - virtual LoadImageErrorCode LoadTables() override; - virtual void BuildTableRowMetas() override; - - //!!!{{READ_TABLES_OVERRIDES - virtual TbTypeRef ReadTypeRef(uint32_t rawIndex) override; - virtual TbTypeDef ReadTypeDef(uint32_t rawIndex) override; - virtual TbField ReadField(uint32_t rawIndex) override; - virtual TbMethod ReadMethod(uint32_t rawIndex) override; - virtual TbParam ReadParam(uint32_t rawIndex) override; - virtual TbInterfaceImpl ReadInterfaceImpl(uint32_t rawIndex) override; - virtual TbMemberRef ReadMemberRef(uint32_t rawIndex) override; - virtual TbConstant ReadConstant(uint32_t rawIndex) override; - virtual TbCustomAttribute ReadCustomAttribute(uint32_t rawIndex) override; - virtual TbClassLayout ReadClassLayout(uint32_t rawIndex) override; - virtual TbFieldLayout ReadFieldLayout(uint32_t rawIndex) override; - virtual TbStandAloneSig ReadStandAloneSig(uint32_t rawIndex) override; - virtual TbEventMap ReadEventMap(uint32_t rawIndex) override; - virtual TbEvent ReadEvent(uint32_t rawIndex) override; - virtual TbPropertyMap ReadPropertyMap(uint32_t rawIndex) override; - virtual TbProperty ReadProperty(uint32_t rawIndex) override; - virtual TbMethodSemantics ReadMethodSemantics(uint32_t rawIndex) override; - virtual TbMethodImpl ReadMethodImpl(uint32_t rawIndex) override; - virtual TbModuleRef ReadModuleRef(uint32_t rawIndex) override; - virtual TbTypeSpec ReadTypeSpec(uint32_t rawIndex) override; - virtual TbImplMap ReadImplMap(uint32_t rawIndex) override; - virtual TbFieldRVA ReadFieldRVA(uint32_t rawIndex) override; - virtual TbAssembly ReadAssembly(uint32_t rawIndex) override; - virtual TbAssemblyRef ReadAssemblyRef(uint32_t rawIndex) override; - virtual TbNestedClass ReadNestedClass(uint32_t rawIndex) override; - virtual TbGenericParam ReadGenericParam(uint32_t rawIndex) override; - virtual TbMethodSpec ReadMethodSpec(uint32_t rawIndex) override; - virtual TbGenericParamConstraint ReadGenericParamConstraint(uint32_t rawIndex) override; - - //!!!}}READ_TABLES_OVERRIDES - private: - - }; -} -} diff --git a/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/package.json b/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/package.json deleted file mode 100644 index 290afcd3..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/package.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "name": "com.code-philosophy.obfuz4hybridclr", - "version": "1.0.0-beta.1", - "displayName": "Obfuz4HybridCLR", - "description": "Obfuz4HybridCLR is a obfuz extension for HybridCLR", - "category": "Scripting", - "documentationUrl": "https://www.obfuz.com", - "changelogUrl": "https://github.com/focus-creative-games/obfuz/commits/main/", - "licensesUrl": "https://github.com/focus-creative-games/obfuz/blob/main/com.code-philosophy.obfuz4hybridclr/LICENSE", - "keywords": [ - "obfuz", - "obfuscation", - "obfuscator", - "confuser", - "code-philosophy" - ], - "author": { - "name": "Code Philosophy", - "email": "obfuz@code-philosophy.com", - "url": "https://code-philosophy.com" - } -} \ No newline at end of file diff --git a/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/package.json.meta b/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/package.json.meta deleted file mode 100644 index 5577b3b3..00000000 --- a/UnityProject/Packages/com.code-philosophy.obfuz4hybridclr/package.json.meta +++ /dev/null @@ -1,7 +0,0 @@ -fileFormatVersion: 2 -guid: 9ac66e213a764b840b2533ee30123717 -PackageManifestImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnityProject/Packages/manifest.json b/UnityProject/Packages/manifest.json index f2dda69d..9901e369 100644 --- a/UnityProject/Packages/manifest.json +++ b/UnityProject/Packages/manifest.json @@ -1,5 +1,7 @@ { "dependencies": { + "com.code-philosophy.obfuz": "https://gitee.com/focus-creative-games/obfuz.git", + "com.code-philosophy.obfuz4hybridclr": "https://gitee.com/focus-creative-games/obfuz4hybridclr.git", "com.unity.ide.rider": "3.0.34", "com.unity.ide.visualstudio": "2.0.22", "com.unity.ide.vscode": "1.2.5", diff --git a/UnityProject/Packages/packages-lock.json b/UnityProject/Packages/packages-lock.json index 069ff254..a9cecd8d 100644 --- a/UnityProject/Packages/packages-lock.json +++ b/UnityProject/Packages/packages-lock.json @@ -7,16 +7,18 @@ "dependencies": {} }, "com.code-philosophy.obfuz": { - "version": "file:com.code-philosophy.obfuz", + "version": "https://gitee.com/focus-creative-games/obfuz.git", "depth": 0, - "source": "embedded", - "dependencies": {} + "source": "git", + "dependencies": {}, + "hash": "6ec1a74d577b6aa6cf16e6588aaf989ca035913a" }, "com.code-philosophy.obfuz4hybridclr": { - "version": "file:com.code-philosophy.obfuz4hybridclr", + "version": "https://gitee.com/focus-creative-games/obfuz4hybridclr.git", "depth": 0, - "source": "embedded", - "dependencies": {} + "source": "git", + "dependencies": {}, + "hash": "be024a3b35d038d61fe8edb4807f14a443bc7751" }, "com.cysharp.unitask": { "version": "file:UniTask", diff --git a/UnityProject/ProjectSettings/Obfuz.asset b/UnityProject/ProjectSettings/Obfuz.asset index 560de562..185fbf72 100644 --- a/UnityProject/ProjectSettings/Obfuz.asset +++ b/UnityProject/ProjectSettings/Obfuz.asset @@ -18,10 +18,12 @@ MonoBehaviour: obfuscationProcessCallbackOrder: 10000 assemblySettings: assembliesToObfuscate: - - TEngine.Runtime - - Assembly-CSharp + - GameLogic + - GameProto nonObfuscatedButReferencingObfuscatedAssemblies: + - TEngine.Runtime - Launcher + - Assembly-CSharp additionalAssemblySearchPaths: [] obfuscateObfuzRuntime: 1 obfuscationPassSettings: