Exemple #1
0
 void IMainView.ShowEditHookForm(MethodHook methodHook)
 {
     using (frmEditHook form = new frmEditHook(methodHook))
     {
         form.ShowDialog();
     }
 }
    public void Test()
    {
        Type typeA = typeof(PropClassA);
        Type typeB = typeof(PropClassB);

        PropertyInfo pi     = typeA.GetProperty("X");
        MethodInfo   miASet = pi.GetSetMethod();

        MethodInfo miBReplace = typeB.GetMethod("PropXSetReplace");
        MethodInfo miBProxy   = typeB.GetMethod("PropXSetProxy");

        if (miBProxy == null)
        {
            throw new Exception("PropXSetProxy is null");
        }

        MethodHook hook = new MethodHook(miASet, miBReplace, miBProxy);

        hook.Install();

        PropClassA a = new PropClassA(5);

        a.X = 7;
        Debug.Assert(a.X == 8);

        a.X = 100;
        Debug.Assert(a.X == 101);
    }
Exemple #3
0
    public string Test()
    {
        Type typeA = typeof(A);
        Type typeB = typeof(B);

        MethodInfo miAFunc    = typeA.GetMethod("Func");
        MethodInfo miBReplace = typeB.GetMethod("FuncReplace");
        MethodInfo miBProxy   = typeB.GetMethod("FuncProxy");

        MethodHook hooker = new MethodHook(miAFunc, miBReplace, miBProxy);

        hooker.Install();

        // 调用原始A的方法测试
        A a = new A()
        {
            val = 5
        };
        int    ret  = a.Func(2);
        string info = string.Format("ret:{0}", ret);

        Debug.Log(info);
        Debug.Assert(ret == 10);
        return(info);
    }
        private void GenerateAssembly(MethodHook methodHook, string code, string path)
        {
            var compilerOptions = new Dictionary <string, string>();

            compilerOptions.Add("CompilerVersion", "v4.0");

            CSharpCodeProvider provider = new CSharpCodeProvider(compilerOptions);

            CompilerParameters cp = new CompilerParameters();

            cp.ReferencedAssemblies.Clear();
            cp.ReferencedAssemblies.AddRange(GetReferencedAssemblies());
            cp.GenerateExecutable = false;
            cp.GenerateInMemory   = false;
            // do not include standard mscorlib.dll
            cp.CompilerOptions = "/noconfig /nostdlib";
            string dllName = String.Format("{0}.dll", methodHook.GetSafeName());

            cp.OutputAssembly = Path.Combine(path, dllName);

            CompilerResults results = provider.CompileAssemblyFromSource(cp, code);

            if (results.Errors.Count > 0)
            {
                string errors = String.Join(Environment.NewLine, results.Errors.Cast <CompilerError>().Select(e => e.ErrorText));
                throw new InvalidOperationException("Unable to compile custom code: " + Environment.NewLine + errors);
            }
        }
    public static void UninstallPatch()
    {
        if (_hook != null)
        {
            _hook.Uninstall();
        }

        _hook = null;
    }
Exemple #6
0
        internal void AddMethodHook()
        {
            string selectedMethod = m_view.ShowSearchForm(m_hooks.Select(h => h.ToString()));

            if (selectedMethod != null)
            {
                MethodHook hook = m_hooks.First(h => h.ToString() == selectedMethod);
                m_view.AddMethod(hook);
            }
        }
Exemple #7
0
 public static void Main1(string[] args)
 {
     MethodHook.Install();
     test();
     Console.WriteLine("end");
     //Console.ReadLine();
     //Console.ReadLine();
     //Console.ReadLine();
     //Console.ReadLine();
 }
Exemple #8
0
        public void ConstructorMethod()
        {
            MethodHook.Install();

            CallContext.LogicalSetData("OpenComputerConstructorHook", "1");
            var o = new Computer();

            CallContext.LogicalSetData("OpenComputerConstructorHook", null);

            Assert.AreEqual("ConstructorMethod X1", o.Name);
        }
    public static void InstallPatch()
    {
        Type typeA = typeof(A);
        Type typeB = typeof(B);

        MethodInfo miAFunc    = typeA.GetMethod("Func");
        MethodInfo miBReplace = typeB.GetMethod("FuncReplace");
        MethodInfo miBProxy   = typeB.GetMethod("FuncProxy");

        _hook = new MethodHook(miAFunc, miBReplace, miBProxy);
        _hook.Install();
    }
