Exemplo n.º 1
0
        internal MethodPatcher(MethodBase original, MethodBase source, List <MethodInfo> prefixes, List <MethodInfo> postfixes, List <MethodInfo> transpilers, List <MethodInfo> finalizers, bool debug)
        {
            if (original == null)
            {
                throw new ArgumentNullException(nameof(original));
            }

            this.debug       = debug;
            this.original    = original;
            this.source      = source;
            this.prefixes    = prefixes;
            this.postfixes   = postfixes;
            this.transpilers = transpilers;
            this.finalizers  = finalizers;

            Memory.MarkForNoInlining(original);

            if (debug)
            {
                FileLog.LogBuffered($"### Patch: {original.FullDescription()}");
                FileLog.FlushBuffer();
            }

            idx = prefixes.Count() + postfixes.Count() + finalizers.Count();
            useStructReturnBuffer = StructReturnBuffer.NeedsFix(original);
            if (debug && useStructReturnBuffer)
            {
                FileLog.Log($"### Note: A buffer for the returned struct is used. That requires an extra IntPtr argument before the first real argument");
            }
            returnType = AccessTools.GetReturnedType(original);
            patch      = CreateDynamicMethod(original, $"_Patch{idx}", debug);
            if (patch == null)
            {
                throw new Exception("Could not create replacement method");
            }

            il      = patch.GetILGenerator();
            emitter = new Emitter(il, debug);
        }
Exemplo n.º 2
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);
            var assemblies = AppDomain.CurrentDomain.GetAssemblies().Where(a => a.FullName.StartsWith("Microsoft.VisualStudio") == false);

            if (type == null)
            {
                type = assemblies
                       .SelectMany(a => GetTypesFromAssembly(a))
                       .FirstOrDefault(t => t.FullName == name);
            }
            if (type == null)
            {
                type = assemblies
                       .SelectMany(a => GetTypesFromAssembly(a))
                       .FirstOrDefault(t => t.Name == name);
            }
            if (type == null && Harmony.DEBUG)
            {
                FileLog.Log("AccessTools.TypeByName: Could not find type named " + name);
            }
            return(type);
        }
Exemplo n.º 3
0
 /// <summary>Removes one unresolved dependency from the least important patch.</summary>
 void CullDependency()
 {
     // Waiting list is already sorted on priority so start from the end.
     // It should always be the last element, otherwise it would not be on the waiting list because
     // it should have been removed by the ProcessWaitingList().
     // But if for some reason it is on the list we will just find the next target.
     for (var i = _waitingList.Count - 1; i >= 0; i--)
     {
         // Find first unresolved dependency and remove it.
         foreach (var afterNode in _waitingList[i].after)
         {
             if (!_handledPatches.Contains(afterNode))
             {
                 _waitingList[i].RemoveAfterDependency(afterNode);
                 if (Harmony.DEBUG)
                 {
                     FileLog.LogBuffered(
                         $"Breaking dependance between {afterNode.innerPatch.patch.FullDescription()} and {_waitingList[i].innerPatch.patch.FullDescription()}");
                 }
                 return;
             }
         }
     }
 }
