Пример #1
0
        /// <summary>Gets a type by name. Prefers a full name with namespace but falls back to the first type matching the name otherwise</summary>
        /// <param name="name">The name</param>
        /// <returns>A Type</returns>
        ///
        public static Type TypeByName(string name)
        {
            var type = Type.GetType(name, false);

            if (type == null)
            {
                type = AppDomain.CurrentDomain.GetAssemblies()
                       .SelectMany(x => x.GetTypes())
                       .FirstOrDefault(x => x.FullName == name);
            }
            if (type == null)
            {
                type = AppDomain.CurrentDomain.GetAssemblies()
                       .SelectMany(x => x.GetTypes())
                       .FirstOrDefault(x => x.Name == name);
            }
            if (type == null && HarmonyInstance.DEBUG)
            {
                FileLog.Log("AccessTools.TypeByName: Could not find type named " + name);
            }
            return(type);
        }
Пример #2
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();
                }
            }
        }
Пример #3
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");
            }
        }
Пример #4
0
        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);
        }
Пример #5
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.ForEach(prefix =>
                {
                    prefix.GetParameters()
                    .Where(patchParam => patchParam.Name == STATE_VAR)
                    .Do(patchParam =>
                    {
                        var privateStateVariable = DynamicTools.DeclareLocalVariable(il, patchParam.ParameterType);
                        privateVars[prefix.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();
                }
            }
        }