|
| 1 | +using System; |
| 2 | +using System.CodeDom.Compiler; |
| 3 | +using System.IO; |
| 4 | +using System.Linq; |
| 5 | +using System.Reflection; |
| 6 | +using System.Text; |
| 7 | +using HarmonyLib; |
| 8 | +using Microsoft.CSharp; |
| 9 | +using UnityExplorer.CSConsole; |
| 10 | + |
| 11 | +namespace UnityExplorer.Hooks |
| 12 | +{ |
| 13 | + public class HookInstance |
| 14 | + { |
| 15 | + private static readonly StringBuilder evalOutput = new StringBuilder(); |
| 16 | + private static readonly ScriptEvaluator scriptEvaluator = new ScriptEvaluator(new StringWriter(evalOutput)); |
| 17 | + |
| 18 | + // Instance |
| 19 | + |
| 20 | + public bool Enabled; |
| 21 | + public MethodInfo TargetMethod; |
| 22 | + public string GeneratedSource; |
| 23 | + |
| 24 | + private string shortSignature; |
| 25 | + private PatchProcessor patchProcessor; |
| 26 | + private HarmonyMethod patchDelegate; |
| 27 | + private MethodInfo patchDelegateMethodInfo; |
| 28 | + |
| 29 | + public HookInstance(MethodInfo targetMethod) |
| 30 | + { |
| 31 | + this.TargetMethod = targetMethod; |
| 32 | + this.shortSignature = $"{targetMethod.DeclaringType.Name}.{targetMethod.Name}"; |
| 33 | + GenerateProcessorAndDelegate(); |
| 34 | + Patch(); |
| 35 | + } |
| 36 | + |
| 37 | + private void GenerateProcessorAndDelegate() |
| 38 | + { |
| 39 | + try |
| 40 | + { |
| 41 | + patchProcessor = ExplorerCore.Harmony.CreateProcessor(TargetMethod); |
| 42 | + |
| 43 | + // Dynamically compile the patch method |
| 44 | + |
| 45 | + scriptEvaluator.Run(GeneratePatchSourceCode(TargetMethod)); |
| 46 | + |
| 47 | + // Get the compiled method and check for errors |
| 48 | + |
| 49 | + string output = scriptEvaluator._textWriter.ToString(); |
| 50 | + var outputSplit = output.Split('\n'); |
| 51 | + if (outputSplit.Length >= 2) |
| 52 | + output = outputSplit[outputSplit.Length - 2]; |
| 53 | + evalOutput.Clear(); |
| 54 | + if (ScriptEvaluator._reportPrinter.ErrorsCount > 0) |
| 55 | + throw new FormatException($"Unable to compile the code. Evaluator's last output was:\r\n{output}"); |
| 56 | + |
| 57 | + // Could publicize MCS to avoid this reflection, but not bothering for now |
| 58 | + var source = (Mono.CSharp.CompilationSourceFile)ReflectionUtility.GetFieldInfo(typeof(Mono.CSharp.Evaluator), "source_file") |
| 59 | + .GetValue(scriptEvaluator); |
| 60 | + var type = (Mono.CSharp.Class)source.Containers.Last(); |
| 61 | + var systemType = ((Mono.CSharp.TypeSpec)ReflectionUtility.GetPropertyInfo(typeof(Mono.CSharp.TypeDefinition), "Definition") |
| 62 | + .GetValue(type, null)) |
| 63 | + .GetMetaInfo(); |
| 64 | + |
| 65 | + this.patchDelegateMethodInfo = systemType.GetMethod("Patch", ReflectionUtility.FLAGS); |
| 66 | + |
| 67 | + // Actually create the harmony patch |
| 68 | + this.patchDelegate = new HarmonyMethod(patchDelegateMethodInfo); |
| 69 | + patchProcessor.AddPostfix(patchDelegate); |
| 70 | + } |
| 71 | + catch (Exception ex) |
| 72 | + { |
| 73 | + ExplorerCore.LogWarning($"Exception creating patch processor for target method {TargetMethod.FullDescription()}!\r\n{ex}"); |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + private string GeneratePatchSourceCode(MethodInfo targetMethod) |
| 78 | + { |
| 79 | + var codeBuilder = new StringBuilder(); |
| 80 | + |
| 81 | + codeBuilder.AppendLine($"public class DynamicPatch_{DateTime.Now.Ticks}"); |
| 82 | + codeBuilder.AppendLine("{"); |
| 83 | + |
| 84 | + // Arguments |
| 85 | + |
| 86 | + codeBuilder.Append(" public static void Patch(System.Reflection.MethodBase __originalMethod"); |
| 87 | + |
| 88 | + if (!targetMethod.IsStatic) |
| 89 | + codeBuilder.Append($", {targetMethod.DeclaringType.FullName} __instance"); |
| 90 | + |
| 91 | + if (targetMethod.ReturnType != typeof(void)) |
| 92 | + codeBuilder.Append($", {targetMethod.ReturnType.FullName} __result"); |
| 93 | + |
| 94 | + int paramIdx = 0; |
| 95 | + var parameters = targetMethod.GetParameters(); |
| 96 | + foreach (var param in parameters) |
| 97 | + { |
| 98 | + codeBuilder.Append($", {param.ParameterType.FullName} __{paramIdx}"); |
| 99 | + paramIdx++; |
| 100 | + } |
| 101 | + |
| 102 | + codeBuilder.Append(")\n"); |
| 103 | + |
| 104 | + // Patch body |
| 105 | + |
| 106 | + codeBuilder.AppendLine(" {"); |
| 107 | + |
| 108 | + codeBuilder.AppendLine(" try {"); |
| 109 | + |
| 110 | + // Log message |
| 111 | + |
| 112 | + var logMessage = new StringBuilder(); |
| 113 | + logMessage.AppendLine($"$@\"Patch called: {shortSignature}"); |
| 114 | + |
| 115 | + if (!targetMethod.IsStatic) |
| 116 | + logMessage.AppendLine("__instance: {__instance.ToString()}"); |
| 117 | + |
| 118 | + paramIdx = 0; |
| 119 | + foreach (var param in parameters) |
| 120 | + { |
| 121 | + if (param.ParameterType.IsValueType) |
| 122 | + logMessage.AppendLine($"Parameter {paramIdx}: {{__{paramIdx}.ToString()}}"); |
| 123 | + else |
| 124 | + logMessage.AppendLine($"Parameter {paramIdx}: {{__{paramIdx}?.ToString() ?? \"null\"}}"); |
| 125 | + paramIdx++; |
| 126 | + } |
| 127 | + |
| 128 | + if (targetMethod.ReturnType != typeof(void)) |
| 129 | + { |
| 130 | + if (targetMethod.ReturnType.IsValueType) |
| 131 | + logMessage.AppendLine("Return value: {__result.ToString()}"); |
| 132 | + else |
| 133 | + logMessage.AppendLine("Return value: {__result?.ToString() ?? \"null\"}"); |
| 134 | + } |
| 135 | + |
| 136 | + logMessage.Append('"'); |
| 137 | + |
| 138 | + codeBuilder.AppendLine($" UnityExplorer.ExplorerCore.Log({logMessage});"); |
| 139 | + codeBuilder.AppendLine(" }"); |
| 140 | + codeBuilder.AppendLine(" catch (System.Exception ex) {"); |
| 141 | + codeBuilder.AppendLine($" UnityExplorer.ExplorerCore.LogWarning($\"Exception in patch of {shortSignature}:\\n{{ex}}\");"); |
| 142 | + codeBuilder.AppendLine(" }"); |
| 143 | + |
| 144 | + // End patch body |
| 145 | + |
| 146 | + codeBuilder.AppendLine(" }"); |
| 147 | + |
| 148 | + // End class |
| 149 | + |
| 150 | + codeBuilder.AppendLine("}"); |
| 151 | + |
| 152 | + return GeneratedSource = codeBuilder.ToString(); |
| 153 | + } |
| 154 | + |
| 155 | + public void TogglePatch() |
| 156 | + { |
| 157 | + Enabled = !Enabled; |
| 158 | + if (Enabled) |
| 159 | + Patch(); |
| 160 | + else |
| 161 | + Unpatch(); |
| 162 | + } |
| 163 | + |
| 164 | + public void Patch() |
| 165 | + { |
| 166 | + try |
| 167 | + { |
| 168 | + patchProcessor.Patch(); |
| 169 | + Enabled = true; |
| 170 | + } |
| 171 | + catch (Exception ex) |
| 172 | + { |
| 173 | + ExplorerCore.LogWarning($"Exception hooking method!\r\n{ex}"); |
| 174 | + } |
| 175 | + } |
| 176 | + |
| 177 | + public void Unpatch() |
| 178 | + { |
| 179 | + if (!Enabled) |
| 180 | + return; |
| 181 | + |
| 182 | + try |
| 183 | + { |
| 184 | + this.patchProcessor.Unpatch(patchDelegateMethodInfo); |
| 185 | + Enabled = false; |
| 186 | + } |
| 187 | + catch (Exception ex) |
| 188 | + { |
| 189 | + ExplorerCore.LogWarning($"Exception unpatching method: {ex}"); |
| 190 | + } |
| 191 | + } |
| 192 | + } |
| 193 | +} |
0 commit comments