Exemplo n.º 4
0
        internal MethodInfo CreateReplacement(out Dictionary <int, CodeInstruction> finalInstructions)
        {
            var originalVariables = DeclareLocalVariables(il, source ?? original);
            var privateVars       = new Dictionary <string, LocalBuilder>();

            LocalBuilder resultVariable = null;

            if (idx > 0)
            {
                resultVariable          = DeclareLocalVariable(returnType, true);
                privateVars[RESULT_VAR] = resultVariable;
            }

            Label?       skipOriginalLabel   = null;
            LocalBuilder runOriginalVariable = null;

            if (prefixes.Any(fix => PrefixAffectsOriginal(fix)))
            {
                runOriginalVariable = DeclareLocalVariable(typeof(bool));
                emitter.Emit(OpCodes.Ldc_I4_1);
                emitter.Emit(OpCodes.Stloc, runOriginalVariable);

                skipOriginalLabel = il.DefineLabel();
            }

            prefixes.Union(postfixes).Union(finalizers).ToList().ForEach(fix =>
            {
                if (fix.DeclaringType is object && privateVars.ContainsKey(fix.DeclaringType.FullName) is false)
                {
                    fix.GetParameters()
                    .Where(patchParam => patchParam.Name == STATE_VAR)
                    .Do(patchParam =>
                    {
                        var privateStateVariable = DeclareLocalVariable(patchParam.ParameterType);
                        privateVars[fix.DeclaringType.FullName] = privateStateVariable;
                    });
                }
            });

            LocalBuilder finalizedVariable = null;

            if (finalizers.Any())
            {
                finalizedVariable = DeclareLocalVariable(typeof(bool));

                privateVars[EXCEPTION_VAR] = DeclareLocalVariable(typeof(Exception));

                // begin try
                emitter.MarkBlockBefore(new ExceptionBlock(ExceptionBlockType.BeginExceptionBlock), out _);
            }

            AddPrefixes(privateVars, runOriginalVariable);
            if (skipOriginalLabel.HasValue)
            {
                emitter.Emit(OpCodes.Ldloc, runOriginalVariable);
                emitter.Emit(OpCodes.Brfalse, skipOriginalLabel.Value);
            }

            var copier = new MethodCopier(source ?? original, il, originalVariables);

            copier.SetArgumentShift(useStructReturnBuffer);
            copier.SetDebugging(debug);

            foreach (var transpiler in transpilers)
            {
                copier.AddTranspiler(transpiler);
            }

            var endLabels = new List <Label>();

            _ = copier.Finalize(emitter, endLabels, out var hasReturnCode);

            foreach (var label in endLabels)
            {
                emitter.MarkLabel(label);
            }
            if (resultVariable is object)
            {
                emitter.Emit(OpCodes.Stloc, resultVariable);
            }
            if (skipOriginalLabel.HasValue)
            {
                emitter.MarkLabel(skipOriginalLabel.Value);
            }

            _ = AddPostfixes(privateVars, false);

            if (resultVariable is object)
            {
                emitter.Emit(OpCodes.Ldloc, resultVariable);
            }

            var needsToStorePassthroughResult = AddPostfixes(privateVars, true);

            var hasFinalizers = finalizers.Any();

            if (hasFinalizers)
            {
                if (needsToStorePassthroughResult)
                {
                    emitter.Emit(OpCodes.Stloc, resultVariable);
                    emitter.Emit(OpCodes.Ldloc, resultVariable);
                }

                _ = AddFinalizers(privateVars, false);
                emitter.Emit(OpCodes.Ldc_I4_1);
                emitter.Emit(OpCodes.Stloc, finalizedVariable);
                var noExceptionLabel1 = il.DefineLabel();
                emitter.Emit(OpCodes.Ldloc, privateVars[EXCEPTION_VAR]);
                emitter.Emit(OpCodes.Brfalse, noExceptionLabel1);
                emitter.Emit(OpCodes.Ldloc, privateVars[EXCEPTION_VAR]);
                emitter.Emit(OpCodes.Throw);
                emitter.MarkLabel(noExceptionLabel1);

                // end try, begin catch
                emitter.MarkBlockBefore(new ExceptionBlock(ExceptionBlockType.BeginCatchBlock), out var label);
                emitter.Emit(OpCodes.Stloc, privateVars[EXCEPTION_VAR]);

                emitter.Emit(OpCodes.Ldloc, finalizedVariable);
                var endFinalizerLabel = il.DefineLabel();
                emitter.Emit(OpCodes.Brtrue, endFinalizerLabel);

                var rethrowPossible = AddFinalizers(privateVars, true);

                emitter.MarkLabel(endFinalizerLabel);

                var noExceptionLabel2 = il.DefineLabel();
                emitter.Emit(OpCodes.Ldloc, privateVars[EXCEPTION_VAR]);
                emitter.Emit(OpCodes.Brfalse, noExceptionLabel2);
                if (rethrowPossible)
                {
                    emitter.Emit(OpCodes.Rethrow);
                }
                else
                {
                    emitter.Emit(OpCodes.Ldloc, privateVars[EXCEPTION_VAR]);
                    emitter.Emit(OpCodes.Throw);
                }
                emitter.MarkLabel(noExceptionLabel2);

                // end catch
                emitter.MarkBlockAfter(new ExceptionBlock(ExceptionBlockType.EndExceptionBlock));

                if (resultVariable is object)
                {
                    emitter.Emit(OpCodes.Ldloc, resultVariable);
                }
            }

            if (useStructReturnBuffer)
            {
                var tmpVar = DeclareLocalVariable(returnType);
                emitter.Emit(OpCodes.Stloc, tmpVar);
                emitter.Emit(original.IsStatic ? OpCodes.Ldarg_0 : OpCodes.Ldarg_1);
                emitter.Emit(OpCodes.Ldloc, tmpVar);
                emitter.Emit(OpCodes.Stobj, returnType);                 // store result into ref
            }

            if (hasFinalizers || hasReturnCode)
            {
                emitter.Emit(OpCodes.Ret);
            }

            finalInstructions = emitter.GetInstructions();

            if (debug)
            {
                FileLog.LogBuffered("DONE");
                FileLog.LogBuffered("");
                FileLog.FlushBuffer();
            }

            return(patch.Generate().Pin());
        }