Exemple #10
0
 private void FillAssemblyMethods(XAPAssembly xapAssembly)
 {
     foreach (var method in xapAssembly.GetMethods())
     {
         var hook = new MethodHook(method)
         {
             LogMethodName      = true,
             LogParameterValues = true,
             LogReturnValues    = true
         };
         m_hooks.Add(hook);
     }
 }
 /// <summary>
 /// Hook 初始化
 /// </summary>
 /// <param name="msg"></param>
 /// <returns></returns>
 public static int Start(string msg)
 {
     try
     {
         TextHelper.LogInfo("开始" + msg);
         MethodHook.Install();
     }
     catch
     {
         return(-1);
     }
     return(1);
 }
 public static string GetSafeName(this MethodHook methodHook)
 {
     return(methodHook.ToString()
            .Replace(" ", "_")
            .Replace(".", "_")
            .Replace("(", "_")
            .Replace(")", "")
            .Replace("[", "_")
            .Replace("]", "_")
            .Replace(",", "")
            .Replace("/", "_")
            .Replace("\\", "_"));
 }
Exemple #13
0
    public static void Init()
    {
        if (_hook == null)
        {
            Type       type     = typeof(GameObject).Assembly.GetType("UnityEngine.GameObject");
            MethodInfo miTarget = type.GetMethod("SetActive", BindingFlags.Instance | BindingFlags.Public);

            MethodInfo miReplacement = new Action <GameObject, bool>(SetActiveNew).Method;
            MethodInfo miProxy       = new Action <GameObject, bool>(SetActiveProxy).Method;

            _hook = new MethodHook(miTarget, miReplacement, miProxy);
            _hook.Install();
        }
    }
    static GameObject_CreatePrimitive_HookTest()
    {
        if (_hook == null)
        {
            Type       type     = typeof(AssetDatabase).Assembly.GetType("UnityEditor.GOCreationCommands");
            MethodInfo miTarget = type.GetMethod("CreateAndPlacePrimitive", BindingFlags.Static | BindingFlags.NonPublic);

            MethodInfo miReplacement = new Action <PrimitiveType, GameObject>(CreateAndPlacePrimitive).Method;
            MethodInfo miProxy       = new Action <PrimitiveType, GameObject>(CreateAndPlacePrimitiveProxy).Method;

            _hook = new MethodHook(miTarget, miReplacement, miProxy);
            _hook.Install();
        }
    }
    public static void AddHook(MethodBase method, MethodHook hook)
    {
        MethodHook preHook;

        if (_hooks.TryGetValue(method, out preHook))
        {
            preHook.Uninstall();
            _hooks[method] = hook;
        }
        else
        {
            _hooks.Add(method, hook);
        }
    }
Exemple #16
0
    public static void AddHooker(MethodBase method, MethodHook hooker)
    {
        MethodHook preHooker;

        if (_hookers.TryGetValue(method, out preHooker))
        {
            preHooker.Uninstall();
            _hookers[method] = hooker;
        }
        else
        {
            _hookers.Add(method, hooker);
        }
    }
        void ICustomCodeGenerator.GenerateAssembly(MethodHook methodHook, string path)
        {
            if (methodHook == null)
            {
                throw new ArgumentNullException("methodHook");
            }
            if (!methodHook.RunCustomCode)
            {
                throw new ArgumentException("RunCustomCode should be set in order to generate custom code");
            }

            StringBuilder customCode = new StringBuilder();

            foreach (string ns in m_referencedNamespaces)
            {
                customCode.AppendLine(String.Format("using {0};", ns));
            }
            customCode.AppendLine();

            customCode.AppendLine(String.Format("namespace {0}", CustomNamespace));
            customCode.AppendLine("{");

            string name      = GetName(methodHook);
            string className = String.Format("{0}_{1}", name, "Class");

            customCode.AppendLine(String.Format("public class {0}", className));
            customCode.AppendLine("{");

            string returnType = GetReturnType(methodHook);
            string methodName = String.Format("{0}_{1}", name, "Hook");
            var    parameters = methodHook.Method.Parameters.Cast <ParameterDefinition>().Select(
                p => "ref " + p.ParameterType.Name + " " + p.Name
                );
            string parametersString = String.Join(", ", parameters);

            customCode.AppendLine(String.Format("public {0} {1}({2})", returnType, methodName, parametersString));
            customCode.AppendLine("{");

            customCode.AppendLine(methodHook.Code);

            // method
            customCode.AppendLine("}");
            // class
            customCode.AppendLine("}");
            // namespace
            customCode.AppendLine("}");

            GenerateAssembly(methodHook, customCode.ToString(), path);
        }
