Esempio n. 1
0
        public static DynamicMethod CreatePatchedMethod(MethodBase original, List <MethodInfo> prefixes, List <MethodInfo> postfixes, List <ICodeProcessor> processors)
        {
            if (MethodCopier.DEBUG_OPCODES)
            {
                FileLog.Log("PATCHING " + original.DeclaringType + " " + original);
            }

            var idx               = prefixes.Count() + postfixes.Count();
            var patch             = DynamicTools.CreateDynamicMethod(original, "_Patch" + idx);
            var il                = patch.GetILGenerator();
            var originalVariables = DynamicTools.DeclareLocalVariables(original, il);
            var resultVariable    = DynamicTools.DeclareLocalVariable(il, AccessTools.GetReturnedType(original));

            var privateVars = new Dictionary <string, LocalBuilder>();

            privateVars[RESULT_VAR] = resultVariable;
            prefixes.ForEach(prefix =>
            {
                prefix.GetParameters()
                .Where(patchParam => patchParam.Name == STATE_VAR)
                .Do(patchParam =>
                {
                    var privateStateVariable = DynamicTools.DeclareLocalVariable(il, patchParam.ParameterType);
                    privateVars[prefix.DeclaringType.FullName] = privateStateVariable;
                });
            });

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

            var copier = new MethodCopier(original, patch, originalVariables);

            foreach (var processor in processors)
            {
                copier.AddReplacement(processor);
            }
            copier.AddReplacement(new RetToBrAfterProcessor(afterOriginal1));
            copier.Emit();
            Emitter.MarkLabel(il, afterOriginal1);
            if (resultVariable != null)
            {
                Emitter.Emit(il, OpCodes.Stloc, resultVariable);
            }
            if (canHaveJump)
            {
                Emitter.MarkLabel(il, afterOriginal2);
            }

            AddPostfixes(il, original, postfixes, privateVars);

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

            if (MethodCopier.DEBUG_OPCODES)
            {
                FileLog.Log("DONE");
                FileLog.Log("");
            }

            DynamicTools.PrepareDynamicMethod(patch);
            return(patch);
        }
Esempio n. 2
0
        public static DynamicMethod CreatePatchedMethod(MethodBase original, string harmonyInstanceID, List <MethodInfo> prefixes, List <MethodInfo> postfixes, List <MethodInfo> transpilers)
        {
            try
            {
                if ((original.DeclaringType.Assembly.GetCustomAttributes(typeof(HarmonyShield), false).Count() > 0) ||
                    (original.DeclaringType.GetCustomAttributes(typeof(HarmonyShield), false).Count() > 0) ||
                    (original.GetCustomAttributes(typeof(HarmonyShield), false).Count() > 0))
                {
                    return(null);
                }
                if (HarmonyInstance.DEBUG)
                {
                    FileLog.LogBuffered("### Patch " + original.DeclaringType + ", " + original);
                }

                bool isIl2Cpp = MelonLoader.UnhollowerSupport.IsGeneratedAssemblyType(original.DeclaringType);
                var  idx      = prefixes.Count() + postfixes.Count();
                var  patch    = DynamicTools.CreateDynamicMethod(original, "_Patch" + idx, isIl2Cpp);
                if (patch == null)
                {
                    return(null);
                }

                var il = patch.GetILGenerator();

                // for debugging
                AssemblyBuilder assemblyBuilder = null;
                TypeBuilder     typeBuilder     = null;
                if (DEBUG_METHOD_GENERATION_BY_DLL_CREATION)
                {
                    il = DynamicTools.CreateSaveableMethod(original, "_Patch" + idx, out assemblyBuilder, out typeBuilder);
                }

                var originalVariables = DynamicTools.DeclareLocalVariables(original, il);
                var privateVars       = new Dictionary <string, LocalBuilder>();

                LocalBuilder resultVariable = null;
                if (idx > 0)
                {
                    resultVariable          = DynamicTools.DeclareLocalVariable(il, AccessTools.GetReturnedType(original));
                    privateVars[RESULT_VAR] = resultVariable;
                }

                prefixes.ForEach(prefix =>
                {
                    prefix.GetParameters()
                    .Where(patchParam => patchParam.Name == STATE_VAR)
                    .Do(patchParam =>
                    {
                        var privateStateVariable = DynamicTools.DeclareLocalVariable(il, patchParam.ParameterType);
                        privateVars[prefix.DeclaringType.FullName] = privateStateVariable;
                    });
                });

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

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

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

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

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

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

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

                Emitter.Emit(il, OpCodes.Ret);

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

                // for debugging
                if (DEBUG_METHOD_GENERATION_BY_DLL_CREATION)
                {
                    DynamicTools.SaveMethod(assemblyBuilder, typeBuilder);
                    return(null);
                }

                DynamicTools.PrepareDynamicMethod(patch);
                return(patch);
            }
            catch (Exception ex)
            {
                throw new Exception("Exception from HarmonyInstance \"" + harmonyInstanceID + "\"", ex);
            }
            finally
            {
                if (HarmonyInstance.DEBUG)
                {
                    FileLog.FlushBuffer();
                }
            }
        }