Exemplo n.º 5
0
        internal static DynamicMethodDefinition CreateDynamicMethod(MethodBase original, string suffix, bool debug)
        {
            if (original is null)
            {
                throw new ArgumentNullException(nameof(original));
            }
            var useStructReturnBuffer = StructReturnBuffer.NeedsFix(original);

            var patchName = $"{original.DeclaringType?.FullName}.{original.Name}{suffix}";

            patchName = patchName.Replace("<>", "");

            var parameters     = original.GetParameters();
            var parameterTypes = new List <Type>();

            parameterTypes.AddRange(parameters.Types());
            if (useStructReturnBuffer)
            {
                parameterTypes.Insert(0, typeof(IntPtr));
            }
            if (original.IsStatic is false)
            {
                if (AccessTools.IsStruct(original.DeclaringType))
                {
                    parameterTypes.Insert(0, original.DeclaringType.MakeByRefType());
                }
                else
                {
                    parameterTypes.Insert(0, original.DeclaringType);
                }
            }

            var returnType = useStructReturnBuffer ? typeof(void) : AccessTools.GetReturnedType(original);

            var method = new DynamicMethodDefinition(
                patchName,
                returnType,
                parameterTypes.ToArray()
                )
            {
                OwnerType = original.DeclaringType
            };

            var offset = (original.IsStatic ? 0 : 1) + (useStructReturnBuffer ? 1 : 0);

            if (useStructReturnBuffer)
            {
                method.Definition.Parameters[original.IsStatic ? 0 : 1].Name = "retbuf";
            }
            if (!original.IsStatic)
            {
                method.Definition.Parameters[0].Name = "this";
            }
            for (var i = 0; i < parameters.Length; i++)
            {
                var param = method.Definition.Parameters[i + offset];
                param.Attributes = (Mono.Cecil.ParameterAttributes)parameters[i].Attributes;
                param.Name       = parameters[i].Name;
            }

            if (debug)
            {
                var parameterStrings = parameterTypes.Select(p => p.FullDescription()).ToList();
                if (parameterTypes.Count == method.Definition.Parameters.Count)
                {
                    for (var i = 0; i < parameterTypes.Count; i++)
                    {
                        parameterStrings[i] += $" {method.Definition.Parameters[i].Name}";
                    }
                }
                FileLog.Log($"### Replacement: static {returnType.FullDescription()} {original.DeclaringType.FullName}::{patchName}({parameterStrings.Join()})");
            }

            return(method);
        }