Exemple #18
0
        public void InstanceMethod2()
        {
            MethodHook.Install();
            Assert.AreEqual("Hook 土豆(worked)", new Computer().Work("土豆"));

            //注意:存在SynchronizationContext时(如:HttpContext),异步方法不能直接在同步方法中调用,真发生异步行为时100%死锁
            var bak = SynchronizationContext.Current;

            SynchronizationContext.SetSynchronizationContext(null);
            try {
                Assert.AreEqual("Hook 土豆(workedAsync)", new Computer().WorkAsync("土豆").Result);
            } finally {
                SynchronizationContext.SetSynchronizationContext(bak);
            }
        }
Exemple #19
0
    public void Test()
    {
        MethodBase mbCtorA   = typeof(CtorHookTarget).GetConstructor(new Type[] { typeof(int) });
        MethodInfo mbReplace = new Action <int>(CtorTargetReplace).Method;
        MethodInfo mbProxy   = new Action <int>(CtorTargetProxy).Method;

        MethodHook hookder = new MethodHook(mbCtorA, mbReplace, mbProxy);

        hookder.Install();

        for (int i = 0; i < 2; i++)
        {
            CtorHookTarget hookTarget = new CtorHookTarget(1);
            Debug.Assert(hookTarget.x == 2, $"expect 2 but get {hookTarget.x} at i:{i}");
        }
    }
Exemple #20
0
    static GameObject_SetActive_HookTest()
    {
        if (_hook == null)
        {
            Type type = typeof(GameObject).Assembly.GetType("UnityEngine.GameObject");

            MethodInfo miTarget = type.GetMethod("SetActive", BindingFlags.Instance | BindingFlags.Public);

            type = typeof(GameObject_SetActive_HookTest);
            MethodInfo miReplacement = type.GetMethod("SetActiveNew", BindingFlags.Static | BindingFlags.NonPublic);
            MethodInfo miProxy       = type.GetMethod("SetActiveProxy", BindingFlags.Static | BindingFlags.NonPublic);

            _hook = new MethodHook(miTarget, miReplacement, miProxy);
            _hook.Install();
        }
    }
Exemple #21
0
    public void Test()
    {
        Type typeA = typeof(CtorHookTarget);
        Type typeB = typeof(CtorHookTest);

        MethodBase mbCtorA   = typeA.GetConstructor(new Type[] { typeof(int) });
        MethodBase mbReplace = typeB.GetMethod("CtorTargetReplace");
        MethodBase mbProxy   = typeB.GetMethod("CtorTargetProxy");

        MethodHook hookder = new MethodHook(mbCtorA, mbReplace, mbProxy);

        hookder.Install();

        CtorHookTarget hookTarget = new CtorHookTarget(1);

        Debug.Assert(hookTarget.x == 2);
    }