Esempio n. 3
0
        static void EmitCallParameter(ILGenerator il, MethodBase original, MethodInfo patch, Dictionary <string, LocalBuilder> variables)
        {
            var isInstance             = original.IsStatic == false;
            var originalParameters     = original.GetParameters();
            var originalParameterNames = originalParameters.Select(p => p.Name).ToArray();

            foreach (var patchParam in patch.GetParameters())
            {
                if (patchParam.Name == INSTANCE_PARAM)
                {
                    if (!isInstance)
                    {
                        throw new Exception("Cannot get instance from static method " + original);
                    }
                    if (patchParam.ParameterType.IsByRef)
                    {
                        Emitter.Emit(il, OpCodes.Ldarga, 0);                         // probably won't work or will be useless
                    }
                    else
                    {
                        Emitter.Emit(il, OpCodes.Ldarg_0);
                    }
                    continue;
                }

                if (patchParam.Name == STATE_VAR)
                {
                    var ldlocCode = patchParam.ParameterType.IsByRef ? OpCodes.Ldloca : OpCodes.Ldloc;
                    Emitter.Emit(il, ldlocCode, variables[patch.DeclaringType.FullName]);
                    continue;
                }

                if (patchParam.Name == RESULT_VAR)
                {
                    if (AccessTools.GetReturnedType(original) == typeof(void))
                    {
                        throw new Exception("Cannot get result from void method " + original);
                    }
                    var ldlocCode = patchParam.ParameterType.IsByRef ? OpCodes.Ldloca : OpCodes.Ldloc;
                    Emitter.Emit(il, ldlocCode, variables[RESULT_VAR]);
                    continue;
                }

                var idx = Array.IndexOf(originalParameterNames, patchParam.Name);
                if (idx == -1)
                {
                    throw new Exception("Parameter \"" + patchParam.Name + "\" not found in method " + original);
                }

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

                // 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));
            }
        }