Exemplo n.º 6
0
        internal static MethodInfo CreatePatchedMethod(MethodBase original, MethodBase source, string harmonyInstanceID, List <MethodInfo> prefixes, List <MethodInfo> postfixes, List <MethodInfo> transpilers, List <MethodInfo> finalizers)
        {
            try
            {
                if (original == null)
                {
                    throw new ArgumentNullException(nameof(original));
                }

                Memory.MarkForNoInlining(original);

                if (Harmony.DEBUG)
                {
                    FileLog.LogBuffered($"### Patch {original.FullDescription()}");
                    FileLog.FlushBuffer();
                }

                var idx = prefixes.Count() + postfixes.Count() + finalizers.Count();
                var firstArgIsReturnBuffer = NativeThisPointer.NeedsNativeThisPointerFix(original);
                var returnType             = AccessTools.GetReturnedType(original);
                var hasFinalizers          = finalizers.Any();
                var patch = DynamicTools.CreateDynamicMethod(original, $"_Patch{idx}");
                if (patch == null)
                {
                    return(null);
                }

                var il = patch.GetILGenerator();

                var originalVariables = DynamicTools.DeclareLocalVariables(source ?? 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).Union(finalizers).ToList().ForEach(fix =>
                {
                    if (fix.DeclaringType != null && 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;
                        });
                    }
                });

                LocalBuilder finalizedVariable = null;
                if (hasFinalizers)
                {
                    finalizedVariable = DynamicTools.DeclareLocalVariable(il, typeof(bool));

                    privateVars[EXCEPTION_VAR] = DynamicTools.DeclareLocalVariable(il, typeof(Exception));

                    // begin try
                    Emitter.MarkBlockBefore(il, new ExceptionBlock(ExceptionBlockType.BeginExceptionBlock), out _);
                }

                if (firstArgIsReturnBuffer)
                {
                    Emitter.Emit(il, OpCodes.Ldarg_1);                     // load ref to return value
                }
                var skipOriginalLabel = il.DefineLabel();
                var canHaveJump       = AddPrefixes(il, original, prefixes, privateVars, skipOriginalLabel);

                var copier = new MethodCopier(source ?? original, il, originalVariables);
                foreach (var transpiler in transpilers)
                {
                    copier.AddTranspiler(transpiler);
                }
                if (firstArgIsReturnBuffer)
                {
                    copier.AddTranspiler(NativeThisPointer.m_ArgumentShiftTranspiler);
                }

                var endLabels = new List <Label>();
                copier.Finalize(endLabels);

                foreach (var label in endLabels)
                {
                    Emitter.MarkLabel(il, label);
                }
                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 (hasFinalizers)
                {
                    _ = AddFinalizers(il, original, finalizers, privateVars, false);
                    Emitter.Emit(il, OpCodes.Ldc_I4_1);
                    Emitter.Emit(il, OpCodes.Stloc, finalizedVariable);
                    var noExceptionLabel1 = il.DefineLabel();
                    Emitter.Emit(il, OpCodes.Ldloc, privateVars[EXCEPTION_VAR]);
                    Emitter.Emit(il, OpCodes.Brfalse, noExceptionLabel1);
                    Emitter.Emit(il, OpCodes.Ldloc, privateVars[EXCEPTION_VAR]);
                    Emitter.Emit(il, OpCodes.Throw);
                    Emitter.MarkLabel(il, noExceptionLabel1);

                    // end try, begin catch
                    Emitter.MarkBlockBefore(il, new ExceptionBlock(ExceptionBlockType.BeginCatchBlock), out var label);
                    Emitter.Emit(il, OpCodes.Stloc, privateVars[EXCEPTION_VAR]);

                    Emitter.Emit(il, OpCodes.Ldloc, finalizedVariable);
                    var endFinalizerLabel = il.DefineLabel();
                    Emitter.Emit(il, OpCodes.Brtrue, endFinalizerLabel);

                    var rethrowPossible = AddFinalizers(il, original, finalizers, privateVars, true);

                    Emitter.MarkLabel(il, endFinalizerLabel);

                    var noExceptionLabel2 = il.DefineLabel();
                    Emitter.Emit(il, OpCodes.Ldloc, privateVars[EXCEPTION_VAR]);
                    Emitter.Emit(il, OpCodes.Brfalse, noExceptionLabel2);
                    if (rethrowPossible)
                    {
                        Emitter.Emit(il, OpCodes.Rethrow);
                    }
                    else
                    {
                        Emitter.Emit(il, OpCodes.Ldloc, privateVars[EXCEPTION_VAR]);
                        Emitter.Emit(il, OpCodes.Throw);
                    }
                    Emitter.MarkLabel(il, noExceptionLabel2);

                    // end catch
                    Emitter.MarkBlockAfter(il, new ExceptionBlock(ExceptionBlockType.EndExceptionBlock));

                    if (resultVariable != null)
                    {
                        Emitter.Emit(il, OpCodes.Ldloc, resultVariable);
                    }
                }

                if (firstArgIsReturnBuffer)
                {
                    Emitter.Emit(il, OpCodes.Stobj, returnType);                     // store result into ref
                }
                Emitter.Emit(il, OpCodes.Ret);

                if (Harmony.DEBUG)
                {
                    FileLog.LogBuffered("DONE");
                    FileLog.LogBuffered("");
                    FileLog.FlushBuffer();
                }

                return(patch.Generate().Pin());
            }
            catch (Exception ex)
            {
                var exceptionString = $"Exception from HarmonyInstance \"{harmonyInstanceID}\" patching {original.FullDescription()}: {ex}";
                if (Harmony.DEBUG)
                {
                    var savedIndentLevel = FileLog.indentLevel;
                    FileLog.indentLevel = 0;
                    FileLog.Log(exceptionString);
                    FileLog.indentLevel = savedIndentLevel;
                }

                throw new Exception(exceptionString, ex);
            }
            finally
            {
                if (Harmony.DEBUG)
                {
                    FileLog.FlushBuffer();
                }
            }
        }
