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

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

            Memory.MarkForNoInlining(original);

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

            idx = prefixes.Count() + postfixes.Count() + finalizers.Count();
            firstArgIsReturnBuffer = NativeThisPointer.NeedsNativeThisPointerFix(original);
            returnType             = AccessTools.GetReturnedType(original);
            patch = CreateDynamicMethod(original, $"_Patch{idx}");
            if (patch == null)
            {
                throw new Exception("Could not create dynamic method");
            }

            il      = patch.GetILGenerator();
            emitter = new Emitter(il);
        }
Ejemplo n.º 2
0
#pragma warning disable IDE0060
#pragma warning disable IDE0051
        static void GetStructReplacement(NativeThisPointer self, IntPtr ptr, IntPtr a, IntPtr b)
#pragma warning restore IDE0051
#pragma warning restore IDE0060
        {
            // Normal argument order:
            // this, a, b

            // If we have a native return buffer pointer, the order is:
            // this, ptr, a, b

            hasNativeThis = a == magicValue && b == magicValue;
        }
Ejemplo n.º 3
0
        internal static DynamicMethodDefinition CreateDynamicMethod(MethodBase original, string suffix)
        {
            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();

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

            var firstArgIsReturnBuffer = NativeThisPointer.NeedsNativeThisPointerFix(original);

            if (firstArgIsReturnBuffer)
            {
                parameterTypes.Insert(0, typeof(IntPtr));
            }
            var returnType = firstArgIsReturnBuffer ? typeof(void) : AccessTools.GetReturnedType(original);

            var method = new DynamicMethodDefinition(
                patchName,
                returnType,
                parameterTypes.ToArray()
                );

#if NETSTANDARD2_0 || NETCOREAPP2_0
#else
            var offset = (original.IsStatic ? 0 : 1) + (firstArgIsReturnBuffer ? 1 : 0);
            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

            return(method);
        }
Ejemplo n.º 4
0
 static bool HasNativeThis()
 {
     if (hasTestResult == false)
     {
         hasNativeThis = false;
         var self        = new NativeThisPointer();
         var original    = AccessTools.DeclaredMethod(typeof(NativeThisPointer), "GetStruct");
         var replacement = AccessTools.DeclaredMethod(typeof(NativeThisPointer), "GetStructReplacement");
         Memory.DetourMethod(original, replacement);
         self.GetStruct(magicValue, magicValue);
         hasTestResult = true;
     }
     return(hasNativeThis);
 }
Ejemplo n.º 5
0
 static bool HasNativeThis()
 {
     if (hasTestResult == false)
     {
         Sandbox.hasNativeThis = false;
         var self        = new NativeThisPointer();
         var original    = AccessTools.DeclaredMethod(typeof(Sandbox), nameof(Sandbox.GetStruct));
         var replacement = AccessTools.DeclaredMethod(typeof(Sandbox), nameof(Sandbox.GetStructReplacement));
         _             = Memory.DetourMethod(original, replacement);
         _             = new Sandbox().GetStruct(Sandbox.magicValue, Sandbox.magicValue);
         hasTestResult = true;
     }
     return(Sandbox.hasNativeThis);
 }
Ejemplo n.º 6
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();
            firstArgIsReturnBuffer = NativeThisPointer.NeedsNativeThisPointerFix(original);
            if (debug && firstArgIsReturnBuffer)
            {
                FileLog.Log($"### Special case: extra argument after 'this' is pointer to valuetype (simulate return value)");
            }
            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);
        }
Ejemplo n.º 7
0
        public static DynamicMethod 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 (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();
                }

                DynamicTools.PrepareDynamicMethod(patch);
                return(patch);
            }
            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();
                }
            }
        }