Esempio n. 4
0
        static void EmitCallParameter(ILGenerator il, MethodBase original, MethodInfo patch, Dictionary <string, LocalBuilder> variables, bool allowFirsParamPassthrough, bool isIl2Cpp)
        {
            var isInstance             = original.IsStatic == false;
            var originalParameters     = original.GetParameters();
            var originalParameterNames = originalParameters.Select(p => p.Name).ToArray();

            // 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 if (patchParam.ParameterType.IsByRef)
                    {
                        Emitter.Emit(il, OpCodes.Ldarga, 0);                         // probably won't work or will be useless
                    }
                    else
                    {
                        Emitter.Emit(il, OpCodes.Ldarg_0);
                    }
                    continue;
                }

                if (patchParam.Name.StartsWith(INSTANCE_FIELD_PREFIX))
                {
                    var fieldName = patchParam.Name.Substring(INSTANCE_FIELD_PREFIX.Length);
                    if (isIl2Cpp)
                    {
                        if (patchParam.ParameterType.IsByRef)
                        {
                            throw new NotSupportedException("Ref parameters to fields are not supported in IL2CPP patches");
                        }

                        var getterMethod = AccessTools.Property(original.DeclaringType, fieldName)?.GetGetMethod();
                        if (getterMethod == null)
                        {
                            throw new ArgumentException("No such field defined in class " + original.DeclaringType.FullName, fieldName);
                        }

                        if (!getterMethod.IsStatic)
                        {
                            Emitter.Emit(il, OpCodes.Ldarg_0);
                        }
                        var opcode = getterMethod.IsVirtual ? OpCodes.Callvirt : OpCodes.Call;
                        Emitter.Emit(il, opcode, getterMethod);
                    }
                    else
                    {
                        FieldInfo fieldInfo;
                        if (fieldName.All(char.IsDigit))
                        {
                            fieldInfo = AccessTools.Field(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.Field(original.DeclaringType, fieldName);
                            if (fieldInfo == null)
                            {
                                throw new ArgumentException("No such field defined in class " + original.DeclaringType.FullName, fieldName);
                            }
                        }

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

                if (patchParam.Name == STATE_VAR)
                {
                    var ldlocCode = patchParam.ParameterType.IsByRef ? OpCodes.Ldloca : OpCodes.Ldloc;
                    Emitter.Emit(il, ldlocCode, variables[patch.DeclaringType.FullName]);
                    continue;
                }

                if (patchParam.Name == RESULT_VAR)
                {
                    if (AccessTools.GetReturnedType(original) == typeof(void))
                    {
                        throw new Exception("Cannot get result from void 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);

                // 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));
            }
        }
Esempio n. 5
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.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));
            }
        }
Esempio n. 6
0
        public static DynamicMethod CreatePatchedMethod(MethodBase original, string harmonyInstanceID, List <MethodInfo> prefixes, List <MethodInfo> postfixes, List <MethodInfo> transpilers)
        {
            Memory.MarkForNoInlining(original);

            if (original == null)
            {
                throw new ArgumentNullException(nameof(original), "Original method is null. Did you specify it correctly?");
            }

            try
            {
                if (HarmonyInstance.DEBUG)
                {
                    FileLog.LogBuffered("### Patch " + original.DeclaringType + ", " + original);
                    FileLog.FlushBuffer();
                }

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

                var il = patch.GetILGenerator();

                var originalVariables = DynamicTools.DeclareLocalVariables(original, il);
                var privateVars       = new Dictionary <string, LocalBuilder>();

                LocalBuilder resultVariable = null;
                if (idx > 0)
                {
                    resultVariable          = DynamicTools.DeclareLocalVariable(il, returnType);
                    privateVars[RESULT_VAR] = resultVariable;
                }

                prefixes.ForEach(prefix =>
                {
                    prefix.GetParameters()
                    .Where(patchParam => patchParam.Name == STATE_VAR)
                    .Do(patchParam =>
                    {
                        var privateStateVariable = DynamicTools.DeclareLocalVariable(il, patchParam.ParameterType);
                        privateVars[prefix.DeclaringType.FullName] = privateStateVariable;
                    });
                });

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

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

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

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

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

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

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

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

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

                Emitter.Emit(il, OpCodes.Ret);

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

                DynamicTools.PrepareDynamicMethod(patch);
                return(patch);
            }
            catch (Exception ex)
            {
                var exceptionString = "Exception from HarmonyInstance \"" + harmonyInstanceID + "\" patching " + original.FullDescription();
                if (HarmonyInstance.DEBUG)
                {
                    FileLog.Log("Exception: " + exceptionString);
                }
                throw new Exception(exceptionString, ex);
            }
            finally
            {
                if (HarmonyInstance.DEBUG)
                {
                    FileLog.FlushBuffer();
                }
            }
        }
