예제 #1
0
        /// <summary>Gets the return type of a method or constructor</summary>
        /// <param name="methodOrConstructor">The method or constructor</param>
        /// <returns>The return type of the method</returns>
        ///
        public static Type GetReturnedType(MethodBase methodOrConstructor)
        {
            if (methodOrConstructor == null)
            {
                if (HarmonyInstance.DEBUG)
                {
                    FileLog.Log("AccessTools.GetReturnedType: methodOrConstructor is null");
                }
                return(null);
            }
            var constructor = methodOrConstructor as ConstructorInfo;

            if (constructor != null)
            {
                return(typeof(void));
            }
            return(((MethodInfo)methodOrConstructor).ReturnType);
        }
예제 #2
0
        /// <summary>Gets the reflection information for a field</summary>
        /// <param name="type">The class where the field is declared</param>
        /// <param name="idx">The zero-based index of the field inside the class definition</param>
        /// <returns>A FieldInfo or null when type is null or when the field cannot be found</returns>
        ///
        public static FieldInfo DeclaredField(Type type, int idx)
        {
            if (type == null)
            {
                if (HarmonyInstance.DEBUG)
                {
                    FileLog.Log("AccessTools.DeclaredField: type is null");
                }
                return(null);
            }
            var field = GetDeclaredFields(type).ElementAtOrDefault(idx);

            if (field == null && HarmonyInstance.DEBUG)
            {
                FileLog.Log("AccessTools.DeclaredField: Could not find field for type " + type + " and idx " + idx);
            }
            return(field);
        }
예제 #3
0
 /// <summary>Gets default value for a specific type</summary>
 /// <param name="type">The type</param>
 /// <returns>The default value</returns>
 ///
 public static object GetDefaultValue(Type type)
 {
     if (type == null)
     {
         if (HarmonyInstance.DEBUG)
         {
             FileLog.Log("AccessTools.GetDefaultValue: type is null");
         }
         return(null);
     }
     if (type == typeof(void))
     {
         return(null);
     }
     if (type.IsValueType)
     {
         return(Activator.CreateInstance(type));
     }
     return(null);
 }
예제 #4
0
 /// <summary>Given a type, returns the first property matching a predicate</summary>
 /// <param name="type">The type to start searching at</param>
 /// <param name="predicate">The predicate to search with</param>
 /// <returns>The PropertyInfo or null if type/predicate is null or if a type with that name cannot be found</returns>
 ///
 public static PropertyInfo FirstProperty(Type type, Func <PropertyInfo, bool> predicate)
 {
     if (type == null)
     {
         if (HarmonyInstance.DEBUG)
         {
             FileLog.Log("AccessTools.FirstProperty: type is null");
         }
         return(null);
     }
     if (predicate == null)
     {
         if (HarmonyInstance.DEBUG)
         {
             FileLog.Log("AccessTools.FirstProperty: predicate is null");
         }
         return(null);
     }
     return(type.GetProperties(allDeclared).FirstOrDefault(property => predicate(property)));
 }
예제 #5
0
 /// <summary>Given a type, returns the first constructor matching a predicate</summary>
 /// <param name="type">The type to start searching at</param>
 /// <param name="predicate">The predicate to search with</param>
 /// <returns>The ConstructorInfo or null if type/predicate is null or if a type with that name cannot be found</returns>
 ///
 public static ConstructorInfo FirstConstructor(Type type, Func <ConstructorInfo, bool> predicate)
 {
     if (type == null)
     {
         if (HarmonyInstance.DEBUG)
         {
             FileLog.Log("AccessTools.FirstConstructor: type is null");
         }
         return(null);
     }
     if (predicate == null)
     {
         if (HarmonyInstance.DEBUG)
         {
             FileLog.Log("AccessTools.FirstConstructor: predicate is null");
         }
         return(null);
     }
     return(type.GetConstructors(allDeclared).FirstOrDefault(constructor => predicate(constructor)));
 }