Ejemplo n.º 8
0
        void EmitCallParameter(MethodInfo patch, Dictionary <string, LocalBuilder> variables, bool allowFirsParamPassthrough)
        {
            var isInstance             = original.IsStatic == false;
            var originalParameters     = original.GetParameters();
            var originalParameterNames = originalParameters.Select(p => p.Name).ToArray();
            var firstArgIsReturnBuffer = NativeThisPointer.NeedsNativeThisPointerFix(original);

            // check for passthrough using first parameter (which must have same type as return type)
            var parameters = patch.GetParameters().ToList();

            if (allowFirsParamPassthrough && patch.ReturnType != typeof(void) && parameters.Count > 0 && parameters[0].ParameterType == patch.ReturnType)
            {
                parameters.RemoveRange(0, 1);
            }

            foreach (var patchParam in parameters)
            {
                if (patchParam.Name == ORIGINAL_METHOD_PARAM)
                {
                    if (EmitOriginalBaseMethod())
                    {
                        continue;
                    }

                    emitter.Emit(OpCodes.Ldnull);
                    continue;
                }

                if (patchParam.Name == INSTANCE_PARAM)
                {
                    if (original.IsStatic)
                    {
                        emitter.Emit(OpCodes.Ldnull);
                    }
                    else
                    {
                        var instanceIsRef  = original.DeclaringType != null && AccessTools.IsStruct(original.DeclaringType);
                        var parameterIsRef = patchParam.ParameterType.IsByRef;
                        if (instanceIsRef == parameterIsRef)
                        {
                            emitter.Emit(OpCodes.Ldarg_0);
                        }
                        if (instanceIsRef && parameterIsRef == false)
                        {
                            emitter.Emit(OpCodes.Ldarg_0);
                            emitter.Emit(OpCodes.Ldobj, original.DeclaringType);
                        }
                        if (instanceIsRef == false && parameterIsRef)
                        {
                            emitter.Emit(OpCodes.Ldarga, 0);
                        }
                    }
                    continue;
                }

                if (patchParam.Name.StartsWith(INSTANCE_FIELD_PREFIX, StringComparison.Ordinal))
                {
                    var       fieldName = patchParam.Name.Substring(INSTANCE_FIELD_PREFIX.Length);
                    FieldInfo fieldInfo;
                    if (fieldName.All(char.IsDigit))
                    {
                        fieldInfo = AccessTools.DeclaredField(original.DeclaringType, int.Parse(fieldName));
                        if (fieldInfo == null)
                        {
                            throw new ArgumentException($"No field found at given index in class {original.DeclaringType.FullName}", fieldName);
                        }
                    }
                    else
                    {
                        fieldInfo = AccessTools.DeclaredField(original.DeclaringType, fieldName);
                        if (fieldInfo == null)
                        {
                            throw new ArgumentException($"No such field defined in class {original.DeclaringType.FullName}", fieldName);
                        }
                    }

                    if (fieldInfo.IsStatic)
                    {
                        emitter.Emit(patchParam.ParameterType.IsByRef ? OpCodes.Ldsflda : OpCodes.Ldsfld, fieldInfo);
                    }
                    else
                    {
                        emitter.Emit(OpCodes.Ldarg_0);
                        emitter.Emit(patchParam.ParameterType.IsByRef ? OpCodes.Ldflda : OpCodes.Ldfld, fieldInfo);
                    }
                    continue;
                }

                // state is special too since each patch has its own local var
                if (patchParam.Name == STATE_VAR)
                {
                    var ldlocCode = patchParam.ParameterType.IsByRef ? OpCodes.Ldloca : OpCodes.Ldloc;
                    if (variables.TryGetValue(patch.DeclaringType.FullName, out var stateVar))
                    {
                        emitter.Emit(ldlocCode, stateVar);
                    }
                    else
                    {
                        emitter.Emit(OpCodes.Ldnull);
                    }
                    continue;
                }

                // treat __result var special
                if (patchParam.Name == RESULT_VAR)
                {
                    var returnType = AccessTools.GetReturnedType(original);
                    if (returnType == typeof(void))
                    {
                        throw new Exception($"Cannot get result from void method {original.FullDescription()}");
                    }
                    var resultType = patchParam.ParameterType;
                    if (resultType.IsByRef)
                    {
                        resultType = resultType.GetElementType();
                    }
                    if (resultType.IsAssignableFrom(returnType) == false)
                    {
                        throw new Exception($"Cannot assign method return type {returnType.FullName} to {RESULT_VAR} type {resultType.FullName} for method {original.FullDescription()}");
                    }
                    var ldlocCode = patchParam.ParameterType.IsByRef ? OpCodes.Ldloca : OpCodes.Ldloc;
                    emitter.Emit(ldlocCode, variables[RESULT_VAR]);
                    continue;
                }

                // any other declared variables
                if (variables.TryGetValue(patchParam.Name, out var localBuilder))
                {
                    var ldlocCode = patchParam.ParameterType.IsByRef ? OpCodes.Ldloca : OpCodes.Ldloc;
                    emitter.Emit(ldlocCode, localBuilder);
                    continue;
                }

                int idx;
                if (patchParam.Name.StartsWith(PARAM_INDEX_PREFIX, StringComparison.Ordinal))
                {
                    var val = patchParam.Name.Substring(PARAM_INDEX_PREFIX.Length);
                    if (!int.TryParse(val, out idx))
                    {
                        throw new Exception($"Parameter {patchParam.Name} does not contain a valid index");
                    }
                    if (idx < 0 || idx >= originalParameters.Length)
                    {
                        throw new Exception($"No parameter found at index {idx}");
                    }
                }
                else
                {
                    idx = patch.GetArgumentIndex(originalParameterNames, patchParam);
                    if (idx == -1)
                    {
                        throw new Exception($"Parameter \"{patchParam.Name}\" not found in method {original.FullDescription()}");
                    }
                }

                //   original -> patch     opcode
                // --------------------------------------
                // 1 normal   -> normal  : LDARG
                // 2 normal   -> ref/out : LDARGA
                // 3 ref/out  -> normal  : LDARG, LDIND_x
                // 4 ref/out  -> ref/out : LDARG
                //
                var originalIsNormal = originalParameters[idx].IsOut == false && originalParameters[idx].ParameterType.IsByRef == false;
                var patchIsNormal    = patchParam.IsOut == false && patchParam.ParameterType.IsByRef == false;
                var patchArgIndex    = idx + (isInstance ? 1 : 0) + (firstArgIsReturnBuffer ? 1 : 0);

                // Case 1 + 4
                if (originalIsNormal == patchIsNormal)
                {
                    emitter.Emit(OpCodes.Ldarg, patchArgIndex);
                    continue;
                }

                // Case 2
                if (originalIsNormal && patchIsNormal == false)
                {
                    emitter.Emit(OpCodes.Ldarga, patchArgIndex);
                    continue;
                }

                // Case 3
                emitter.Emit(OpCodes.Ldarg, patchArgIndex);
                emitter.Emit(LoadIndOpCodeFor(originalParameters[idx].ParameterType));
            }
        }
Ejemplo n.º 9
0
        internal static DynamicMethod CreateDynamicMethod(MethodBase original, string suffix)
        {
            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();

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

            var firstArgIsReturnBuffer = NativeThisPointer.NeedsNativeThisPointerFix(original);

            if (firstArgIsReturnBuffer)
            {
                parameterTypes.Insert(0, typeof(IntPtr));
            }
            var returnType = firstArgIsReturnBuffer ? typeof(void) : AccessTools.GetReturnedType(original);

            // DynamicMethod does not support byref return types
            if (returnType == null || returnType.IsByRef)
            {
                return(null);
            }

            DynamicMethod method;

            try
            {
                method = new DynamicMethod(
                    patchName,
                    MethodAttributes.Public | MethodAttributes.Static,
                    CallingConventions.Standard,
                    returnType,
                    parameterTypes.ToArray(),
                    original.DeclaringType,
                    true
                    );
            }
            catch (Exception)
            {
                return(null);
            }

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

            for (var i = 0; i < parameters.Length; i++)
            {
                method.DefineParameter(i + offset, parameters[i].Attributes, parameters[i].Name);
            }

            return(method);
        }