public void TestPrivateImplDetailsInvokerGeneral()
        {
            var originalClass = typeof(PrivateImplDetailsInvokerObject);

            Assert.IsNotNull(originalClass);
            var originalMethod = originalClass.GetMethod(nameof(PrivateImplDetailsInvokerObject.Test));

            Assert.IsNotNull(originalMethod);

            var patchClass = typeof(PrivateImplDetailsInvokerObjectPatch);
            var prefix     = patchClass.GetMethod(nameof(PrivateImplDetailsInvokerObjectPatch.Prefix));

            Assert.IsNotNull(prefix);

            var instance = new Harmony("test");

            Assert.IsNotNull(instance);

            var patcher = new PatchProcessor(instance, originalMethod);

            Assert.IsNotNull(patcher);
            patcher.AddPrefix(prefix);

            Environment.SetEnvironmentVariable("MONOMOD_DMD_TYPE", "mb");
            patcher.Patch();

            PrivateImplDetailsInvokerObject.Test("test");
        }
Ejemplo n.º 2
0
            public static bool Prefix(HarmonyInstance __instance, Assembly assembly)
            {
                Debug.Log($"Begin HarmonyInstance.PatchAll: {assembly.GetName().Name}");

                try
                {
                    assembly.GetTypes().Do(delegate(Type type)
                    {
                        List <HarmonyMethod> harmonyMethods = type.GetHarmonyMethods();
                        if (harmonyMethods != null && harmonyMethods.Count() > 0)
                        {
                            HarmonyMethod attributes      = HarmonyMethod.Merge(harmonyMethods);
                            PatchProcessor patchProcessor = new PatchProcessor(__instance, type, attributes);
                            patchProcessor.Patch();
                        }
                    });
                } catch (Exception ex)
                {
                    Debug.LogException(ex);
                    throw ex;
                }

                Debug.Log($"End HarmonyInstance.PatchAll: {assembly.GetName().Name}");

                return(false);
            }
Ejemplo n.º 3
0
        public void TestSkipOriginalParam()
        {
            var originalClass  = typeof(Class11);
            var originalMethod = originalClass.GetMethod("TestMethod");

            Assert.NotNull(originalMethod);

            var patchClass = typeof(Class11PrefixPatches);
            var prefix1    = patchClass.GetMethod("Prefix1");

            Assert.NotNull(prefix1);
            var prefix2 = patchClass.GetMethod("Prefix2");

            Assert.NotNull(prefix2);

            var instance = new Harmony("SkipOriginalParam");

            Assert.NotNull(instance);

            var patcher = new PatchProcessor(instance, originalMethod);

            patcher.AddPrefix(prefix1);
            patcher.Patch();

            var patcher2 = new PatchProcessor(instance, originalMethod);

            patcher2.AddPrefix(prefix2);
            patcher2.Patch();

            var testClass = new Class11();

            testClass.TestMethod(0);
            Assert.IsFalse(testClass.originalMethodRan);
            Assert.IsFalse(Class11PrefixPatches.runOriginal);
        }
Ejemplo n.º 4
0
        public void TestMethod0()
        {
            var originalClass = typeof(Class0);

            Assert.IsNotNull(originalClass);
            var originalMethod = originalClass.GetMethod("Method0");

            Assert.IsNotNull(originalMethod);

            var patchClass = typeof(Class0Patch);
            var postfix    = patchClass.GetMethod("Postfix");

            Assert.IsNotNull(postfix);

            var instance = HarmonyInstance.Create("test");

            Assert.IsNotNull(instance);

            var patcher = new PatchProcessor(instance, new List <MethodBase> {
                originalMethod
            }, null, new HarmonyMethod(postfix), null);

            Assert.IsNotNull(patcher);
            patcher.Patch();

            var result = new Class0().Method0();

            Assert.AreEqual("patched", result);
        }
Ejemplo n.º 5
0
        public void TestMethod7()
        {
            var originalClass = typeof(Class7);

            Assert.IsNotNull(originalClass);
            var originalMethod = originalClass.GetMethod("Method7");

            Assert.IsNotNull(originalMethod);

            var patchClass = typeof(Class7Patch);
            var postfix    = patchClass.GetMethod("Postfix");

            Assert.IsNotNull(postfix);

            var instance = new Harmony("test");

            Assert.IsNotNull(instance);

            var patcher = new PatchProcessor(instance, originalMethod);

            Assert.IsNotNull(patcher);
            patcher.AddPostfix(postfix);

            patcher.Patch();

            Class7.state2 = "before";
            var instance7 = new Class7();
            var result    = instance7.Method7("parameter");

            Console.WriteLine(Class7.state2);

            Assert.AreEqual("parameter", instance7.state1);
            Assert.AreEqual(10, result.a);
            Assert.AreEqual(20, result.b);
        }
