Ejemplo n.º 1
0
        static unsafe void GetStructReplacement(NativeThisPointer self, IntPtr ptr, IntPtr a, IntPtr b)
        {
            // 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.º 2
0
        static unsafe void GetStructReplacement(NativeThisPointer self, IntPtr ptr, IntPtr a, IntPtr b)
        {
            // Normal argument order:
            // this, a, b

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

            hasNativeThis = (a == (IntPtr)0xdeadbeef) && (b == (IntPtr)0xdeadbeef);
        }
Ejemplo n.º 3
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);
         new NativeThisPointer().GetStruct(magicValue, magicValue);
         hasTestResult = true;
     }
     return(hasNativeThis);
 }
Ejemplo n.º 4
0
        static void EmitCallParameter(ILGenerator il, MethodBase original, 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)
                {
                    var constructorInfo = original as ConstructorInfo;
                    if (constructorInfo != null)
                    {
                        Emitter.Emit(il, OpCodes.Ldtoken, constructorInfo);
                        Emitter.Emit(il, OpCodes.Call, getMethodMethod);
                        continue;
                    }
                    var methodInfo = original as MethodInfo;
                    if (methodInfo != null)
                    {
                        Emitter.Emit(il, OpCodes.Ldtoken, methodInfo);
                        Emitter.Emit(il, OpCodes.Call, getMethodMethod);
                        continue;
                    }
                    Emitter.Emit(il, OpCodes.Ldnull);
                    continue;
                }

                if (patchParam.Name == INSTANCE_PARAM)
                {
                    if (original.IsStatic)
                    {
                        Emitter.Emit(il, OpCodes.Ldnull);
                    }
                    else
                    {
                        var instanceIsRef  = AccessTools.IsStruct(original.DeclaringType);
                        var parameterIsRef = patchParam.ParameterType.IsByRef;
                        if (instanceIsRef == parameterIsRef)
                        {
                            Emitter.Emit(il, firstArgIsReturnBuffer ? OpCodes.Ldarg_1 : OpCodes.Ldarg_0);
                        }
                        if (instanceIsRef && parameterIsRef == false)
                        {
                            Emitter.Emit(il, firstArgIsReturnBuffer ? OpCodes.Ldarg_1 : OpCodes.Ldarg_0);
                            Emitter.Emit(il, OpCodes.Ldobj, original.DeclaringType);
                        }
                        if (instanceIsRef == false && parameterIsRef)
                        {
                            Emitter.Emit(il, OpCodes.Ldarga, firstArgIsReturnBuffer ? 1 : 0);
                        }
                    }
                    continue;
                }

                if (patchParam.Name.StartsWith(INSTANCE_FIELD_PREFIX))
                {
                    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(il, patchParam.ParameterType.IsByRef ? OpCodes.Ldsflda : OpCodes.Ldsfld, fieldInfo);
                    }
                    else
                    {
                        Emitter.Emit(il, firstArgIsReturnBuffer ? OpCodes.Ldarg_1 : OpCodes.Ldarg_0);
                        Emitter.Emit(il, patchParam.ParameterType.IsByRef ? OpCodes.Ldflda : OpCodes.Ldfld, fieldInfo);
                    }
                    continue;
                }

                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(il, ldlocCode, stateVar);
                    }
                    else
                    {
                        Emitter.Emit(il, OpCodes.Ldnull);
                    }
                    continue;
                }

                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(il, ldlocCode, variables[RESULT_VAR]);
                    continue;
                }

                int idx;
                if (patchParam.Name.StartsWith(PARAM_INDEX_PREFIX))
                {
                    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 = GetArgumentIndex(patch, 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(il, OpCodes.Ldarg, patchArgIndex);
                    continue;
                }

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

                // Case 3
                Emitter.Emit(il, OpCodes.Ldarg, patchArgIndex);
                Emitter.Emit(il, LoadIndOpCodeFor(originalParameters[idx].ParameterType));
            }
        }
Ejemplo n.º 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.Union(postfixes).ToList().ForEach(fix =>
                {
                    if (privateVars.ContainsKey(fix.DeclaringType.FullName) == false)
                    {
                        fix.GetParameters()
                        .Where(patchParam => patchParam.Name == STATE_VAR)
                        .Do(patchParam =>
                        {
                            var privateStateVariable = DynamicTools.DeclareLocalVariable(il, patchParam.ParameterType);
                            privateVars[fix.DeclaringType.FullName] = privateStateVariable;
                        });
                    }
                });

                if (firstArgIsReturnBuffer)
                {
                    Emitter.Emit(il, original.IsStatic ? OpCodes.Ldarg_0 : OpCodes.Ldarg_1);
                }

                var skipOriginalLabel = il.DefineLabel();
                var canHaveJump       = AddPrefixes(il, original, prefixes, privateVars, skipOriginalLabel);

                var copier = new MethodCopier(original, il, originalVariables);
                foreach (var transpiler in transpilers)
                {
                    copier.AddTranspiler(transpiler);
                }

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

                foreach (var label in endLabels)
                {
                    Emitter.MarkLabel(il, label);
                }
                foreach (var block in endBlocks)
                {
                    Emitter.MarkBlockAfter(il, block);
                }
                if (resultVariable != null)
                {
                    Emitter.Emit(il, OpCodes.Stloc, resultVariable);
                }
                if (canHaveJump)
                {
                    Emitter.MarkLabel(il, skipOriginalLabel);
                }

                AddPostfixes(il, original, postfixes, privateVars, false);

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

                AddPostfixes(il, original, postfixes, privateVars, true);

                if (firstArgIsReturnBuffer)
                {
                    Emitter.Emit(il, OpCodes.Stobj, returnType);
                }

                Emitter.Emit(il, OpCodes.Ret);

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

                DynamicTools.PrepareDynamicMethod(patch);
                return(patch);
            }
            catch (Exception ex)
            {
                var exceptionString = "Exception from HarmonyInstance \"" + harmonyInstanceID + "\" patching " + original.FullDescription();
                if (HarmonyInstance.DEBUG)
                {
                    FileLog.Log("Exception: " + exceptionString);
                }
                throw new Exception(exceptionString, ex);
            }
            finally
            {
                if (HarmonyInstance.DEBUG)
                {
                    FileLog.FlushBuffer();
                }
            }
        }
Ejemplo n.º 6
0
        internal static DynamicMethod CreateDynamicMethod(MethodBase original, string suffix)
        {
            if (original == null)
            {
                throw new ArgumentNullException("original cannot be null");
            }
            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);
        }