예제 #6
0
 /// <summary>Given a type, returns the first method matching a predicate</summary>
 /// <param name="type">The type to start searching at</param>
 /// <param name="predicate">The predicate to search with</param>
 /// <returns>The MethodInfo or null if type/predicate is null or if a type with that name cannot be found</returns>
 ///
 public static MethodInfo FirstMethod(Type type, Func <MethodInfo, bool> predicate)
 {
     if (type == null)
     {
         if (HarmonyInstance.DEBUG)
         {
             FileLog.Log("AccessTools.FirstMethod: type is null");
         }
         return(null);
     }
     if (predicate == null)
     {
         if (HarmonyInstance.DEBUG)
         {
             FileLog.Log("AccessTools.FirstMethod: predicate is null");
         }
         return(null);
     }
     return(type.GetMethods(allDeclared).FirstOrDefault(method => predicate(method)));
 }
예제 #7
0
 /// <summary>Given a type, returns the first inner type matching a recursive search with a predicate</summary>
 /// <param name="type">The type to start searching at</param>
 /// <param name="predicate">The predicate to search with</param>
 /// <returns>The inner type or null if type/predicate is null or if a type with that name cannot be found</returns>
 ///
 public static Type FirstInner(Type type, Func <Type, bool> predicate)
 {
     if (type == null)
     {
         if (HarmonyInstance.DEBUG)
         {
             FileLog.Log("AccessTools.FirstInner: type is null");
         }
         return(null);
     }
     if (predicate == null)
     {
         if (HarmonyInstance.DEBUG)
         {
             FileLog.Log("AccessTools.FirstInner: predicate is null");
         }
         return(null);
     }
     return(type.GetNestedTypes(all).FirstOrDefault(subType => predicate(subType)));
 }
예제 #8
0
 /// <summary>Given a type, returns the first inner type matching a recursive search by name</summary>
 /// <param name="type">The type to start searching at</param>
 /// <param name="name">The name of the inner type (case sensitive)</param>
 /// <returns>The inner type or null if type/name is null or if a type with that name cannot be found</returns>
 ///
 public static Type Inner(Type type, string name)
 {
     if (type == null)
     {
         if (HarmonyInstance.DEBUG)
         {
             FileLog.Log("AccessTools.Inner: type is null");
         }
         return(null);
     }
     if (name == null)
     {
         if (HarmonyInstance.DEBUG)
         {
             FileLog.Log("AccessTools.Inner: name is null");
         }
         return(null);
     }
     return(FindIncludingBaseTypes(type, t => t.GetNestedType(name, all)));
 }
예제 #9
0
        /// <summary>Gets the reflection information for a method by searching the type and all its super types</summary>
        /// <param name="typeColonMethodname">The full name (Namespace.Type1.Type2:MethodName) of the type where the method is declared</param>
        /// <param name="parameters">Optional parameters to target a specific overload of the method</param>
        /// <param name="generics">Optional list of types that define the generic version of the method</param>
        /// <returns>A MethodInfo or null when type/name is null or when the method cannot be found</returns>
        ///
        public static MethodInfo Method(string typeColonMethodname, Type[] parameters = null, Type[] generics = null)
        {
            if (typeColonMethodname == null)
            {
                if (HarmonyInstance.DEBUG)
                {
                    FileLog.Log("AccessTools.Method: typeColonMethodname is null");
                }
                return(null);
            }
            var parts = typeColonMethodname.Split(':');

            if (parts.Length != 2)
            {
                throw new ArgumentException("Method must be specified as 'Namespace.Type1.Type2:MethodName", nameof(typeColonMethodname));
            }

            var type = TypeByName(parts[0]);

            return(DeclaredMethod(type, parts[1], parameters, generics));
        }