Exemple #22
0
        public void ModifyGnomoria()
        {
            Reference.GnomodiaDirectory.GetFile(RuntimeModController.Log.LogfileName).Delete();

            var sourceExe = Reference.GameDirectory.GetFile(Reference.OriginalExecutable);
            var moddedExe = Reference.GnomodiaDirectory.GetFile(Reference.ModdedExecutable);
            var sourceLib = Reference.GameDirectory.GetFile(Reference.OriginalLibrary);
            var moddedLib = Reference.GnomodiaDirectory.GetFile(Reference.ModdedLibrary);

            var gameInjector = new GnomoriaExeInjector(sourceExe);
            var libInjector  = new Injector(sourceLib);

            gameInjector.InitializeGnomodia(Reference.GnomodiaDirectory.GetFile(Reference.GnomodiaLibrary));
            gameInjector.InjectMapGenerationCalls();
            gameInjector.InjectSaveLoadCalls();
            //gameInjector.Debug_ManipulateStuff();

            foreach (var mod in ModManager.CreateOrGetAllMods())
            {
                var interceptedMethods =
                    from method in mod.GetType().GetMethods(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)
                    where method.GetCustomAttributes(typeof(InterceptMethodAttribute), false).Any()
                    select new { Method = method, Attribute = method.GetCustomAttributes(typeof(InterceptMethodAttribute), false).Cast <InterceptMethodAttribute>().Single() };

                foreach (var interceptedMethod in interceptedMethods)
                {
                    var           attribute = interceptedMethod.Attribute;
                    IModification mh        = new MethodHook(attribute.InterceptedMethod, interceptedMethod.Method, attribute.HookType, attribute.HookFlags);
                    if (gameInjector.AssemblyContainsType(mh.TargetType))
                    {
                        gameInjector.InjectModification(mh);
                    }
                    else if (libInjector.AssemblyContainsType(mh.TargetType))
                    {
                        libInjector.InjectModification(mh);
                    }
                    else
                    {
                        throw new InvalidOperationException(string.Format("Cannot change behavior of type {0}!", mh.TargetType));
                    }
                }
            }

            gameInjector.Write(moddedExe);
            libInjector.Write(moddedLib);
        }
    static SceneHierarchyStageHandling_HookTest()
    {
        if (_hook == null)
        {
            Type type = Type.GetType("UnityEditor.SceneHierarchyStageHandling,UnityEditor.dll");
#if UNITY_2021_2_OR_NEWER
            var target = type.GetMethod("StageHeaderGUI", BindingFlags.Instance | BindingFlags.Public);
#else
            var target = type.GetMethod("PrefabStageHeaderGUI", BindingFlags.Instance | BindingFlags.Public);
#endif
            var dst = new Action <object, Rect>(PrefabStageHeaderGUINew).Method;
            var old = new Action <object, Rect>(PrefabStageHeaderGUIOld).Method;

            _hook = new MethodHook(target, dst, old);
            _hook.Install();
        }
    }
Exemple #24
0
    public void Test()
    {
        Type typeA = typeof(PrivateTestA);
        Type typeB = typeof(PrivateTestB);

        MethodInfo miAPrivateFunc = typeA.GetMethod("InnerFuncTest", BindingFlags.Instance | BindingFlags.NonPublic);
        MethodInfo miBReplace     = typeB.GetMethod("FuncReplace");
        MethodInfo miBProxy       = typeB.GetMethod("Proxy");

        MethodHook hooker = new MethodHook(miAPrivateFunc, miBReplace, miBProxy);

        hooker.Install();

        PrivateTestA privateTestA = new PrivateTestA();

        privateTestA.FuncTest();
    }
Exemple #25
0
    static PinnedLog()
    {
        if (_hook == null)
        {
#if UNITY_2017_1_OR_NEWER
            Type type = Type.GetType("UnityEditor.LogEntries,UnityEditor.dll");
#else
            Type type = Type.GetType("UnityEditorInternal.LogEntries,UnityEditor.dll");
#endif
            MethodInfo miTarget = type.GetMethod("Clear", BindingFlags.Static | BindingFlags.Public);

            MethodInfo miReplacement = new Action(NewClearLog).Method;
            MethodInfo miProxy       = new Action(ProxyClearLog).Method;

            _hook = new MethodHook(miTarget, miReplacement, miProxy);
            _hook.Install();
        }
    }