Esempio n. 7
0
        private static DynamicMethod CreateIl2CppShim(DynamicMethod original, Type owner)
        {
            var patchName = original.Name + "_il2cpp";

            var parameters     = original.GetParameters();
            var result         = parameters.Types().ToList();
            var origParamTypes = result.ToArray();
            var paramTypes     = new Type[origParamTypes.Length];

            for (int i = 0; i < paramTypes.Length; ++i)
            {
                paramTypes[i] = IsIl2CppType(origParamTypes[i]) ? typeof(IntPtr) : origParamTypes[i];
            }

            var origReturnType = AccessTools.GetReturnedType(original);
            var returnType     = IsIl2CppType(origReturnType) ? typeof(IntPtr) : origReturnType;

            DynamicMethod method;

            method = new DynamicMethod(
                patchName,
                MethodAttributes.Public | MethodAttributes.Static,
                CallingConventions.Standard,
                returnType,
                paramTypes,
                owner,
                true
                );

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

            var il = method.GetILGenerator();

            // Load arguments, invoking the IntPrt -> Il2CppObject constructor for IL2CPP types
            for (int i = 0; i < origParamTypes.Length; ++i)
            {
                Emitter.Emit(il, OpCodes.Ldarg, i);
                if (IsIl2CppType(origParamTypes[i]))
                {
                    Emitter.Emit(il, OpCodes.Newobj, Il2CppConstuctor(origParamTypes[i]));
                }
            }

            // Call the original patch with the now-correct types
            Emitter.Emit(il, OpCodes.Call, original);

            // If needed, unwrap the return value; then return
            if (IsIl2CppType(origReturnType))
            {
                var pointerGetter = AccessTools.DeclaredProperty(typeof(Il2CppObjectBase), "Pointer").GetMethod;
                Emitter.Emit(il, OpCodes.Call, pointerGetter);
            }

            Emitter.Emit(il, OpCodes.Ret);

            DynamicTools.PrepareDynamicMethod(method);
            return(method);
        }
Esempio n. 8
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();

            // 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 if (patchParam.ParameterType.IsByRef)
                    {
                        Emitter.Emit(il, OpCodes.Ldarga, 0);                         // probably won't work or will be useless
                    }
                    else
                    {
                        Emitter.Emit(il, OpCodes.Ldarg_0);
                    }
                    continue;
                }

                if (patchParam.Name.StartsWith(INSTANCE_FIELD_PREFIX))
                {
                    var fieldInfo = AccessTools.Field(original.DeclaringType, patchParam.Name.Substring(INSTANCE_FIELD_PREFIX.Length));
                    if (fieldInfo.IsStatic)
                    {
                        if (patchParam.ParameterType.IsByRef)
                        {
                            Emitter.Emit(il, OpCodes.Ldsflda, fieldInfo);
                        }
                        else
                        {
                            Emitter.Emit(il, OpCodes.Ldsfld, fieldInfo);
                        }
                    }
                    else
                    {
                        if (patchParam.ParameterType.IsByRef)
                        {
                            Emitter.Emit(il, OpCodes.Ldarg_0);
                            Emitter.Emit(il, OpCodes.Ldflda, fieldInfo);
                        }
                        else
                        {
                            Emitter.Emit(il, OpCodes.Ldarg_0);
                            Emitter.Emit(il, OpCodes.Ldfld, fieldInfo);
                        }
                    }
                    continue;
                }

                if (patchParam.Name == STATE_VAR)
                {
                    var ldlocCode = patchParam.ParameterType.IsByRef ? OpCodes.Ldloca : OpCodes.Ldloc;
                    Emitter.Emit(il, ldlocCode, variables[patch.DeclaringType.FullName]);
                    continue;
                }

                if (patchParam.Name == RESULT_VAR)
                {
                    if (AccessTools.GetReturnedType(original) == typeof(void))
                    {
                        throw new Exception("Cannot get result from void method " + original.FullDescription());
                    }
                    var ldlocCode = patchParam.ParameterType.IsByRef ? OpCodes.Ldloca : OpCodes.Ldloc;
                    Emitter.Emit(il, ldlocCode, variables[RESULT_VAR]);
                    continue;
                }

                var patchParamName = patchParam.Name;

                var originalName = patchParam.GetParameterOverride();
                if (originalName != null)
                {
                    patchParamName = originalName;
                }
                else
                {
                    originalName = patch.GetParameterOverride(patchParamName, true);
                    if (originalName != null)
                    {
                        patchParamName = originalName;
                    }
                }

                var idx = Array.IndexOf(originalParameterNames, patchParamName);
                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);

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