Exemplo n.º 7
0
        internal MethodInfo CreateReplacement(out Dictionary <int, CodeInstruction> finalInstructions)
        {
            var originalVariables = DeclareLocalVariables(source ?? original);
            var privateVars       = new Dictionary <string, LocalBuilder>();

            LocalBuilder resultVariable = null;

            if (idx > 0)
            {
                resultVariable          = DeclareLocalVariable(returnType);
                privateVars[RESULT_VAR] = resultVariable;
            }

            prefixes.Union(postfixes).Union(finalizers).ToList().ForEach(fix =>
            {
                if (fix.DeclaringType != null && privateVars.ContainsKey(fix.DeclaringType.FullName) == false)
                {
                    fix.GetParameters()
                    .Where(patchParam => patchParam.Name == STATE_VAR)
                    .Do(patchParam =>
                    {
                        var privateStateVariable = DeclareLocalVariable(patchParam.ParameterType);
                        privateVars[fix.DeclaringType.FullName] = privateStateVariable;
                    });
                }
            });

            LocalBuilder finalizedVariable = null;

            if (finalizers.Any())
            {
                finalizedVariable = DeclareLocalVariable(typeof(bool));

                privateVars[EXCEPTION_VAR] = DeclareLocalVariable(typeof(Exception));

                // begin try
                emitter.MarkBlockBefore(new ExceptionBlock(ExceptionBlockType.BeginExceptionBlock), out _);
            }

            if (firstArgIsReturnBuffer)
            {
                emitter.Emit(original.IsStatic ? OpCodes.Ldarg_0 : OpCodes.Ldarg_1);                 // load ref to return value
            }
            var skipOriginalLabel = il.DefineLabel();
            var canHaveJump       = AddPrefixes(privateVars, skipOriginalLabel);

            var copier = new MethodCopier(source ?? original, il, originalVariables);

            foreach (var transpiler in transpilers)
            {
                copier.AddTranspiler(transpiler);
            }
            if (firstArgIsReturnBuffer)
            {
                if (original.IsStatic)
                {
                    copier.AddTranspiler(NativeThisPointer.m_ArgumentShiftTranspilerStatic);
                }
                else
                {
                    copier.AddTranspiler(NativeThisPointer.m_ArgumentShiftTranspilerInstance);
                }
            }

            var endLabels = new List <Label>();

            copier.Finalize(emitter, endLabels, out var endingReturn);

            foreach (var label in endLabels)
            {
                emitter.MarkLabel(label);
            }
            if (resultVariable != null)
            {
                emitter.Emit(OpCodes.Stloc, resultVariable);
            }
            if (canHaveJump)
            {
                emitter.MarkLabel(skipOriginalLabel);
            }

            AddPostfixes(privateVars, false);

            if (resultVariable != null)
            {
                emitter.Emit(OpCodes.Ldloc, resultVariable);
            }

            AddPostfixes(privateVars, true);

            var hasFinalizers = finalizers.Any();

            if (hasFinalizers)
            {
                _ = AddFinalizers(privateVars, false);
                emitter.Emit(OpCodes.Ldc_I4_1);
                emitter.Emit(OpCodes.Stloc, finalizedVariable);
                var noExceptionLabel1 = il.DefineLabel();
                emitter.Emit(OpCodes.Ldloc, privateVars[EXCEPTION_VAR]);
                emitter.Emit(OpCodes.Brfalse, noExceptionLabel1);
                emitter.Emit(OpCodes.Ldloc, privateVars[EXCEPTION_VAR]);
                emitter.Emit(OpCodes.Throw);
                emitter.MarkLabel(noExceptionLabel1);

                // end try, begin catch
                emitter.MarkBlockBefore(new ExceptionBlock(ExceptionBlockType.BeginCatchBlock), out var label);
                emitter.Emit(OpCodes.Stloc, privateVars[EXCEPTION_VAR]);

                emitter.Emit(OpCodes.Ldloc, finalizedVariable);
                var endFinalizerLabel = il.DefineLabel();
                emitter.Emit(OpCodes.Brtrue, endFinalizerLabel);

                var rethrowPossible = AddFinalizers(privateVars, true);

                emitter.MarkLabel(endFinalizerLabel);

                var noExceptionLabel2 = il.DefineLabel();
                emitter.Emit(OpCodes.Ldloc, privateVars[EXCEPTION_VAR]);
                emitter.Emit(OpCodes.Brfalse, noExceptionLabel2);
                if (rethrowPossible)
                {
                    emitter.Emit(OpCodes.Rethrow);
                }
                else
                {
                    emitter.Emit(OpCodes.Ldloc, privateVars[EXCEPTION_VAR]);
                    emitter.Emit(OpCodes.Throw);
                }
                emitter.MarkLabel(noExceptionLabel2);

                // end catch
                emitter.MarkBlockAfter(new ExceptionBlock(ExceptionBlockType.EndExceptionBlock));

                if (resultVariable != null)
                {
                    emitter.Emit(OpCodes.Ldloc, resultVariable);
                }
            }

            if (firstArgIsReturnBuffer)
            {
                emitter.Emit(OpCodes.Stobj, returnType);                 // store result into ref
            }
            if (hasFinalizers || endingReturn)
            {
                emitter.Emit(OpCodes.Ret);
            }

            finalInstructions = emitter.GetInstructions();

            if (debug)
            {
                FileLog.LogBuffered("DONE");
                FileLog.LogBuffered("");
                FileLog.FlushBuffer();
            }

            return(patch.Generate().Pin());
        }