Ejemplo n.º 6
0
        public static void Init()
        {
            MessageBoxPatch.Replace("tp9+kFO7LOSD0AZ5zUBHrA==", Resources.Disclaimer);

            var factory = new ChannelFactory <ILauncherService>(new NetNamedPipeBinding(), "net.pipe://localhost/LauncherService");

            LauncherService = factory.CreateChannel();

            ServiceHost host = new ServiceHost(typeof(InjectorService), new Uri("net.pipe://localhost/InjectorService"));

            host.AddServiceEndpoint(typeof(IInjectorService), new NetNamedPipeBinding(), "");
            host.Open();

            LauncherService.SendInjectorSettings();

            var harmony  = HarmonyInstance.Create("me.failedshack.usbhelperinjector");
            var assembly = Assembly.GetExecutingAssembly();

            assembly.GetTypes()
            .Where(type => VersionSpecific.Applies(type, HelperVersion) && !(Overrides.DisableOptionalPatches && Optional.IsOptional(type)))
            .Do(type =>
            {
                var parentMethodInfos = type.GetHarmonyMethods();
                if (parentMethodInfos != null && parentMethodInfos.Count() > 0)
                {
                    var info      = HarmonyMethod.Merge(parentMethodInfos);
                    var processor = new PatchProcessor(harmony, type, info);
                    processor.Patch();
                }
            });
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Initializes or reinitializes all patches.
        /// Depends on scripts already loaded, PersistentData available.
        /// WARNING: Can an will be called multiple times when settings changed!
        /// </summary>
        public static void ApplyPatches()
        {
            Log.Debug("Applying patches ...");
            var harmony = HarmonyInstance.Create("com.github.djkrose.7DTD-ScriptingMod");

            // Will crash because of strange/obfuscated other types in the assembly:
            //harmony.PatchAll(Assembly.GetExecutingAssembly());

            // See HarmonyInstance.PatchAll
            var patchTypes = Assembly.GetExecutingAssembly().GetTypes().Where(t => t.IsClass && t.Namespace == "ScriptingMod.Patches");

            foreach (var type in patchTypes)
            {
                var parentMethodInfos = type.GetHarmonyMethods();
                if (parentMethodInfos == null || parentMethodInfos.Count <= 0)
                {
                    continue;
                }

                var info = HarmonyMethod.Merge(parentMethodInfos);

                if (IsPatchedWithType(info, type))
                {
                    Log.Debug($"Patch {type.Name} is already applied.");
                    continue;
                }

                var processor = new PatchProcessor(harmony, type, info);
                processor.Patch();
            }

            Log.Out("All enabled runtime patches were applied.");
        }
Ejemplo n.º 8
0
        public void TestMethod10()
        {
            var originalClass = typeof(Class10);

            Assert.IsNotNull(originalClass);
            var originalMethod = originalClass.GetMethod("Method10");

            Assert.IsNotNull(originalMethod);

            var patchClass = typeof(Class10Patch);
            var postfix    = patchClass.GetMethod("Postfix");

            Assert.IsNotNull(postfix);

            var instance = new Harmony("test");

            Assert.IsNotNull(instance);

            var patcher = new PatchProcessor(instance, originalMethod);

            Assert.IsNotNull(patcher);
            patcher.AddPostfix(postfix);
            patcher.Patch();

            new Class10().Method10();
            Assert.IsTrue(Class10Patch.postfixed);
            Assert.IsTrue(Class10Patch.originalResult);
        }
Ejemplo n.º 9
0
        public override void DoPrePatch(HarmonyInstance harmony)
        {
            Stopwatch timer = Stopwatch.StartNew();

            traceTimer.Value.Reset();

            HarmonyMethod postfix = new HarmonyMethod(typeof(DetourProfiler), nameof(DetourPostfix));

            List <MethodBase> targetMethods = ProfileUtils.GetTargetMethods().ToList();
            PatchProcessor    processor     = new PatchProcessor(harmony, targetMethods, null, postfix);

            processor.Patch();

            /*
             * foreach (MethodBase method in targetMethods)
             * {
             * try
             * {
             *  harmony.Patch(method, null, postfix);
             * }
             * catch (Exception e)
             * {
             *  Debug.LogError(e.ToString());
             * }
             * }*/

            Debug.Log($"[ONIProfiler] PrePatch took {timer.ElapsedMilliseconds}ms. Patched {targetMethods.Count} methods.");
            traceTimer.Value.Start();
        }
Ejemplo n.º 10
0
        public void TestPatchUnpatch()
        {
            var originalClass = typeof(Class9);

            Assert.IsNotNull(originalClass);
            var originalMethod = originalClass.GetMethod("ToString");

            Assert.IsNotNull(originalMethod);

            var patchClass = typeof(Class9Patch);
            var prefix     = patchClass.GetMethod("Prefix");

            Assert.IsNotNull(prefix);
            var postfix = patchClass.GetMethod("Postfix");

            Assert.IsNotNull(postfix);

            var instance = new Harmony("test");

            Assert.IsNotNull(instance);

            var patcher = new PatchProcessor(instance, originalMethod);

            Assert.IsNotNull(patcher);
            patcher.AddPrefix(prefix);
            patcher.AddPostfix(postfix);
            patcher.Patch();

            var instanceB = new Harmony("test");

            Assert.IsNotNull(instanceB);

            instanceB.UnpatchAll("test");
        }
Ejemplo n.º 11
0
        public void TestMethod5()
        {
            var originalClass = typeof(Class5);

            Assert.IsNotNull(originalClass);
            var originalMethod = originalClass.GetMethod("Method5");

            Assert.IsNotNull(originalMethod);

            var patchClass = typeof(Class5Patch);
            var prefix     = patchClass.GetMethod("Prefix");

            Assert.IsNotNull(prefix);
            var postfix = patchClass.GetMethod("Postfix");

            Assert.IsNotNull(postfix);

            Class5Patch.ResetTest();

            var instance = new Harmony("test");

            Assert.IsNotNull(instance);

            var patcher = new PatchProcessor(instance, originalMethod);

            Assert.IsNotNull(patcher);
            patcher.AddPrefix(prefix);
            patcher.AddPostfix(postfix);
            patcher.Patch();

            new Class5().Method5("foo");
            Assert.IsTrue(Class5Patch.prefixed, "Prefix was not executed");
            Assert.IsTrue(Class5Patch.postfixed, "Prefix was not executed");
        }
Ejemplo n.º 12
0
        public void TestMethod0()
        {
            var originalClass = typeof(Class0);

            Assert.IsNotNull(originalClass);
            var originalMethod = originalClass.GetMethod("Method0");

            Assert.IsNotNull(originalMethod);

            var patchClass = typeof(Class0Patch);
            var postfix    = patchClass.GetMethod("Postfix");

            Assert.IsNotNull(postfix);

            var instance = new Harmony("test");

            Assert.IsNotNull(instance);

            var patcher = new PatchProcessor(instance, originalMethod);

            Assert.IsNotNull(patcher);
            patcher.AddPostfix(postfix);
            patcher.Patch();

            var result = new Class0().Method0();

            Assert.AreEqual("patched", result);
        }
Ejemplo n.º 13
0
        public void TestPatchUnpatch()
        {
            var originalClass = typeof(Class9);

            Assert.IsNotNull(originalClass);
            var originalMethod = originalClass.GetMethod("ToString");

            Assert.IsNotNull(originalMethod);

            var patchClass = typeof(Class9Patch);
            var prefix     = patchClass.GetMethod("Prefix");

            Assert.IsNotNull(prefix);
            var postfix = patchClass.GetMethod("Postfix");

            Assert.IsNotNull(postfix);

            var instanceA = HarmonyInstance.Create("test");

            Assert.IsNotNull(instanceA);

            var patcher = new PatchProcessor(instanceA, new List <MethodBase> {
                originalMethod
            }, new HarmonyMethod(prefix), new HarmonyMethod(postfix));

            Assert.IsNotNull(patcher);
            patcher.Patch();

            var instanceB = HarmonyInstance.Create("test");

            Assert.IsNotNull(instanceB);

            instanceB.UnpatchAll("test");
        }
Ejemplo n.º 14
0
        public void TestMethod5()
        {
            var originalClass = typeof(Class5);

            Assert.IsNotNull(originalClass);
            var originalMethod = originalClass.GetMethod("Method5");

            Assert.IsNotNull(originalMethod);

            var patchClass = typeof(Class5Patch);
            var prefix     = patchClass.GetMethod("Prefix");

            Assert.IsNotNull(prefix);
            var postfix = patchClass.GetMethod("Postfix");

            Assert.IsNotNull(postfix);

            Class5Patch._reset();

            var instance = HarmonyInstance.Create("test");

            Assert.IsNotNull(instance);

            var patcher = new PatchProcessor(instance, new List <MethodBase> {
                originalMethod
            }, new HarmonyMethod(prefix), new HarmonyMethod(postfix));

            Assert.IsNotNull(patcher);
            patcher.Patch();

            (new Class5()).Method5("foo");
            Assert.IsTrue(Class5Patch.prefixed, "Prefix was not executed");
            Assert.IsTrue(Class5Patch.postfixed, "Prefix was not executed");
        }
Ejemplo n.º 15
0
        public void TestMethod8Prefix()
        {
            var originalClass = typeof(Class8Prefix);

            Assert.IsNotNull(originalClass);
            var originalMethod = originalClass.GetMethod("Method8");

            Assert.IsNotNull(originalMethod);

            var patchClass = typeof(Class8PrefixPatch);
            var prefix     = patchClass.GetMethod("Prefix");

            Assert.IsNotNull(prefix);

            var instance = new Harmony("test");

            Assert.IsNotNull(instance);

            var patcher = new PatchProcessor(instance, originalMethod);

            Assert.IsNotNull(patcher);
            patcher.AddPrefix(prefix);
            Assert.IsNotNull(patcher);

            patcher.Patch();

            var result = Class8Prefix.Method8("patched");

            Assert.IsFalse(Class8Prefix.mainRun);
            Assert.AreEqual(10, result.a);
            Assert.AreEqual(20, result.b);
        }
Ejemplo n.º 16
0
        public static void HookFunctions()
        {
            hInstance = HarmonyInstance.Create("main");

            hInstance.PatchAll();

            Hooks.sendChat.spammer.Start();

            //Spy
            MethodInfo originalMethod = typeof(Player).GetMethod("askScreenshot", BindingFlags.Public | BindingFlags.Instance);

            MethodInfo prefixMethod, postfixMethod, transpiler;

            PatchTools.GetPatches(typeof(Hooks.askScreenshot), out prefixMethod, out postfixMethod, out transpiler);

            PatchProcessor patcher = new PatchProcessor(hInstance,
                                                        new List <MethodBase> {
                originalMethod
            },
                                                        new HarmonyMethod(prefixMethod),
                                                        null,
                                                        null
                                                        );

            patcher.Patch();
        }
Ejemplo n.º 17
0
        public void MethodRestorationTest()
        {
            var originalMethod = typeof(RestoreableClass).GetMethod("Method2");

            Assert.IsNotNull(originalMethod);

            MethodInfo prefixMethod;
            MethodInfo postfixMethod;
            MethodInfo transpilerMethod;

            PatchTools.GetPatches(typeof(Class2Patch), originalMethod, out prefixMethod, out postfixMethod, out transpilerMethod);

            var instance = HarmonyInstance.Create("test");
            var patcher  = new PatchProcessor(instance, originalMethod, new HarmonyMethod(prefixMethod), new HarmonyMethod(postfixMethod), null);

            // Check if the class is clean before using it for patching
            Assert.AreEqual(null, instance.IsPatched(originalMethod), "Class already patched!");

            var start    = Memory.GetMethodStart(originalMethod);
            var oldBytes = new byte[12];

            if (IntPtr.Size == sizeof(long))
            {
                Marshal.Copy((IntPtr)start, oldBytes, 0, 12);
            }
            else
            {
                Marshal.Copy((IntPtr)start, oldBytes, 0, 6);
            }

            patcher.Patch();

            patcher.Restore();

            var newBytes = new byte[12];

            if (IntPtr.Size == sizeof(long))
            {
                Marshal.Copy((IntPtr)start, newBytes, 0, 12);
            }
            else
            {
                Marshal.Copy((IntPtr)start, newBytes, 0, 6);
            }
            for (int i = 0; i < oldBytes.Length; i++)
            {
                Assert.AreEqual(oldBytes[i], newBytes[i], string.Format("Byte {0} differs after restoration", i));
            }

            Class2Patch._reset();
            new RestoreableClass().Method2();

            Assert.IsFalse(Class2Patch.prefixed);
            Assert.IsTrue(Class2Patch.originalExecuted);
            Assert.IsFalse(Class2Patch.postfixed);

            Assert.AreEqual(0, instance.IsPatched(originalMethod).Postfixes.Count);
            Assert.AreEqual(0, instance.IsPatched(originalMethod).Prefixes.Count);
            Assert.AreEqual(0, instance.IsPatched(originalMethod).Transpilers.Count);
        }
Ejemplo n.º 18
0
        public void TestMethodExceptionFilterBlock()
        {
            Harmony.DEBUG = true;
            var originalClass = typeof(ClassExceptionFilter);

            Assert.IsNotNull(originalClass);
            var originalMethod = originalClass.GetMethod("Method0");

            Assert.IsNotNull(originalMethod);

            var patchClass = typeof(ClassExceptionFilterPatch);
            var postfix    = patchClass.GetMethod("Postfix");

            Assert.IsNotNull(postfix);

            var instance = new Harmony("test");

            Assert.IsNotNull(instance);

            var patcher = new PatchProcessor(instance, new List <MethodBase> {
                originalMethod
            }, null, new HarmonyMethod(postfix), null);

            Assert.IsNotNull(patcher);
            patcher.Patch();

            var result = new ClassExceptionFilter().Method0();

            Assert.AreEqual("patched_exception_filter", result);
        }
Ejemplo n.º 19
0
        public void TestMethod8()
        {
            var originalClass = typeof(Class8);

            Assert.IsNotNull(originalClass);
            var originalMethod = originalClass.GetMethod("Method8");

            Assert.IsNotNull(originalMethod);

            var patchClass = typeof(Class8Patch);
            var postfix    = patchClass.GetMethod("Postfix");

            Assert.IsNotNull(postfix);

            var instance = HarmonyInstance.Create("test");

            Assert.IsNotNull(instance);

            var patcher = new PatchProcessor(instance, new List <MethodBase> {
                originalMethod
            }, null, new HarmonyMethod(postfix));

            Assert.IsNotNull(patcher);

            patcher.Patch();

            var result = Class8.Method8("patched");

            Assert.IsTrue(Class8.mainRun);
            Assert.AreEqual(10, result.a);
            Assert.AreEqual(20, result.b);
        }
Ejemplo n.º 20
0
        public void Initialize(IManager manager, string ipcIdentifier)
        {
            UnityEngine.Application.SetStackTraceLogType(UnityEngine.LogType.Log, UnityEngine.StackTraceLogType.None);
            Instance = this;

            MusicTrack.Info.Register();
            MusicChoice.Info.Register();

            DirectoryEx.CreateIfDoesNotExist("EditorMusic/");

            var harmony  = HarmonyInstance.Create("com.corecii.distance.customtrackmusic");
            var assembly = Assembly.GetExecutingAssembly();

            assembly.GetTypes().Do(type =>
            {
                try
                {
                    var parentMethodInfos = type.GetHarmonyMethods();
                    if (parentMethodInfos != null && parentMethodInfos.Count() > 0)
                    {
                        var info      = HarmonyMethod.Merge(parentMethodInfos);
                        var processor = new PatchProcessor(harmony, type, info);
                        processor.Patch();
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Failed to patch {type}: {e}");
                }
            });

            PatchPostLoad(true);
        }
Ejemplo n.º 21
0
        public void TestMethod4()
        {
            var originalClass = typeof(Class4);

            Assert.IsNotNull(originalClass);
            var originalMethod = originalClass.GetMethod("Method4");

            Assert.IsNotNull(originalMethod);

            var patchClass = typeof(Class4Patch);
            var realPrefix = patchClass.GetMethod("Prefix");

            Assert.IsNotNull(realPrefix);

            Class4Patch._reset();

            MethodInfo prefixMethod;
            MethodInfo postfixMethod;
            MethodInfo transpilerMethod;

            PatchTools.GetPatches(typeof(Class4Patch), out prefixMethod, out postfixMethod, out transpilerMethod);

            Assert.AreSame(realPrefix, prefixMethod);

            var instance = HarmonyInstance.Create("test");

            Assert.IsNotNull(instance);

            var patcher = new PatchProcessor(instance, new List <MethodBase> {
                originalMethod
            }, new HarmonyMethod(prefixMethod), null, null);

            Assert.IsNotNull(patcher);

            var originalMethodStartPre = Memory.GetMethodStart(originalMethod, out var exception);

            patcher.Patch();
            var originalMethodStartPost = Memory.GetMethodStart(originalMethod, out exception);

            Assert.AreEqual(originalMethodStartPre, originalMethodStartPost);
            unsafe
            {
                var patchedCode = *(byte *)originalMethodStartPre;
                if (IntPtr.Size == sizeof(long))
                {
                    Assert.IsTrue(patchedCode == 0x48);
                }
                else
                {
                    Assert.IsTrue(patchedCode == 0x68);
                }
            }

            (new Class4()).Method4("foo");
            Assert.IsTrue(Class4Patch.prefixed, "Prefix was not executed");
            Assert.IsTrue(Class4Patch.originalExecuted, "Original was not executed");
            Assert.AreEqual(Class4Patch.senderValue, "foo");
        }
Ejemplo n.º 22
0
        public void SetUp()
        {
            var testMethod   = TestContext.CurrentContext.Test.Name;
            var parts        = testMethod.Split('_');
            var originalType = AccessTools.TypeByName("HarmonyLibTests.Assets." + parts[1]);
            var patchType    = AccessTools.TypeByName("HarmonyLibTests.Assets." + parts[2]);

            Assert.IsNotNull(originalType);
            var originalMethod = originalType.GetMethod("Method");

            Assert.IsNotNull(originalMethod);

            var finalizer = patchType.GetMethod("Finalizer");

            Assert.IsNotNull(finalizer);

            var instance = new Harmony("test");

            Assert.IsNotNull(instance);
            var patcher = new PatchProcessor(instance, originalMethod);

            Assert.IsNotNull(patcher);
            patcher.AddFinalizer(finalizer);
            patcher.Patch();

            var trv = Traverse.Create(patchType);

            trv.Field("finalized").SetValue(false);
            trv.Field("exception").SetValue(new NullReferenceException("replace-me"));

            var obj      = Activator.CreateInstance(originalType);
            var m_method = AccessTools.Method(originalType, "Method");

            info = new Dictionary <string, object>();
            try
            {
                if (m_method.ReturnType == typeof(void))
                {
                    m_method.Invoke(obj, null);
                }
                else
                {
                    info["result"] = m_method.Invoke(obj, null);
                }
                info["outerexception"] = null;
            }
            catch (TargetInvocationException e)
            {
                info["outerexception"] = e.InnerException;
            }

            trv.Fields().ForEach(name => info[name] = trv.Field(name).GetValue());

            instance.UnpatchAll();

            Assert.IsTrue((bool)info["finalized"], "Finalizer not called");
        }
Ejemplo n.º 23
0
        public void TestMethod2()
        {
            var originalClass = typeof(Class2);

            Assert.IsNotNull(originalClass);
            var originalMethod = originalClass.GetMethod("Method2");

            Assert.IsNotNull(originalMethod);

            var patchClass     = typeof(Class2Patch);
            var realPrefix     = patchClass.GetMethod("Prefix");
            var realPostfix    = patchClass.GetMethod("Postfix");
            var realTranspiler = patchClass.GetMethod("Transpiler");

            Assert.IsNotNull(realPrefix);
            Assert.IsNotNull(realPostfix);
            Assert.IsNotNull(realTranspiler);

            Class2Patch._reset();

            MethodInfo prefixMethod;
            MethodInfo postfixMethod;
            MethodInfo transpilerMethod;

            PatchTools.GetPatches(typeof(Class2Patch), out prefixMethod, out postfixMethod, out transpilerMethod);

            Assert.AreSame(realPrefix, prefixMethod);
            Assert.AreSame(realPostfix, postfixMethod);
            Assert.AreSame(realTranspiler, transpilerMethod);

            var instance = HarmonyInstance.Create("test");

            Assert.IsNotNull(instance);

            var patcher = new PatchProcessor(instance, new List <MethodBase> {
                originalMethod
            }, new HarmonyMethod(prefixMethod), new HarmonyMethod(postfixMethod), new HarmonyMethod(transpilerMethod));

            Assert.IsNotNull(patcher);

            var originalMethodStartPre = Memory.GetMethodStart(originalMethod, out var exception);

            patcher.Patch();
            var originalMethodStartPost = Memory.GetMethodStart(originalMethod, out exception);

            Assert.AreEqual(originalMethodStartPre, originalMethodStartPost);

            new Class2().Method2();
            Warn.If(Class1Patch.prefixed != true, "Prefix was not executed");
            Warn.If(Class1Patch.originalExecuted != true, "Original was not executed");
            Warn.If(Class1Patch.postfixed != true, "Postfix was not executed");
            // Assert.IsTrue(Class1Patch.prefixed, "Prefix was not executed");
            // Assert.IsTrue(Class1Patch.originalExecuted, "Original was not executed");
            // Assert.IsTrue(Class1Patch.postfixed, "Postfix was not executed");
        }
        public static void PatchType(this HarmonyInstance instance, Type type)
        {
            var parentMethodInfos = type.GetHarmonyMethods();

            if (parentMethodInfos != null && parentMethodInfos.Count() > 0)
            {
                var info      = HarmonyMethod.Merge(parentMethodInfos);
                var processor = new PatchProcessor(instance, type, info);
                processor.Patch();
            }
        }
Ejemplo n.º 25
0
        public void TestMethod1()
        {
            var originalClass = typeof(Class1);

            Assert.IsNotNull(originalClass);
            var originalMethod = originalClass.GetMethod("Method1");

            Assert.IsNotNull(originalMethod);

            var patchClass = typeof(Class1Patch);
            var prefix     = patchClass.GetMethod("Prefix");
            var postfix    = patchClass.GetMethod("Postfix");
            var transpiler = patchClass.GetMethod("Transpiler");

            Assert.IsNotNull(prefix);
            Assert.IsNotNull(postfix);
            Assert.IsNotNull(transpiler);

            Class1Patch._reset();

            var instance = HarmonyInstance.Create("test");

            Assert.IsNotNull(instance);

            var patcher = new PatchProcessor(instance, new List <MethodBase> {
                originalMethod
            }, new HarmonyMethod(prefix), new HarmonyMethod(postfix), new HarmonyMethod(transpiler));

            Assert.IsNotNull(patcher);

            var originalMethodStartPre = Memory.GetMethodStart(originalMethod, out var exception);

            patcher.Patch();
            var originalMethodStartPost = Memory.GetMethodStart(originalMethod, out exception);

            Assert.AreEqual(originalMethodStartPre, originalMethodStartPost);
            unsafe
            {
                var patchedCode = *(byte *)originalMethodStartPre;
                if (IntPtr.Size == sizeof(long))
                {
                    Assert.IsTrue(patchedCode == 0x48);
                }
                else
                {
                    Assert.IsTrue(patchedCode == 0x68);
                }
            }

            Class1.Method1();
            Assert.IsTrue(Class1Patch.prefixed, "Prefix was not executed");
            Assert.IsTrue(Class1Patch.originalExecuted, "Original was not executed");
            Assert.IsTrue(Class1Patch.postfixed, "Postfix was not executed");
        }
Ejemplo n.º 26
0
        public void Enable(UnityModManager.ModEntry modEntry)
        {
            DateTime startTime = DateTime.Now;

            Debug($"[{DateTime.Now - startTime:ss':'ff}] Enabling.");

            try
            {
                Debug($"[{DateTime.Now - startTime:ss':'ff}] Loading settings.");
                Settings = UnityModManager.ModSettings.Load <TSettings>(modEntry);
                Mod      = new TMod();

                modEntry.OnSaveGUI += HandleSaveGUI;

                // patchcing
                if (!Patched)
                {
                    HarmonyInstance harmonyInstance = HarmonyInstance.Create(modEntry.Info.Id);
                    foreach (Type type in _assembly.GetTypes())
                    {
                        List <HarmonyMethod> harmonyMethods = type.GetHarmonyMethods();
                        if (harmonyMethods != null && harmonyMethods.Count() > 0)
                        {
                            Debug($"[{DateTime.Now - startTime:ss':'ff}] Patching: {type.DeclaringType?.Name}.{type.Name}");
                            HarmonyMethod  attributes     = HarmonyMethod.Merge(harmonyMethods);
                            PatchProcessor patchProcessor = new PatchProcessor(harmonyInstance, type, attributes);
                            patchProcessor.Patch();
                        }
                    }
                }
                Patched = true;

                // register events
                Debug($"[{DateTime.Now - startTime:ss':'ff}] Registering events.");
                _eventHandler = _assembly.GetTypes()
                                .Where(type => !type.IsInterface && !type.IsAbstract && typeof(IModEventHandler).IsAssignableFrom(type))
                                .Select(handler => Activator.CreateInstance(handler, true) as IModEventHandler).ToList();

                Enabled = true;

                Debug($"[{DateTime.Now - startTime:ss':'ff}] Raising events: 'OnEnable'");
                foreach (IModEventHandler handler in _eventHandler)
                {
                    handler.HandleModEnable();
                }
            }
            catch (Exception e)
            {
                Disable(modEntry, true);
                throw e;
            }

            Debug($"[{DateTime.Now - startTime:ss':'ff}] Enabled.");
        }
Ejemplo n.º 27
0
        public static void Patch(this HarmonyInstance harmony, Type type)
        {
            // Following copied from HarmonyInstance.PatchAll(Assembly).
            var harmonyMethods = type.GetHarmonyMethods();

            if (harmonyMethods != null && harmonyMethods.Count > 0)
            {
                var attributes     = HarmonyMethod.Merge(harmonyMethods);
                var patchProcessor = new PatchProcessor(harmony, type, attributes);
                patchProcessor.Patch();
            }
        }
Ejemplo n.º 28
0
        static HarmonyLoader()
        {
            // load directly embedded patches

            var harmony = new Harmony("harmony-loader-" + Guid.NewGuid().ToString("N"));

            var assembly = Assembly.GetExecutingAssembly();

            foreach (var type in assembly.GetTypes())
            {
                foreach (var method in type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic))
                {
                    var harmonyMethods = HarmonyMethodExtensions.GetFromMethod(method);
                    if (harmonyMethods is null || !harmonyMethods.Any())
                    {
                        continue;
                    }
                    var merged = new HarmonyMethod()
                    {
                        methodType = MethodType.Normal
                    }.Merge(HarmonyMethod.Merge(harmonyMethods));

                    Logger.LogDebug($"found method: {method} / {merged}");

                    var proc = new PatchProcessor(harmony);

                    proc.AddOriginal(PatchProcessor.GetOriginalMethod(merged) /*(MethodBase) Info.OfMethod<PatchProcessor>("GetOriginalMethod").Invoke(null, new[] {merged})*/);

                    if (method.GetCustomAttributes <HarmonyTranspiler>().Any())
                    {
                        proc.AddTranspiler(method);
                    }
                    if (method.GetCustomAttributes <HarmonyPrefix>().Any())
                    {
                        proc.AddPrefix(method);
                    }
                    if (method.GetCustomAttributes <HarmonyPostfix>().Any())
                    {
                        proc.AddPostfix(method);
                    }
                    if (method.GetCustomAttributes <HarmonyFinalizer>().Any())
                    {
                        proc.AddFinalizer(method);
                    }

                    proc.Patch();
                }
            }

            // load the normal style of patches
            Harmony.CreateAndPatchAll(typeof(AutoLoadManager).Assembly);
        }
Ejemplo n.º 29
0
        static HarmonyLoader()
        {
            // load directly embedded patches

            var harmony = new Harmony("harmony-loader-" + Guid.NewGuid().ToString("N"));

            var assembly = Assembly.GetExecutingAssembly();

            foreach (var type in assembly.GetTypes())
            {
                foreach (var method in type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic))
                {
                    var harmonyMethods = HarmonyMethodExtensions.GetFromMethod(method);
                    if (harmonyMethods is null || !harmonyMethods.Any())
                    {
                        continue;
                    }
                    var merged = new HarmonyMethod()
                    {
                        methodType = MethodType.Normal
                    }.Merge(HarmonyMethod.Merge(harmonyMethods));

                    Logger.LogDebug($"found method: {method} / {merged}");

#if BepInEx
                    var proc = new PatchProcessor(harmony);
                    proc.AddOriginal(PatchProcessor.GetOriginalMethod(merged));
#elif UMM
                    var proc = new PatchProcessor(harmony, merged.GetOriginalMethod());
#endif

                    if (method.GetCustomAttributes <HarmonyTranspiler>().Any())
                    {
                        proc.AddTranspiler(method);
                    }
                    if (method.GetCustomAttributes <HarmonyPrefix>().Any())
                    {
                        proc.AddPrefix(method);
                    }
                    if (method.GetCustomAttributes <HarmonyPostfix>().Any())
                    {
                        proc.AddPostfix(method);
                    }
                    if (method.GetCustomAttributes <HarmonyFinalizer>().Any())
                    {
                        proc.AddFinalizer(method);
                    }

                    proc.Patch();
                }
            }
        }
 //Applies the patch.
 private static void ApplyPatch(PatchInfo patch)
 {
     try
     {
         PatchProcessor proc = new PatchProcessor(harmony, patch.patchClass, patch.target);
         proc.Patch();
         appliedPatches.Add(proc);
     }
     catch (Exception ex)
     {
         Debug.Log(string.Format("PostDbPatcher: Failed to apply patch for {0}, targetting {1}.{2}({3}): {4}", patch.patchClass.FullName, patch.target.declaringType, patch.target.methodName ?? ".ctor", ArgumentsToString(patch.target.argumentTypes), ex.ToString()));
     }
 }