Beispiel #1
0
        public static LocalBuilder DeclareLocalVariable(ILGenerator il, Type type)
        {
            if (type.IsByRef)
            {
                type = type.GetElementType();
            }

            if (AccessTools.IsClass(type))
            {
                var v = il.DeclareLocal(type);
                Emitter.LogLocalVariable(il, v);
                Emitter.Emit(il, OpCodes.Ldnull);
                Emitter.Emit(il, OpCodes.Stloc, v);
                return(v);
            }
            if (AccessTools.IsStruct(type))
            {
                var v = il.DeclareLocal(type);
                Emitter.LogLocalVariable(il, v);
                Emitter.Emit(il, OpCodes.Ldloca, v);
                Emitter.Emit(il, OpCodes.Initobj, type);
                return(v);
            }
            if (AccessTools.IsValue(type))
            {
                var v = il.DeclareLocal(type);
                Emitter.LogLocalVariable(il, v);
                if (type == typeof(float))
                {
                    Emitter.Emit(il, OpCodes.Ldc_R4, (float)0);
                }
                else if (type == typeof(double))
                {
                    Emitter.Emit(il, OpCodes.Ldc_R8, (double)0);
                }
                else if (type == typeof(long))
                {
                    Emitter.Emit(il, OpCodes.Ldc_I8, (long)0);
                }
                else
                {
                    Emitter.Emit(il, OpCodes.Ldc_I4, 0);
                }
                Emitter.Emit(il, OpCodes.Stloc, v);
                return(v);
            }
            return(null);
        }
Beispiel #2
0
        public static LocalBuilder[] DeclareLocalVariables(MethodBase original, ILGenerator il, bool logOutput = true)
        {
            var vars = original.GetMethodBody()?.LocalVariables;

            if (vars == null)
            {
                return(new LocalBuilder[0]);
            }
            return(vars.Select(lvi =>
            {
                var localBuilder = il.DeclareLocal(lvi.LocalType, lvi.IsPinned);
                if (logOutput)
                {
                    Emitter.LogLocalVariable(il, localBuilder);
                }
                return localBuilder;
            }).ToArray());
        }
Beispiel #3
0
        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);
        }
Beispiel #4
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");
            }
        }