Esempio n. 1
0
 internal static void LogIL(ILGenerator il, OpCode opCode, object argument)
 {
     if (HarmonyInstance.DEBUG)
     {
         var argStr = FormatArgument(argument);
         var space  = argStr.Length > 0 ? " " : "";
         FileLog.LogBuffered(string.Format("{0}{1}{2}{3}", CodePos(il), opCode, space, argStr));
     }
 }
Esempio n. 2
0
        internal static void MarkBlockAfter(ILGenerator il, ExceptionBlock block)
        {
            if (block.blockType == ExceptionBlockType.EndExceptionBlock)
            {
                if (HarmonyInstance.DEBUG)
                {
                    // fake log a LEAVE code since BeginCatchBlock() does add it
                    LogIL(il, OpCodes.Leave, new LeaveTry());

                    FileLog.ChangeIndent(-1);
                    FileLog.LogBuffered("} // end handler");
                }
                il.EndExceptionBlock();
            }
        }
Esempio n. 3
0
        internal static void LogComment(ILGenerator il, string comment)
        {
            var str = string.Format("{0}// {1}", CodePos(il), comment);

            FileLog.LogBuffered(str);
        }
Esempio n. 4
0
        internal static void MarkBlockBefore(ILGenerator il, ExceptionBlock block, out Label?label)
        {
            label = null;
            switch (block.blockType)
            {
            case ExceptionBlockType.BeginExceptionBlock:
                if (HarmonyInstance.DEBUG)
                {
                    FileLog.LogBuffered(".try");
                    FileLog.LogBuffered("{");
                    FileLog.ChangeIndent(1);
                }
                label = il.BeginExceptionBlock();
                return;

            case ExceptionBlockType.BeginCatchBlock:
                if (HarmonyInstance.DEBUG)
                {
                    // fake log a LEAVE code since BeginCatchBlock() does add it
                    LogIL(il, OpCodes.Leave, new LeaveTry());

                    FileLog.ChangeIndent(-1);
                    FileLog.LogBuffered("} // end try");

                    FileLog.LogBuffered(".catch " + block.catchType);
                    FileLog.LogBuffered("{");
                    FileLog.ChangeIndent(1);
                }
                il.BeginCatchBlock(block.catchType);
                return;

            case ExceptionBlockType.BeginExceptFilterBlock:
                if (HarmonyInstance.DEBUG)
                {
                    // fake log a LEAVE code since BeginCatchBlock() does add it
                    LogIL(il, OpCodes.Leave, new LeaveTry());

                    FileLog.ChangeIndent(-1);
                    FileLog.LogBuffered("} // end try");

                    FileLog.LogBuffered(".filter");
                    FileLog.LogBuffered("{");
                    FileLog.ChangeIndent(1);
                }
                il.BeginExceptFilterBlock();
                return;

            case ExceptionBlockType.BeginFaultBlock:
                if (HarmonyInstance.DEBUG)
                {
                    // fake log a LEAVE code since BeginCatchBlock() does add it
                    LogIL(il, OpCodes.Leave, new LeaveTry());

                    FileLog.ChangeIndent(-1);
                    FileLog.LogBuffered("} // end try");

                    FileLog.LogBuffered(".fault");
                    FileLog.LogBuffered("{");
                    FileLog.ChangeIndent(1);
                }
                il.BeginFaultBlock();
                return;

            case ExceptionBlockType.BeginFinallyBlock:
                if (HarmonyInstance.DEBUG)
                {
                    // fake log a LEAVE code since BeginCatchBlock() does add it
                    LogIL(il, OpCodes.Leave, new LeaveTry());

                    FileLog.ChangeIndent(-1);
                    FileLog.LogBuffered("} // end try");

                    FileLog.LogBuffered(".finally");
                    FileLog.LogBuffered("{");
                    FileLog.ChangeIndent(1);
                }
                il.BeginFinallyBlock();
                return;
            }
        }
Esempio n. 5
0
        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();
                }
            }
        }