Exemplo n.º 8
0
        internal List <CodeInstruction> FinalizeILCodes(Emitter emitter, List <MethodInfo> transpilers, List <Label> endLabels, out bool hasReturnCode)
        {
            hasReturnCode = false;
            if (generator == null)
            {
                return(null);
            }

            // 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, argumentShift);

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

            if (emitter == null)
            {
                return(codeInstructions);
            }

            emitter.LogComment("start original");

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

            emitter.LogAllLocalVariables();
            FileLog.LogBuffered(savedLog);

            // pass4 - check for any RET
            //
            hasReturnCode = codeInstructions.Any(code => code.opcode == OpCodes.Ret);

            // pass5 - 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);
            }

            // pass6 - mark labels and exceptions and emit codes
            //
            codeInstructions.Do(codeInstruction =>
            {
                // mark all labels
                codeInstruction.labels.Do(label => emitter.MarkLabel(label));

                // start all exception blocks
                // TODO: we ignore the resulting label because we have no way to use it
                //
                codeInstruction.blocks.Do(block =>
                {
                    emitter.MarkBlockBefore(block, out var 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;
                }

                switch (code.OperandType)
                {
                case OperandType.InlineNone:
                    emitter.Emit(code);
                    break;

                case OperandType.InlineSig:
                    var cecilGenerator = generator.GetProxiedShim <CecilILGenerator>();
                    if (cecilGenerator == null)
                    {
                        // Right now InlineSignatures can only be emitted using MonoMod.Common and its CecilILGenerator.
                        // That is because DynamicMethod's original ILGenerator is very restrictive about the calli opcode.
                        throw new NotSupportedException();
                    }
                    if (operand == null)
                    {
                        throw new Exception($"Wrong null argument: {codeInstruction}");
                    }
                    if ((operand is ICallSiteGenerator) == false)
                    {
                        throw new Exception($"Wrong Emit argument type {operand.GetType()} in {codeInstruction}");
                    }
                    emitter.AddInstruction(code, operand);
                    emitter.LogIL(code, operand);
                    cecilGenerator.Emit(code, (ICallSiteGenerator)operand);
                    break;

                default:
                    if (operand == null)
                    {
                        throw new Exception($"Wrong null argument: {codeInstruction}");
                    }
                    emitter.AddInstruction(code, operand);
                    emitter.LogIL(code, operand);
                    _ = generator.DynEmit(code, operand);
                    break;
                }

                codeInstruction.blocks.Do(block => emitter.MarkBlockAfter(block));
            });

            emitter.LogComment("end original");
            return(codeInstructions);
        }
Exemplo n.º 9
0
        internal void MarkBlockBefore(ExceptionBlock block, out Label?label)
        {
            label = null;
            switch (block.blockType)
            {
            case ExceptionBlockType.BeginExceptionBlock:
                if (debug)
                {
                    FileLog.LogBuffered(".try");
                    FileLog.LogBuffered("{");
                    FileLog.ChangeIndent(1);
                }
                label = il.BeginExceptionBlock();
                return;

            case ExceptionBlockType.BeginCatchBlock:
                if (debug)
                {
                    // fake log a LEAVE code since BeginCatchBlock() does add it
                    LogIL(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 (debug)
                {
                    // fake log a LEAVE code since BeginCatchBlock() does add it
                    LogIL(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 (debug)
                {
                    // fake log a LEAVE code since BeginCatchBlock() does add it
                    LogIL(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 (debug)
                {
                    // fake log a LEAVE code since BeginCatchBlock() does add it
                    LogIL(OpCodes.Leave, new LeaveTry());

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

                    FileLog.LogBuffered(".finally");
                    FileLog.LogBuffered("{");
                    FileLog.ChangeIndent(1);
                }
                il.BeginFinallyBlock();
                return;
            }
        }
Exemplo n.º 10
0
        internal void FinalizeILCodes(List <MethodInfo> transpilers, List <Label> endLabels)
        {
            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 (Harmony.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(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 =>
                {
                    Emitter.MarkBlockBefore(generator, block, out var 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 (Harmony.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 (Harmony.DEBUG)
            {
                Emitter.LogComment(generator, "end original");
            }
        }
Exemplo n.º 11
0
        internal static DynamicMethodDefinition CreateDynamicMethod(MethodBase original, string suffix, bool debug)
        {
            if (original == null)
            {
                throw new ArgumentNullException(nameof(original));
            }
            var patchName = original.Name + suffix;

            patchName = patchName.Replace("<>", "");

            var parameters     = original.GetParameters();
            var parameterTypes = parameters.Types().ToList();

            var useStructReturnBuffer = StructReturnBuffer.NeedsFix(original);

            if (useStructReturnBuffer)
            {
                parameterTypes.Insert(0, typeof(IntPtr));
            }

            if (original.IsStatic == false)
            {
                if (AccessTools.IsStruct(original.DeclaringType))
                {
                    parameterTypes.Insert(0, original.DeclaringType.MakeByRefType());
                }
                else
                {
                    parameterTypes.Insert(0, original.DeclaringType);
                }
            }

            var returnType = useStructReturnBuffer ? typeof(void) : AccessTools.GetReturnedType(original);

            var method = new DynamicMethodDefinition(
                patchName,
                returnType,
                parameterTypes.ToArray()
                )
            {
                OwnerType = original.DeclaringType
            };

#if NETSTANDARD2_0 || NETCOREAPP2_0
#else
            var offset = (original.IsStatic ? 0 : 1) + (useStructReturnBuffer ? 1 : 0);
            if (useStructReturnBuffer)
            {
                method.Definition.Parameters[original.IsStatic ? 0 : 1].Name = "retbuf";
            }
            if (!original.IsStatic)
            {
                method.Definition.Parameters[0].Name = "this";
            }
            for (var i = 0; i < parameters.Length; i++)
            {
                var param = method.Definition.Parameters[i + offset];
                param.Attributes = (Mono.Cecil.ParameterAttributes)parameters[i].Attributes;
                param.Name       = parameters[i].Name;
            }
#endif

            if (debug)
            {
                FileLog.LogBuffered($"### Replacement: static {returnType.FullDescription()} {original.DeclaringType.FullName}::{patchName}{parameterTypes.ToArray().Description()}");
            }

            return(method);
        }
Exemplo n.º 12
0
        internal static void LogComment(ILGenerator il, string comment)
        {
            var str = string.Format("{0}// {1}", CodePos(il), comment);

            FileLog.LogBuffered(str);
        }
Exemplo n.º 13
0
        internal static void PatchOldHarmonyMethods()
        {
            var watch = new Stopwatch();

            watch.Start();

            var ourAssembly = new StackTrace(true).GetFrame(1).GetMethod().DeclaringType.Assembly;

            if (Harmony.DEBUG)
            {
                var originalVersion = ourAssembly.GetName().Version;
                var runningVersion  = typeof(SelfPatching).Assembly.GetName().Version;
                if (runningVersion > originalVersion)
                {
                    // log start because FileLog has not done it
                    FileLog.Log("### Harmony v" + originalVersion + " started");
                    FileLog.Log("### Self-patching unnecessary because we are already patched by v" + runningVersion);
                    FileLog.Log("### At " + DateTime.Now.ToString("yyyy-MM-dd hh.mm.ss"));
                    return;
                }
                FileLog.Log("Self-patching started (v" + originalVersion + ")");
            }

            var potentialMethodsToUpgrade = new Dictionary <string, MethodBase>();

            GetAllMethods(ourAssembly)
            .Where(method => method != null && method.GetCustomAttributes(false).Any(attr => IsUpgrade(attr)))
            .Do(method => potentialMethodsToUpgrade.Add(MethodKey(method), method));

            var otherHarmonyAssemblies = AppDomain.CurrentDomain.GetAssemblies()
                                         .Where(assembly => IsHarmonyAssembly(assembly) && assembly != ourAssembly)
                                         .ToList();

            if (Harmony.DEBUG)
            {
                otherHarmonyAssemblies.Do(assembly => FileLog.Log("Found Harmony " + AssemblyInfo(assembly)));

                FileLog.Log("Potential methods to upgrade:");
                potentialMethodsToUpgrade.Values.OrderBy(method => method.FullDescription()).Do(method => FileLog.Log("- " + method.FullDescription()));
            }

            var totalCounter     = 0;
            var potentialCounter = 0;
            var patchedCounter   = 0;

            foreach (var assembly in otherHarmonyAssemblies)
            {
                foreach (var oldMethod in GetAllMethods(assembly))
                {
                    totalCounter++;

                    if (potentialMethodsToUpgrade.TryGetValue(MethodKey(oldMethod), out var newMethod))
                    {
                        var newVersion = GetVersion(newMethod);
                        potentialCounter++;

                        var oldVersion = GetVersion(oldMethod);
                        if (oldVersion < newVersion)
                        {
                            var generics = GetGenericTypes(newMethod);
                            if (generics != null)
                            {
                                foreach (var generic in generics)
                                {
                                    var oldMethodInfo = (oldMethod as MethodInfo).MakeGenericMethod(generic);
                                    var newMethodInfo = (newMethod as MethodInfo).MakeGenericMethod(generic);
                                    if (Harmony.DEBUG)
                                    {
                                        FileLog.Log("Self-patching " + oldMethodInfo.FullDescription() + " with <" + generic.FullName + "> in " + AssemblyInfo(assembly));
                                    }
                                    Memory.DetourMethod(oldMethodInfo, newMethodInfo);
                                }
                                patchedCounter++;
                            }
                            else
                            {
                                if (Harmony.DEBUG)
                                {
                                    FileLog.Log("Self-patching " + oldMethod.FullDescription() + " in " + AssemblyInfo(assembly));
                                }
                                patchedCounter++;
                                Memory.DetourMethod(oldMethod, newMethod);
                            }
                        }
                    }
                }
            }

            if (Harmony.DEBUG)
            {
                FileLog.Log("Self-patched " + patchedCounter + " out of " + totalCounter + " methods (" + (potentialCounter - patchedCounter) + " skipped) in " + watch.ElapsedMilliseconds + "ms");
            }
        }