public static DynamicMethod CreatePatchedMethod(MethodBase original, List <MethodInfo> prefixes, List <MethodInfo> postfixes, List <MethodInfo> transpilers) { if (HarmonyInstance.DEBUG) { FileLog.Log("PATCHING " + original.DeclaringType + " " + original); } var idx = prefixes.Count() + postfixes.Count(); var patch = DynamicTools.CreateDynamicMethod(original, "_Patch" + idx); var il = patch.GetILGenerator(); GenerateDynamicMethod( original, prefixes, postfixes, transpilers, il, idx ); if (HarmonyInstance.DEBUG) { FileLog.Log("DONE"); FileLog.Log(""); } DynamicTools.PrepareDynamicMethod(patch); return(patch); }
static void GenerateDynamicMethod(MethodBase original, List <MethodInfo> prefixes, List <MethodInfo> postfixes, List <MethodInfo> transpilers, ILGenerator il, int idx) { var originalVariables = DynamicTools.DeclareLocalVariables(original, il); var privateVars = new Dictionary <string, LocalBuilder>(); LocalBuilder resultVariable = null; if (idx > 0) { resultVariable = DynamicTools.DeclareLocalVariable(il, AccessTools.GetReturnedType(original)); privateVars[RESULT_VAR] = resultVariable; } prefixes.ForEach(prefix => { prefix.GetParameters() .Where(patchParam => patchParam.Name == STATE_VAR) .Do(patchParam => { var privateStateVariable = DynamicTools.DeclareLocalVariable(il, patchParam.ParameterType); privateVars[prefix.DeclaringType.FullName] = privateStateVariable; }); }); var afterOriginal1 = il.DefineLabel(); var afterOriginal2 = il.DefineLabel(); var canHaveJump = AddPrefixes(il, original, prefixes, privateVars, afterOriginal2); var copier = new MethodCopier(original, il, originalVariables); foreach (var transpiler in transpilers) { copier.AddTranspiler(transpiler); } copier.Emit(afterOriginal1); Emitter.MarkLabel(il, afterOriginal1); if (resultVariable != null) { Emitter.Emit(il, OpCodes.Stloc, resultVariable); } if (canHaveJump) { Emitter.MarkLabel(il, afterOriginal2); } AddPostfixes(il, original, postfixes, privateVars); if (resultVariable != null) { Emitter.Emit(il, OpCodes.Ldloc, resultVariable); } Emitter.Emit(il, OpCodes.Ret); }
public static DynamicMethod CreatePatchedMethod(MethodBase original, List <MethodInfo> prefixes, List <MethodInfo> postfixes, List <IILProcessor> processors) { var idx = prefixes.Count() + postfixes.Count(); var patch = DynamicTools.CreateDynamicMethod(original, "_Patch" + idx); var il = patch.GetILGenerator(); var originalVariables = DynamicTools.DeclareLocalVariables(original, il); var resultVariable = DynamicTools.DeclareReturnVar(original, il); // TODO: this is broken because it has only one var for all patches together. // to make this useful, we need one var for each patch pair var privateStateVariable = DeclarePrivateStateVar(il); var privateVars = new Dictionary <string, LocalBuilder>(); privateVars[RESULT_VAR] = resultVariable; privateVars[STATE_VAR] = privateStateVariable; var afterOriginal1 = il.DefineLabel(); var afterOriginal2 = il.DefineLabel(); AddPrefixes(il, original, prefixes, privateVars, afterOriginal2); var copier = new MethodCopier(original, patch, originalVariables); foreach (var processor in processors) { copier.AddReplacement(processor); } copier.AddReplacement(new RetToBrAfterProcessor(afterOriginal1)); copier.Emit(); il.MarkLabel(afterOriginal1); if (resultVariable != null) { il.Emit(OpCodes.Stloc, resultVariable); } il.MarkLabel(afterOriginal2); AddPostfixes(il, original, postfixes, privateVars); if (resultVariable != null) { il.Emit(OpCodes.Ldloc, resultVariable); } il.Emit(OpCodes.Ret); DynamicTools.PrepareDynamicMethod(patch); return(patch); }
public static DynamicMethod CreatePatchedMethod(MethodBase original, MethodInfo postfix) { var patch = DynamicTools.CreateDynamicMethod(original, "_Patch"); var il = patch.GetILGenerator(); var originalVariables = DynamicTools.DeclareLocalVariables(original, il); var privateVars = new Dictionary <string, LocalBuilder>(); LocalBuilder resultVariable = null; if (postfix != null) { resultVariable = DynamicTools.DeclareLocalVariable(il, AccessTools.GetReturnedType(original)); privateVars[RESULT_VAR] = resultVariable; } var afterOriginal1 = il.DefineLabel(); var copier = new MethodCopier(original, patch, originalVariables); copier.Emit(afterOriginal1); Emitter.MarkLabel(il, afterOriginal1); if (resultVariable != null) { Emitter.Emit(il, OpCodes.Stloc, resultVariable); } AddPostfix(il, original, postfix, privateVars); if (resultVariable != null) { Emitter.Emit(il, OpCodes.Ldloc, resultVariable); } Emitter.Emit(il, OpCodes.Ret); DynamicTools.PrepareDynamicMethod(patch); return(patch); }
private static DynamicMethod CreateIl2CppShim(DynamicMethod original, Type owner) { var patchName = original.Name + "_il2cpp"; var parameters = original.GetParameters(); var result = parameters.Types().ToList(); var origParamTypes = result.ToArray(); var paramTypes = new Type[origParamTypes.Length]; for (int i = 0; i < paramTypes.Length; ++i) { paramTypes[i] = UnhollowerSupport.IsGeneratedAssemblyType(origParamTypes[i]) ? typeof(IntPtr) : origParamTypes[i]; } var origReturnType = AccessTools.GetReturnedType(original); var returnType = UnhollowerSupport.IsGeneratedAssemblyType(origReturnType) ? typeof(IntPtr) : origReturnType; DynamicMethod method; method = new DynamicMethod( patchName, MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, returnType, paramTypes, owner, true ); for (var i = 0; i < parameters.Length; i++) { method.DefineParameter(i + 1, parameters[i].Attributes, parameters[i].Name); } var il = method.GetILGenerator(); // Load arguments, invoking the IntPrt -> Il2CppObject constructor for IL2CPP types for (int i = 0; i < origParamTypes.Length; ++i) { Emitter.Emit(il, OpCodes.Ldarg, i); if (UnhollowerSupport.IsGeneratedAssemblyType(origParamTypes[i])) { Emitter.Emit(il, OpCodes.Newobj, Il2CppConstuctor(origParamTypes[i])); } } // Call the original patch with the now-correct types Emitter.Emit(il, OpCodes.Call, original); // If needed, unwrap the return value; then return if (UnhollowerSupport.IsGeneratedAssemblyType(origReturnType)) { var pointerGetter = AccessTools.DeclaredProperty(UnhollowerSupport.Il2CppObjectBaseType, "Pointer").GetGetMethod(); Emitter.Emit(il, OpCodes.Call, pointerGetter); } Emitter.Emit(il, OpCodes.Ret); DynamicTools.PrepareDynamicMethod(method); return(method); }
public static DynamicMethod CreatePatchedMethod(MethodBase original, string harmonyInstanceID, List <MethodInfo> prefixes, List <MethodInfo> postfixes, List <MethodInfo> transpilers) { try { if (HarmonyInstance.DEBUG) { FileLog.LogBuffered("### Patch " + original.DeclaringType + ", " + original); } bool isIl2Cpp = original.DeclaringType.IsSubclassOf(typeof(Il2CppObjectBase)); if (isIl2Cpp && transpilers.Count > 0) { throw new NotSupportedException("IL2CPP patches cannot use transpilers (got " + transpilers.Count + ")"); } var idx = prefixes.Count() + postfixes.Count(); var patch = DynamicTools.CreateDynamicMethod(original, "_Patch" + idx, isIl2Cpp); if (patch == null) { return(null); } var il = patch.GetILGenerator(); // for debugging AssemblyBuilder assemblyBuilder = null; TypeBuilder typeBuilder = null; if (DEBUG_METHOD_GENERATION_BY_DLL_CREATION) { il = DynamicTools.CreateSaveableMethod(original, "_Patch" + idx, out assemblyBuilder, out typeBuilder); } var originalVariables = DynamicTools.DeclareLocalVariables(original, il); var privateVars = new Dictionary <string, LocalBuilder>(); LocalBuilder resultVariable = null; if (idx > 0) { resultVariable = DynamicTools.DeclareLocalVariable(il, AccessTools.GetReturnedType(original)); privateVars[RESULT_VAR] = resultVariable; } prefixes.ForEach(prefix => { prefix.GetParameters() .Where(patchParam => patchParam.Name == STATE_VAR) .Do(patchParam => { var privateStateVariable = DynamicTools.DeclareLocalVariable(il, patchParam.ParameterType); privateVars[prefix.DeclaringType.FullName] = privateStateVariable; }); }); var skipOriginalLabel = il.DefineLabel(); var canHaveJump = AddPrefixes(il, original, prefixes, privateVars, skipOriginalLabel, isIl2Cpp); var copier = new MethodCopier(original, il, originalVariables); foreach (var transpiler in transpilers) { copier.AddTranspiler(transpiler); } var endLabels = new List <Label>(); var endBlocks = new List <ExceptionBlock>(); copier.Finalize(endLabels, endBlocks); foreach (var label in endLabels) { Emitter.MarkLabel(il, label); } foreach (var block in endBlocks) { Emitter.MarkBlockAfter(il, block); } if (resultVariable != null) { Emitter.Emit(il, OpCodes.Stloc, resultVariable); } if (canHaveJump) { Emitter.MarkLabel(il, skipOriginalLabel); } AddPostfixes(il, original, postfixes, privateVars, false, isIl2Cpp); if (resultVariable != null) { Emitter.Emit(il, OpCodes.Ldloc, resultVariable); } AddPostfixes(il, original, postfixes, privateVars, true, isIl2Cpp); Emitter.Emit(il, OpCodes.Ret); if (HarmonyInstance.DEBUG) { FileLog.LogBuffered("DONE"); FileLog.LogBuffered(""); FileLog.FlushBuffer(); } // for debugging if (DEBUG_METHOD_GENERATION_BY_DLL_CREATION) { DynamicTools.SaveMethod(assemblyBuilder, typeBuilder); return(null); } DynamicTools.PrepareDynamicMethod(patch); return(patch); } catch (Exception ex) { throw new Exception("Exception from HarmonyInstance \"" + harmonyInstanceID + "\"", ex); } finally { if (HarmonyInstance.DEBUG) { FileLog.FlushBuffer(); } } }
private static DynamicMethod CreateIl2CppShim(DynamicMethod patch, MethodBase original) { var patchName = patch.Name + "_il2cpp"; var parameters = patch.GetParameters(); var result = parameters.Types().ToList(); var origParamTypes = result.ToArray(); var paramTypes = new Type[origParamTypes.Length]; for (int i = 0; i < paramTypes.Length; ++i) { paramTypes[i] = Il2CppTypeForPatchType(origParamTypes[i]); } var origReturnType = AccessTools.GetReturnedType(patch); var returnType = Il2CppTypeForPatchType(origReturnType); DynamicMethod method = new DynamicMethod( patchName, MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, returnType, paramTypes, original.DeclaringType, true ); for (var i = 0; i < parameters.Length; i++) { method.DefineParameter(i + 1, parameters[i].Attributes, parameters[i].Name); } var il = method.GetILGenerator(); LocalBuilder[] byRefValues = new LocalBuilder[parameters.Length]; LocalBuilder returnLocal = null; if (origReturnType != typeof(void)) { returnLocal = il.DeclareLocal(origReturnType); Emitter.LogLocalVariable(il, returnLocal); } LocalBuilder exceptionLocal = il.DeclareLocal(typeof(Exception)); Emitter.LogLocalVariable(il, exceptionLocal); // Start a try-block for the call to the original patch Emitter.MarkBlockBefore(il, new ExceptionBlock(ExceptionBlockType.BeginExceptionBlock, null), out _); // Load arguments, invoking the IntPrt -> Il2CppObject constructor for IL2CPP types for (int i = 0; i < origParamTypes.Length; ++i) { Emitter.Emit(il, OpCodes.Ldarg, i); ConvertArgument(il, origParamTypes[i], ref byRefValues[i]); if (byRefValues[i] != null) { Emitter.LogLocalVariable(il, byRefValues[i]); } } // Call the original patch with the now-correct types Emitter.Emit(il, OpCodes.Call, patch); // Store the result, if any if (returnLocal != null) { Emitter.Emit(il, OpCodes.Stloc, returnLocal); } // Catch any exceptions that may have been thrown Emitter.MarkBlockBefore(il, new ExceptionBlock(ExceptionBlockType.BeginCatchBlock, typeof(Exception)), out _); // MelonModLogger.LogError("Exception in ...\n" + exception.ToString()); Emitter.Emit(il, OpCodes.Stloc, exceptionLocal); Emitter.Emit(il, OpCodes.Ldstr, $"Exception in Harmony patch of method {original.FullDescription()}:\n"); Emitter.Emit(il, OpCodes.Ldloc, exceptionLocal); Emitter.Emit(il, OpCodes.Call, AccessTools.DeclaredMethod(typeof(Exception), "ToString", new Type[0])); Emitter.Emit(il, OpCodes.Call, AccessTools.DeclaredMethod(typeof(string), "Concat", new Type[] { typeof(string), typeof(string) })); Emitter.Emit(il, OpCodes.Call, AccessTools.DeclaredMethod(typeof(MelonModLogger), "LogError", new Type[] { typeof(string) })); // Close the exception block Emitter.MarkBlockAfter(il, new ExceptionBlock(ExceptionBlockType.EndExceptionBlock, null)); // Write back the pointers of ref arguments for (int i = 0; i < parameters.Length; ++i) { if (byRefValues[i] == null) { continue; } Emitter.Emit(il, OpCodes.Ldarg, i); // -> [intptr*] Emitter.Emit(il, OpCodes.Ldloc, byRefValues[i]); // -> [intptr*, obj] if (origParamTypes[i].GetElementType() == typeof(string)) { Emitter.Emit(il, OpCodes.Call, UnhollowerSupport.ManagedStringToIl2CppMethod); // -> [intptr*, intptr] } else { Emitter.Emit(il, OpCodes.Call, UnhollowerSupport.Il2CppObjectBaseToPtrMethod); // -> [intptr*, intptr] } Emitter.Emit(il, OpCodes.Stind_I); // -> [] } // Load the return value, if any, and unwrap it if required if (returnLocal != null) { Emitter.Emit(il, OpCodes.Ldloc, returnLocal); ConvertReturnValue(il, origReturnType); } Emitter.Emit(il, OpCodes.Ret); DynamicTools.PrepareDynamicMethod(method); return(method); }
public static DynamicMethod CreatePatchedMethod(MethodBase original, List <MethodInfo> prefixes, List <MethodInfo> postfixes, List <TranspilerImpl> transpilers, PatchFlags flags) { if (HarmonyInstance.DEBUG) { FileLog.Log("PATCHING " + original.DeclaringType + " " + original); } var idx = prefixes.Count() + postfixes.Count(); var patch = DynamicTools.CreateDynamicMethod(original, "_Patch" + idx); var il = patch.GetILGenerator(); var originalVariables = DynamicTools.DeclareLocalVariables(original, il); var privateVars = new Dictionary <string, LocalBuilder>(); LocalBuilder resultVariable = null; if (idx > 0) { resultVariable = DynamicTools.DeclareLocalVariable(il, AccessTools.GetReturnedType(original)); privateVars[RESULT_VAR] = resultVariable; } prefixes.ForEach(prefix => { prefix.GetParameters() .Where(patchParam => patchParam.Name == STATE_VAR) .Do(patchParam => { var privateStateVariable = DynamicTools.DeclareLocalVariable(il, patchParam.ParameterType); privateVars[prefix.DeclaringType.FullName] = privateStateVariable; }); }); var afterOriginal1 = il.DefineLabel(); var afterOriginal2 = il.DefineLabel(); bool canHaveJump = false; if (flags.HasFlag(PatchFlags.PF_Detour) == false) { canHaveJump = AddPrefixes(il, original, prefixes, privateVars, afterOriginal2); if (flags.HasFlag(PatchFlags.PF_NoOrigin) == false) { var copier = new MethodCopier(original, patch, originalVariables); foreach (var transpiler in transpilers) { copier.AddTranspiler(transpiler); } copier.Emit(afterOriginal1); Emitter.MarkLabel(il, afterOriginal1); if (resultVariable != null) { Emitter.Emit(il, OpCodes.Stloc, resultVariable); } } } if (canHaveJump) { Emitter.MarkLabel(il, afterOriginal2); } if (AddPostfixes(il, original, postfixes, privateVars)) { if (resultVariable != null) { Emitter.Emit(il, OpCodes.Stloc, resultVariable); } } if (resultVariable != null) { Emitter.Emit(il, OpCodes.Ldloc, resultVariable); } Emitter.Emit(il, OpCodes.Ret); if (HarmonyInstance.DEBUG) { FileLog.Log("DONE"); FileLog.Log(""); } DynamicTools.PrepareDynamicMethod(patch); return(patch); }
public static DynamicMethod CreatePatchedMethod(MethodBase original, string harmonyInstanceID, List <MethodInfo> prefixes, List <MethodInfo> postfixes, List <MethodInfo> transpilers) { Memory.MarkForNoInlining(original); if (original == null) { throw new ArgumentNullException(nameof(original), "Original method is null. Did you specify it correctly?"); } try { if (HarmonyInstance.DEBUG) { FileLog.LogBuffered("### Patch " + original.DeclaringType + ", " + original); FileLog.FlushBuffer(); } var idx = prefixes.Count() + postfixes.Count(); var firstArgIsReturnBuffer = NativeThisPointer.NeedsNativeThisPointerFix(original); var returnType = AccessTools.GetReturnedType(original); var patch = DynamicTools.CreateDynamicMethod(original, "_Patch" + idx); if (patch == null) { return(null); } var il = patch.GetILGenerator(); var originalVariables = DynamicTools.DeclareLocalVariables(original, il); var privateVars = new Dictionary <string, LocalBuilder>(); LocalBuilder resultVariable = null; if (idx > 0) { resultVariable = DynamicTools.DeclareLocalVariable(il, returnType); privateVars[RESULT_VAR] = resultVariable; } prefixes.Union(postfixes).ToList().ForEach(fix => { if (privateVars.ContainsKey(fix.DeclaringType.FullName) == false) { fix.GetParameters() .Where(patchParam => patchParam.Name == STATE_VAR) .Do(patchParam => { var privateStateVariable = DynamicTools.DeclareLocalVariable(il, patchParam.ParameterType); privateVars[fix.DeclaringType.FullName] = privateStateVariable; }); } }); if (firstArgIsReturnBuffer) { Emitter.Emit(il, original.IsStatic ? OpCodes.Ldarg_0 : OpCodes.Ldarg_1); } var skipOriginalLabel = il.DefineLabel(); var canHaveJump = AddPrefixes(il, original, prefixes, privateVars, skipOriginalLabel); var copier = new MethodCopier(original, il, originalVariables); foreach (var transpiler in transpilers) { copier.AddTranspiler(transpiler); } var endLabels = new List <Label>(); var endBlocks = new List <ExceptionBlock>(); copier.Finalize(endLabels, endBlocks); foreach (var label in endLabels) { Emitter.MarkLabel(il, label); } foreach (var block in endBlocks) { Emitter.MarkBlockAfter(il, block); } if (resultVariable != null) { Emitter.Emit(il, OpCodes.Stloc, resultVariable); } if (canHaveJump) { Emitter.MarkLabel(il, skipOriginalLabel); } AddPostfixes(il, original, postfixes, privateVars, false); if (resultVariable != null) { Emitter.Emit(il, OpCodes.Ldloc, resultVariable); } AddPostfixes(il, original, postfixes, privateVars, true); if (firstArgIsReturnBuffer) { Emitter.Emit(il, OpCodes.Stobj, returnType); } Emitter.Emit(il, OpCodes.Ret); if (HarmonyInstance.DEBUG) { FileLog.LogBuffered("DONE"); FileLog.LogBuffered(""); FileLog.FlushBuffer(); } DynamicTools.PrepareDynamicMethod(patch); return(patch); } catch (Exception ex) { var exceptionString = "Exception from HarmonyInstance \"" + harmonyInstanceID + "\" patching " + original.FullDescription(); if (HarmonyInstance.DEBUG) { FileLog.Log("Exception: " + exceptionString); } throw new Exception(exceptionString, ex); } finally { if (HarmonyInstance.DEBUG) { FileLog.FlushBuffer(); } } }
public static DynamicMethod CreatePatchedMethod(MethodBase original, List <MethodInfo> prefixes, List <MethodInfo> postfixes, List <ICodeProcessor> processors) { if (MethodCopier.DEBUG_OPCODES) { FileLog.Log("PATCHING " + original.DeclaringType + " " + original); } var idx = prefixes.Count() + postfixes.Count(); var patch = DynamicTools.CreateDynamicMethod(original, "_Patch" + idx); var il = patch.GetILGenerator(); var originalVariables = DynamicTools.DeclareLocalVariables(original, il); var resultVariable = DynamicTools.DeclareLocalVariable(il, AccessTools.GetReturnedType(original)); var privateVars = new Dictionary <string, LocalBuilder>(); privateVars[RESULT_VAR] = resultVariable; prefixes.ForEach(prefix => { prefix.GetParameters() .Where(patchParam => patchParam.Name == STATE_VAR) .Do(patchParam => { var privateStateVariable = DynamicTools.DeclareLocalVariable(il, patchParam.ParameterType); privateVars[prefix.DeclaringType.FullName] = privateStateVariable; }); }); var afterOriginal1 = il.DefineLabel(); var afterOriginal2 = il.DefineLabel(); var canHaveJump = AddPrefixes(il, original, prefixes, privateVars, afterOriginal2); var copier = new MethodCopier(original, patch, originalVariables); foreach (var processor in processors) { copier.AddReplacement(processor); } copier.AddReplacement(new RetToBrAfterProcessor(afterOriginal1)); copier.Emit(); Emitter.MarkLabel(il, afterOriginal1); if (resultVariable != null) { Emitter.Emit(il, OpCodes.Stloc, resultVariable); } if (canHaveJump) { Emitter.MarkLabel(il, afterOriginal2); } AddPostfixes(il, original, postfixes, privateVars); if (resultVariable != null) { Emitter.Emit(il, OpCodes.Ldloc, resultVariable); } Emitter.Emit(il, OpCodes.Ret); if (MethodCopier.DEBUG_OPCODES) { FileLog.Log("DONE"); FileLog.Log(""); } DynamicTools.PrepareDynamicMethod(patch); return(patch); }