예제 #10
0
        /// <summary>Gets a type by name. Prefers a full name with namespace but falls back to the first type matching the name otherwise</summary>
        /// <param name="name">The name</param>
        /// <returns>A Type</returns>
        ///
        public static Type TypeByName(string name)
        {
            var type = Type.GetType(name, false);

            if (type == null)
            {
                type = AppDomain.CurrentDomain.GetAssemblies()
                       .SelectMany(x => x.GetTypes())
                       .FirstOrDefault(x => x.FullName == name);
            }
            if (type == null)
            {
                type = AppDomain.CurrentDomain.GetAssemblies()
                       .SelectMany(x => x.GetTypes())
                       .FirstOrDefault(x => x.Name == name);
            }
            if (type == null && HarmonyInstance.DEBUG)
            {
                FileLog.Log("AccessTools.TypeByName: Could not find type named " + name);
            }
            return(type);
        }
예제 #11
0
        /// <summary>Creates patched method.</summary>
        /// <exception cref="ArgumentNullException">Thrown when one or more required arguments are null.</exception>
        /// <exception cref="Exception">				  Thrown when an exception error condition occurs.</exception>
        /// <param name="original">			The original method.</param>
        /// <param name="harmonyInstanceID">Identifier for the harmony instance.</param>
        /// <param name="prefixes">			The prefix methods.</param>
        /// <param name="postfixes">			The postfix methods.</param>
        /// <param name="transpilers">		The transpiler methods.</param>
        /// <returns>A new dynamic method.</returns>
        ///
        public static DynamicMethod CreatePatchedMethod(MethodBase original, string harmonyInstanceID, List <MethodInfo> prefixes, List <MethodInfo> postfixes, List <MethodInfo> transpilers)
        {
            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);
                }

                var idx   = prefixes.Count() + postfixes.Count();
                var patch = DynamicTools.CreateDynamicMethod(original, "_Patch" + idx);
                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);

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

                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)
            {
                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();
                }
            }
        }
예제 #12
0
        public static DynamicMethod CreatePatchedMethod(MethodBase original, List <MethodInfo> prefixes, List <MethodInfo> postfixes, List <TranspilerImpl> transpilers, PatchFlags flags)
        {
            if (HarmonyInstance.DEBUG)
            {
                FileLog.Log("PATCHING " + original.DeclaringType + " " + original);
            }

            var idx   = prefixes.Count() + postfixes.Count();
            var patch = DynamicTools.CreateDynamicMethod(original, "_Patch" + idx);
            var il    = patch.GetILGenerator();

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

            LocalBuilder resultVariable = null;

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

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

            var  afterOriginal1 = il.DefineLabel();
            var  afterOriginal2 = il.DefineLabel();
            bool canHaveJump    = false;

            if (flags.HasFlag(PatchFlags.PF_Detour) == false)
            {
                canHaveJump = AddPrefixes(il, original, prefixes, privateVars, afterOriginal2);

                if (flags.HasFlag(PatchFlags.PF_NoOrigin) == false)
                {
                    var copier = new MethodCopier(original, patch, originalVariables);
                    foreach (var transpiler in transpilers)
                    {
                        copier.AddTranspiler(transpiler);
                    }
                    copier.Emit(afterOriginal1);
                    Emitter.MarkLabel(il, afterOriginal1);
                    if (resultVariable != null)
                    {
                        Emitter.Emit(il, OpCodes.Stloc, resultVariable);
                    }
                }
            }
            if (canHaveJump)
            {
                Emitter.MarkLabel(il, afterOriginal2);
            }

            if (AddPostfixes(il, original, postfixes, privateVars))
            {
                if (resultVariable != null)
                {
                    Emitter.Emit(il, OpCodes.Stloc, resultVariable);
                }
            }
            if (resultVariable != null)
            {
                Emitter.Emit(il, OpCodes.Ldloc, resultVariable);
            }
            Emitter.Emit(il, OpCodes.Ret);

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

            DynamicTools.PrepareDynamicMethod(patch);
            return(patch);
        }
예제 #13
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();
                }
            }
        }
예제 #14
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);
        }