Esempio n. 6
0
        internal void FinalizeILCodes(List <MethodInfo> transpilers, List <Label> endLabels, List <ExceptionBlock> endBlocks)
        {
            if (generator == null)
            {
                return;
            }

            // pass1 - define labels and add them to instructions that are target of a jump
            //
            foreach (var ilInstruction in ilInstructions)
            {
                switch (ilInstruction.opcode.OperandType)
                {
                case OperandType.InlineSwitch:
                {
                    var targets = ilInstruction.operand as ILInstruction[];
                    if (targets != null)
                    {
                        var labels = new List <Label>();
                        foreach (var target in targets)
                        {
                            var label = generator.DefineLabel();
                            target.labels.Add(label);
                            labels.Add(label);
                        }
                        ilInstruction.argument = labels.ToArray();
                    }
                    break;
                }

                case OperandType.ShortInlineBrTarget:
                case OperandType.InlineBrTarget:
                {
                    var target = ilInstruction.operand as ILInstruction;
                    if (target != null)
                    {
                        var label = generator.DefineLabel();
                        target.labels.Add(label);
                        ilInstruction.argument = label;
                    }
                    break;
                }
                }
            }

            // pass2 - filter through all processors
            //
            var codeTranspiler = new CodeTranspiler(ilInstructions);

            transpilers.Do(transpiler => codeTranspiler.Add(transpiler));
            var codeInstructions = codeTranspiler.GetResult(generator, method);

            if (HarmonyInstance.DEBUG)
            {
                Emitter.LogComment(generator, "start original");
            }

            // pass3 - log out all new local variables
            //
            var savedLog = FileLog.GetBuffer(true);

            Emitter.AllLocalVariables(generator).Do(local => Emitter.LogLocalVariable(generator, local));
            FileLog.LogBuffered(savedLog);

            // pass4 - remove RET if it appears at the end
            //
            while (true)
            {
                var lastInstruction = codeInstructions.LastOrDefault();
                if (lastInstruction == null || lastInstruction.opcode != OpCodes.Ret)
                {
                    break;
                }

                // remember any existing labels
                endLabels.AddRange(lastInstruction.labels);

                codeInstructions.RemoveAt(codeInstructions.Count - 1);
            }

            // pass5 - mark labels and exceptions and emit codes
            //
            var idx = 0;

            codeInstructions.Do(codeInstruction =>
            {
                // mark all labels
                codeInstruction.labels.Do(label => Emitter.MarkLabel(generator, label));

                // start all exception blocks
                // TODO: we ignore the resulting label because we have no way to use it
                //
                codeInstruction.blocks.Do(block => {
                    Label?label;
                    Emitter.MarkBlockBefore(generator, block, out label);
                });

                var code    = codeInstruction.opcode;
                var operand = codeInstruction.operand;

                // replace RET with a jump to the end (outside this code)
                if (code == OpCodes.Ret)
                {
                    var endLabel = generator.DefineLabel();
                    code         = OpCodes.Br;
                    operand      = endLabel;
                    endLabels.Add(endLabel);
                }

                // replace short jumps with long ones (can be optimized but requires byte counting, not instruction counting)
                if (shortJumps.TryGetValue(code, out var longJump))
                {
                    code = longJump;
                }

                var emitCode = true;

                //if (code == OpCodes.Leave || code == OpCodes.Leave_S)
                //{
                //	// skip LEAVE on EndExceptionBlock
                //	if (codeInstruction.blocks.Any(block => block.blockType == ExceptionBlockType.EndExceptionBlock))
                //		emitCode = false;

                //	// skip LEAVE on next instruction starts a new exception handler and we are already in
                //	if (idx < instructions.Length - 1)
                //		if (instructions[idx + 1].blocks.Any(block => block.blockType != ExceptionBlockType.EndExceptionBlock))
                //			emitCode = false;
                //}

                if (emitCode)
                {
                    switch (code.OperandType)
                    {
                    case OperandType.InlineNone:
                        Emitter.Emit(generator, code);
                        break;

                    case OperandType.InlineSig:

                        // TODO the following will fail because we do not convert the token (operand)
                        // All the decompilers can show the arguments correctly, we just need to find out how
                        //
                        if (operand == null)
                        {
                            throw new Exception("Wrong null argument: " + codeInstruction);
                        }
                        if ((operand is int) == false)
                        {
                            throw new Exception("Wrong Emit argument type " + operand.GetType() + " in " + codeInstruction);
                        }
                        Emitter.Emit(generator, code, (int)operand);

                        /*
                         * // the following will only work if we can convert the original signature token to the required arguments
                         * //
                         * var callingConvention = System.Runtime.InteropServices.CallingConvention.ThisCall;
                         * var returnType = typeof(object);
                         * var parameterTypes = new[] { typeof(object) };
                         * Emitter.EmitCalli(generator, code, callingConvention, returnType, parameterTypes);
                         *
                         * var callingConventions = System.Reflection.CallingConventions.Standard;
                         * var optionalParameterTypes = new[] { typeof(object) };
                         * Emitter.EmitCalli(generator, code, callingConventions, returnType, parameterTypes, optionalParameterTypes);
                         */
                        break;

                    default:
                        if (operand == null)
                        {
                            throw new Exception("Wrong null argument: " + codeInstruction);
                        }
                        var emitMethod = EmitMethodForType(operand.GetType());
                        if (emitMethod == null)
                        {
                            throw new Exception("Unknown Emit argument type " + operand.GetType() + " in " + codeInstruction);
                        }
                        if (HarmonyInstance.DEBUG)
                        {
                            FileLog.LogBuffered(Emitter.CodePos(generator) + code + " " + Emitter.FormatArgument(operand));
                        }
                        emitMethod.Invoke(generator, new object[] { code, operand });
                        break;
                    }
                }

                codeInstruction.blocks.Do(block => Emitter.MarkBlockAfter(generator, block));

                idx++;
            });

            if (HarmonyInstance.DEBUG)
            {
                Emitter.LogComment(generator, "end original");
            }
        }
Esempio n. 7
0
        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();
                }
            }
        }