Exemple #26
0
    static ProjectWindow_DuplicateAsset_HookTest()
    {
        if (_hook == null)
        {
#if UNITY_2021_2_OR_NEWER
            Type type = typeof(UnityEditor.AssetDatabase).Assembly.GetType("UnityEditor.AssetClipboardUtility");
#else
            Type type = typeof(UnityEditor.AssetDatabase).Assembly.GetType("UnityEditor.ProjectWindowUtil");
#endif
            MethodInfo miTarget = type.GetMethod("DuplicateSelectedAssets", BindingFlags.Static | BindingFlags.NonPublic);

            MethodInfo miReplacement = new Action(DuplicateSelectedAssets).Method;
            MethodInfo miProxy       = new Action(DuplicateSelectedAssetsProxy).Method;

            _hook = new MethodHook(miTarget, miReplacement, miProxy);
            _hook.Install();
        }
    }
Exemple #27
0
        public void GenericMethodMethod()
        {
            MethodHook.Install();

            Assert.AreEqual("Hook<int> 123", Computer.Any <int>(123));
            //引用类型的没法正确hook,不知道啥原因
            //Assert.AreEqual("Hook<string> str", Computer.Any<string>("str"));


            //注意:存在SynchronizationContext时(如:HttpContext),异步方法不能直接在同步方法中调用,真发生异步行为时100%死锁
            var bak = SynchronizationContext.Current;

            SynchronizationContext.SetSynchronizationContext(null);
            try {
                Assert.AreEqual("Hook<int> 123Async", Computer.AnyAsync <int>(123).Result);
            } finally {
                SynchronizationContext.SetSynchronizationContext(bak);
            }
        }
Exemple #28
0
    static PinnedLog()
    {
        if (_hooker == null)
        {
#if UNITY_2017 || UNITY_2018 || UNITY_2019 || UNITY_2020
            Type type = Type.GetType("UnityEditor.LogEntries,UnityEditor.dll");
#else
            Type type = Type.GetType("UnityEditorInternal.LogEntries,UnityEditor.dll");
#endif
            MethodInfo miTarget = type.GetMethod("Clear", BindingFlags.Static | BindingFlags.Public);

            type = typeof(PinnedLog);
            MethodInfo miReplacement = type.GetMethod("NewClearLog", BindingFlags.Static | BindingFlags.NonPublic);
            MethodInfo miProxy       = type.GetMethod("ProxyClearLog", BindingFlags.Static | BindingFlags.NonPublic);

            _hooker = new MethodHook(miTarget, miReplacement, miProxy);
            _hooker.Install();
        }
    }
Exemple #29
0
    static SceneHierarchyStageHandling_HookTest()
    {
        if (_hooker == null)
        {
            Type type = Type.GetType("UnityEditor.SceneHierarchyStageHandling,UnityEditor.dll");
#if UNITY_2021_2_OR_NEWER
            var target = type.GetMethod("StageHeaderGUI", BindingFlags.Instance | BindingFlags.Public);
#else
            var target = type.GetMethod("PrefabStageHeaderGUI", BindingFlags.Instance | BindingFlags.Public);
#endif
            var dst = typeof(SceneHierarchyStageHandling_HookTest).GetMethod("PrefabStageHeaderGUINew",
                                                                             BindingFlags.Static | BindingFlags.NonPublic);
            var old = typeof(SceneHierarchyStageHandling_HookTest).GetMethod("PrefabStageHeaderGUIOld",
                                                                             BindingFlags.Static | BindingFlags.NonPublic);

            _hooker = new MethodHook(target, dst, old);
            _hooker.Install();
        }
    }
Exemple #30
0
        public void GenericTypeMethod()
        {
            MethodHook.Install();

            Assert.AreEqual("Hook<string> Jack", new ComputerOf <string>().ComputerIo("Jack"));

            Assert.AreEqual("Hook<object> X1", new ComputerOf <Computer>().ComputerIo(new Computer()).Name);

            Assert.AreEqual(5, new ComputerOf <int>().ComputerIo(4));

            //注意:存在SynchronizationContext时(如:HttpContext),异步方法不能直接在同步方法中调用,真发生异步行为时100%死锁
            var bak = SynchronizationContext.Current;

            SynchronizationContext.SetSynchronizationContext(null);
            try {
                Assert.AreEqual(5, new ComputerOf <int>().ComputerIoAsync(4).Result);
            } finally {
                SynchronizationContext.SetSynchronizationContext(bak);
            }
        }