public static RedirectCallsState RedirectCalls(MethodInfo from, MethodInfo to)
        {
            RuntimeMethodHandle methodHandle = from.MethodHandle;
            IntPtr functionPointer1          = methodHandle.GetFunctionPointer();

            methodHandle = to.MethodHandle;
            IntPtr functionPointer2 = methodHandle.GetFunctionPointer();

            return(RedirectionHelper.PatchJumpTo(functionPointer1, functionPointer2));
        }
Esempio n. 2
0
    public static void  RuntimeMethodHandleTest()
    {
        MethodInfo          minfo = typeof(Co6006LateBoundDelegate).GetMethod("Method1");
        RuntimeMethodHandle rmh   = minfo.MethodHandle;

        Assert.True(rmh.Value != null);
        Assert.True(rmh.GetFunctionPointer() != null);
        Object []  args = new Object[] { null, rmh.GetFunctionPointer() };
        MyDelegate dg   = (MyDelegate)Activator.CreateInstance(typeof(MyDelegate), args);

        dg();
        Assert.True(Co6006LateBoundDelegate.iInvokeCount == 1);
    }
Esempio n. 3
0
        private static IntPtr GetMethodStart(MethodBase method)
        {
            RuntimeMethodHandle handle = GetRuntimeMethodHandle(method);

            RuntimeHelpers.PrepareMethod(handle);
            return(handle.GetFunctionPointer());
        }
Esempio n. 4
0
        private static unsafe MethodDesc *GetMethodDesc(this RuntimeMethodHandle handle)
        {
            IntPtr addr    = handle.GetFunctionPointer();
            var    precode = (FixupPrecode *)addr;

            const byte callRel32 = 0xE8;
            const byte jmpRel32  = 0xE9;

            bool validOp   = precode->m_op == jmpRel32 || precode->m_op == callRel32;
            bool validType = precode->m_type == FixupPrecode.TypePrestub || precode->m_type == FixupPrecode.Type;

            if (!validOp || !validType)
            {
                return(null);
            }

            byte methodDescChunkIndex = precode->m_MethodDescChunkIndex;
            byte precodeChunkIndex    = precode->m_PrecodeChunkIndex;

            // coreclr/src/vm/i368/stublinkerx86.h: FixupPrecode::GetBase
            // coreclr/src/vm/i368/stublinkerx86.cpp: FixupPrecode::GetMethodDesc
            IntPtr methodDescChunkBase = *(IntPtr *)(addr + (precodeChunkIndex + 1) * sizeof(FixupPrecode));
            IntPtr methodDescAddr      = methodDescChunkBase + methodDescChunkIndex * sizeof(void *);

            return((MethodDesc *)methodDescAddr);
        }
Esempio n. 5
0
        public void ctor(HUD.HUD hud, FContainer fContainer)
        {
            Type[] constructorSignature = new Type[1];
            constructorSignature[0] = typeof(HUD.HUD);
            RuntimeMethodHandle handle = typeof(HudPart).GetConstructor(constructorSignature).MethodHandle;

            RuntimeHelpers.PrepareMethod(handle);
            IntPtr           ptr   = handle.GetFunctionPointer();
            Action <HUD.HUD> funct = (Action <HUD.HUD>)Activator.CreateInstance(typeof(Action <HUD.HUD>), this, ptr);

            funct(hud);//HudPart Constructor
            this.lastPos = this.pos;

            if (hud.owner != null & hud.owner is Player)
            {
                if (MonklandSteamManager.isInGame)
                {
                    this.circles = new HUDCircle[MonklandSteamManager.WorldManager.cycleLength / 1200];
                }
                else
                {
                    this.circles = new HUDCircle[(hud.owner as Player).room.world.rainCycle.cycleLength / 1200];
                }
            }
            else if (hud.owner != null & (hud.owner is MultiplayerSleepAndDeathScreen) && MonklandSteamManager.isInGame && MonklandSteamManager.WorldManager != null)
            {
                this.circles = new HUDCircle[MonklandSteamManager.WorldManager.cycleLength / 1200];
            }
            for (int i = 0; i < this.circles.Length; i++)
            {
                this.circles[i] = new HUDCircle(hud, HUDCircle.SnapToGraphic.smallEmptyCircle, fContainer, 0);
            }
        }
Esempio n. 6
0
    public void ctor(HUD.HUD hud, FContainer fContainer)
    {
        Type[] constructorSignature = new Type[1];
        constructorSignature[0] = typeof(HUD.HUD);
        RuntimeMethodHandle handle = typeof(HudPart).GetConstructor(constructorSignature).MethodHandle;

        RuntimeHelpers.PrepareMethod(handle);
        IntPtr           ptr   = handle.GetFunctionPointer();
        Action <HUD.HUD> funct = (Action <HUD.HUD>)Activator.CreateInstance(typeof(Action <HUD.HUD>), this, ptr);

        funct(hud);//HudPart Constructor
        this.lastPos = this.pos;

        if (hud.owner != null & hud.owner is Player)
        {
            this.circles = new HUDCircle[(hud.owner as Player).room.world.rainCycle.cycleLength / 1200];
        }
        else if (hud.owner != null & (hud.owner is patch_SleepAndDeathScreen))
        {
            this.circles = new HUDCircle[(hud.owner as patch_SleepAndDeathScreen).nextcycleLength / 1200];
        }
        for (int i = 0; i < this.circles.Length; i++)
        {
            this.circles[i] = new HUDCircle(hud, HUDCircle.SnapToGraphic.smallEmptyCircle, fContainer, 0);
        }
        if (hud.owner != null & hud.owner is Player)
        {
            if (((hud.owner as Player).room.world.rainCycle as patch_RainCycle).getBurstIndex(0) < this.circles.Length)
            {
                (this.circles[((hud.owner as Player).room.world.rainCycle as patch_RainCycle).getBurstIndex(0)] as patch_HUDCircle).danger = true;
            }
            if (((hud.owner as Player).room.world.rainCycle as patch_RainCycle).getBurstIndex(1) < this.circles.Length)
            {
                (this.circles[((hud.owner as Player).room.world.rainCycle as patch_RainCycle).getBurstIndex(1)] as patch_HUDCircle).danger = true;
            }
            if (((hud.owner as Player).room.world.rainCycle as patch_RainCycle).getBurstIndex(2) < this.circles.Length)
            {
                (this.circles[((hud.owner as Player).room.world.rainCycle as patch_RainCycle).getBurstIndex(2)] as patch_HUDCircle).danger = true;
            }
        }
        else if (hud.owner != null & !(hud.owner is Player) & (hud.owner is patch_SleepAndDeathScreen))
        {
            if ((hud.owner as patch_SleepAndDeathScreen).getBurst(0) < this.circles.Length)
            {
                (this.circles[(hud.owner as patch_SleepAndDeathScreen).getBurst(0)] as patch_HUDCircle).danger = true;
            }
            if ((hud.owner as patch_SleepAndDeathScreen).getBurst(1) < this.circles.Length)
            {
                (this.circles[(hud.owner as patch_SleepAndDeathScreen).getBurst(1)] as patch_HUDCircle).danger = true;
            }
            if ((hud.owner as patch_SleepAndDeathScreen).getBurst(2) < this.circles.Length)
            {
                (this.circles[(hud.owner as patch_SleepAndDeathScreen).getBurst(2)] as patch_HUDCircle).danger = true;
            }
            (hud.owner as patch_SleepAndDeathScreen).nextcycleLength  = (hud.owner as patch_SleepAndDeathScreen).nextcycleLength2;
            (hud.owner as patch_SleepAndDeathScreen).nextcycleLength2 = (hud.owner as patch_SleepAndDeathScreen).nextcycleLength3;
            (hud.owner as patch_SleepAndDeathScreen).burstNum         = (hud.owner as patch_SleepAndDeathScreen).burstNum2;
            (hud.owner as patch_SleepAndDeathScreen).burstNum2        = (hud.owner as patch_SleepAndDeathScreen).burstNum3;
        }
    }
        public static IntPtr PrepareMethod(this DynamicMethod meth)
        {
            Type t = meth.GetType();
            RuntimeMethodHandle handle =
                t.GetMethod("GetMethodDescriptor", mflag0) is MethodInfo getmd
                    ? (RuntimeMethodHandle)getmd.Invoke(meth, null)
                    : t.GetField("m_method", mflag0) is FieldInfo mm
                    ? (RuntimeMethodHandle)mm.GetValue(meth)
                    : (RuntimeMethodHandle)t.GetField("mhandle", mflag0).GetValue(meth);

            Type ht = handle.GetType();

            object result =
                ht.GetField("m_value", mflag0) is FieldInfo fd
                ? fd.GetValue(handle)
                : ht.GetMethod("GetMethodInfo", mflag0) is MethodInfo mi
                ? mi.Invoke(handle, null)
                : null;

            if (result != null)
            {
                try
                {
                    // 2020 01 30
                    // dynamicmethod 코드에 전혀 문제가 없는 경우에
                    // 여기서 오류가 발생하지 않는다
                    m_compileMeth.Invoke(null, new object[1] {
                        result
                    });
                    return(handle.GetFunctionPointer());
                }
            }
Esempio n. 8
0
 public static void Ngen(Type type)
 {
     if (type == null)
     {
         throw new ArgumentNullException("type");
     }
     foreach (var m in type.GetMethods(BindingFlags.NonPublic | BindingFlags.Public
                                       | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly))
     {
         if (m.IsGenericMethod || m.IsAbstract)
         {
             continue;
         }
         MethodBody body = m.GetMethodBody();
         if (body == null)
         {
             throw new InvalidProgramException("In a given program there is a case where a method does not have a code-body.");
         }
         byte[] il = body.GetILAsByteArray();
         if (il == null || il.Length <= 0)
         {
             throw new InvalidProgramException("In the specified program, there is an error function that does not have any il instruction");
         }
         RuntimeMethodHandle handle = m.MethodHandle;
         IntPtr address             = handle.GetFunctionPointer();
         if (address == IntPtr.Zero)
         {
             throw new InvalidProgramException("In the given assembly a method that failed to get the function native-code address was found");
         }
     }
 }
    public static IntPtr GetFunctionPointer()
    {
        A obj1 = new A();
        RuntimeMethodHandle method = ((Action)obj1.Method1).Method.MethodHandle;
        IntPtr p = method.GetFunctionPointer();

        return(p);
    }
Esempio n. 10
0
 public MethodJitResult(RuntimeMethodHandle handle, MethodJitStatus status)
 {
     Handle  = handle.Value;
     Pointer = GetIsSuccess(status)
             ? handle.GetFunctionPointer()
             : (IntPtr?)null;
     Status = status;
 }
Esempio n. 11
0
        private void PrepareDetour()
        {
            // Ensure both methods are JIT compiled

            RuntimeHelpers.PrepareMethod(_originalMethodHandle);

            RuntimeHelpers.PrepareMethod(_targetMethodHandle);

            // Construct the shellcode needed to detour the method

            var shellcode = new List <byte>();

            if (Environment.Is64BitProcess)
            {
                // mov rax, targetMethodAddress

                shellcode.AddRange(new byte[] { 0x48, 0xB8 });

                shellcode.AddRange(BitConverter.GetBytes((long)_targetMethodHandle.GetFunctionPointer()));

                // jmp rax

                shellcode.AddRange(new byte[] { 0xFF, 0xE0 });
            }

            else
            {
                // mov eax, targetMethodAddress

                shellcode.Add(0xB8);

                shellcode.AddRange(BitConverter.GetBytes((int)_targetMethodHandle.GetFunctionPointer()));

                // jmp eax

                shellcode.AddRange(new byte[] { 0xFF, 0xE0 });
            }

            _detourBytes = shellcode.ToArray();

            // Save the bytes of the original method

            _originalMethodBytes = new byte[_detourBytes.Length];

            Marshal.Copy(_originalMethodHandle.GetFunctionPointer(), _originalMethodBytes, 0, _detourBytes.Length);
        }
        public static RedirectCallsState RedirectCalls(RuntimeMethodHandle from, RuntimeMethodHandle to)
        {
            // GetFunctionPointer enforces compilation of the method.
            var fptr1 = from.GetFunctionPointer();
            var fptr2 = to.GetFunctionPointer();

            return(PatchJumpTo(fptr1, fptr2));
        }
Esempio n. 13
0
        // [JUNK]

        void ShitFunc(Type T, string mtdName)
        {
            //  T.InvokeMember(mtdName, BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.Public, null, null, null);
            RuntimeMethodHandle mtdHandle = ((MethodInfo)(T.GetMember(mtdName, BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.Public)[0])).MethodHandle;
            MtdSig mtd = (MtdSig)Marshal.GetDelegateForFunctionPointer(mtdHandle.GetFunctionPointer(), typeof(MtdSig));

            mtd();
        }
Esempio n. 14
0
        internal static void ReplaceMethod(MethodBase oldmethod, IntPtr newmethod_ptr)
        {
            RuntimeMethodHandle o_handle = oldmethod.MethodHandle;

            RuntimeHelpers.PrepareMethod(o_handle);

            WriteIL(o_handle.GetFunctionPointer(), newmethod_ptr);
        }
 public MethodJitResult(RuntimeMethodHandle handle, MethodJitStatus status, bool isGeneric)
 {
     Handle  = handle.Value;
     Pointer = status == MethodJitStatus.Success
             ? handle.GetFunctionPointer()
             : (IntPtr?)null;
     Status    = status;
     IsGeneric = isGeneric;
 }
Esempio n. 16
0
        private void Redirect(RuntimeMethodHandle from, RuntimeMethodHandle to)
        {
            RuntimeHelpers.PrepareMethod(from);
            RuntimeHelpers.PrepareMethod(to);


            // Just in case someone calls apply twice or something, let's not get the same ptr for no reason.
            if (_fromPtr == default(IntPtr))
            {
                _fromPtr = from.GetFunctionPointer();
            }
            if (_toPtr == default(IntPtr))
            {
                _toPtr = to.GetFunctionPointer();
            }

            FromPtrData = new byte[32];
            Marshal.Copy(_fromPtr, FromPtrData, 0, 32);

            VirtualProtect(_fromPtr, (IntPtr)5, 0x40, out uint x);

            if (IntPtr.Size == 8)
            {
                // x64

                _originalPtrData = new byte[13];

                // 13
                Marshal.Copy(_fromPtr, _originalPtrData, 0, 13);

                Marshal.WriteByte(_fromPtr, 0, 0x49);
                Marshal.WriteByte(_fromPtr, 1, 0xbb);

                Marshal.WriteInt64(_fromPtr, 2, _toPtr.ToInt64());

                Marshal.WriteByte(_fromPtr, 10, 0x41);
                Marshal.WriteByte(_fromPtr, 11, 0xff);
                Marshal.WriteByte(_fromPtr, 12, 0xe3);
            }
            else if (IntPtr.Size == 4)
            {
                // x86

                _originalPtrData = new byte[6];

                // 6
                Marshal.Copy(_fromPtr, _originalPtrData, 0, 6);

                Marshal.WriteByte(_fromPtr, 0, 0xe9);
                Marshal.WriteInt32(_fromPtr, 1, _toPtr.ToInt32() - _fromPtr.ToInt32() - 5);
                Marshal.WriteByte(_fromPtr, 5, 0xc3);
            }

            VirtualProtect(_fromPtr, (IntPtr)5, x, out x);
        }
Esempio n. 17
0
        public static long GetMethodStart(MethodBase method)
        {
            RuntimeMethodHandle handle = GetMethodHandle(method);

            /* Required to ensure that the method is already JITed and the method start doesn't change.
             * This seemingly only affects the .NET Framework.
             * - ade
             */
            RuntimeHelpers.PrepareMethod(handle);
            return(handle.GetFunctionPointer().ToInt64());
        }
Esempio n. 18
0
        /// <summary>
        /// Detours the original method to call the target method
        /// </summary>
        public void InitialiseDetour()
        {
            var originalMethodAddress = _originalMethodHandle.GetFunctionPointer();

            // Adjust the protection of the virtual memory region to ensure it has write privileges

            if (!Kernel32.VirtualProtect(originalMethodAddress, _detourBytes.Length, MemoryProtectionType.ReadWrite, out var oldProtection))
            {
                throw new PInvokeException("Failed to call VirtualProtect");
            }

            Marshal.Copy(_detourBytes, 0, originalMethodAddress, _detourBytes.Length);

            // Restore the original protection of the virtual memory region

            if (!Kernel32.VirtualProtect(originalMethodAddress, _detourBytes.Length, oldProtection, out _))
            {
                throw new PInvokeException("Failed to call VirtualProtect");
            }
        }
Esempio n. 19
0
        // 한 번만 한다
        static NativeThisPointer()
        {
            NativeThisPointer instance = new NativeThisPointer();
            Type me = instance.GetType();

            RuntimeMethodHandle handle = me.GetMethod(nameof(ReplacedTest), Helper.mflag1).MethodHandle;

            RuntimeHelpers.PrepareMethod(handle);
            Helper.ReplaceMethod(me.GetMethod(nameof(GetTest), Helper.mflag0), handle.GetFunctionPointer());

            instance.GetTest(magic, magic);
        }
Esempio n. 20
0
 public bool AddHook(MethodInfo handing)
 {
     if (handing == null)
     {
         return(false);
     }
     lock (this)
     {
         RuntimeMethodHandle handle = handing.MethodHandle;
         IntPtr address             = handle.GetFunctionPointer();
         return(AddHook(address));
     }
 }
Esempio n. 21
0
    public void ctor(ProcessManager manager, SlideShow.SlideShowID slideShowID)
    {
        Type[] constructorSignature = new Type[2];
        constructorSignature[0] = typeof(ProcessManager);
        constructorSignature[1] = typeof(ProcessManager.ProcessID);
        RuntimeMethodHandle handle = typeof(Menu.Menu).GetConstructor(constructorSignature).MethodHandle;

        RuntimeHelpers.PrepareMethod(handle);
        IntPtr ptr = handle.GetFunctionPointer();
        Action <ProcessManager, ProcessManager.ProcessID> funct = (Action <ProcessManager, ProcessManager.ProcessID>)Activator.CreateInstance(typeof(Action <ProcessManager, ProcessManager.ProcessID>), this, ptr);

        if (slideShowID != (SlideShow.SlideShowID)SlideShowID.WhiteOutro)
        {
            orig_ctor(manager, slideShowID);
        }
        else
        {
            this.current = -1;
            //Delegate to call the base constructor
            funct(manager, ProcessManager.ProcessID.SlideShow);//Menu Constructor

            this.slideShowID = (SlideShow.SlideShowID)slideShowID;
            this.pages.Add(new Page(this, null, "main", 0));
            this.playList = new List <SlideShow.Scene>();
            if (manager.musicPlayer != null)
            {
                this.waitForMusic = "RW_Outro_Theme";
                this.stall        = true;
                manager.musicPlayer.MenuRequestsSong(this.waitForMusic, 1.5f, 10f);
            }
            this.playList.Add(new SlideShow.Scene(MenuScene.SceneID.Empty, 0f, 0f, 0f));
            this.playList.Add(new SlideShow.Scene(MenuScene.SceneID.Outro_1_Left_Swim, this.ConvertTime(0, 1, 20), this.ConvertTime(0, 5, 0), this.ConvertTime(0, 17, 0)));
            this.playList.Add(new SlideShow.Scene(MenuScene.SceneID.Outro_2_Up_Swim, this.ConvertTime(0, 21, 0), this.ConvertTime(0, 25, 0), this.ConvertTime(0, 37, 0)));
            this.playList.Add(new SlideShow.Scene(MenuScene.SceneID.Empty, this.ConvertTime(1, 1, 0), this.ConvertTime(1, 1, 0), this.ConvertTime(1, 6, 0)));
            for (int j = 1; j < this.playList.Count; j++)
            {
                this.playList[j].startAt        -= 1.1f;
                this.playList[j].fadeInDoneAt   -= 1.1f;
                this.playList[j].fadeOutStartAt -= 1.1f;
            }
            this.nextProcess     = ProcessManager.ProcessID.Credits;
            this.preloadedScenes = new SlideShowMenuScene[this.playList.Count];
            for (int k = 0; k < this.preloadedScenes.Length; k++)
            {
                this.preloadedScenes[k] = new SlideShowMenuScene(this, this.pages[0], this.playList[k].sceneID);
                this.preloadedScenes[k].Hide();
            }
            manager.RemoveLoadingLabel();
            this.NextScene();
        }
    }
Esempio n. 22
0
        public override void Update()
        {
            if (this.menu is SleepAndDeathScreen)
            {
                orig_Update();
            }
            else
            {
                //Created Delegate to call base.Update
                Type[] constructorSignature = new Type[0];
                RuntimeMethodHandle handle  = typeof(Menu.PositionedMenuObject).GetMethod("Update").MethodHandle;
                RuntimeHelpers.PrepareMethod(handle);
                IntPtr ptr   = handle.GetFunctionPointer();
                Action funct = (Action)Activator.CreateInstance(typeof(Action), this, ptr);
                funct();                //PositionedMenuObject.Update

                this.lastBlackFade = this.blackFade;
                if (this.blackFade > 0f)
                {
                    this.blackFade = Mathf.Min(1f, this.blackFade + 0.025f);
                }
                if (this.addPassageButtonWhenTokenBecomesVisible)
                {
                    bool flag = true;
                    for (int i = 0; i < this.tokens.Count; i++)
                    {
                        if (this.tokens[i].endgameMeter.fullfilledNow && this.tokens[i].endgameMeter.showAsFullfilled < 0.9f)
                        {
                            flag = false;
                        }
                    }
                    if (flag)
                    {
                        (this.menu as MultiplayerSleepAndDeathScreen).AddPassageButton(true);
                        this.addPassageButtonWhenTokenBecomesVisible = false;
                    }
                }
                if (this.pingAchivements && this.AllAnimationsDone)
                {
                    this.pingAchivements = false;
                    for (int j = 0; j < (this.menu as MultiplayerSleepAndDeathScreen).winState.endgameTrackers.Count; j++)
                    {
                        if (!(this.menu as MultiplayerSleepAndDeathScreen).winState.endgameTrackers[j].GoalAlreadyFullfilled && (this.menu as MultiplayerSleepAndDeathScreen).winState.endgameTrackers[j].GoalFullfilled)
                        {
                            this.menu.manager.CueAchievement(WinState.PassageAchievementID((this.menu as MultiplayerSleepAndDeathScreen).winState.endgameTrackers[j].ID), 6f);
                        }
                    }
                }
            }
        }
Esempio n. 23
0
    public override void Update()
    {
        //Delegate to call the base Update
        Type[] updateSignature     = new Type[0];
        RuntimeMethodHandle handle = typeof(Menu.Menu).GetMethod("Update", updateSignature).MethodHandle;

        RuntimeHelpers.PrepareMethod(handle);
        IntPtr ptr   = handle.GetFunctionPointer();
        Action funct = (Action)Activator.CreateInstance(typeof(Action), this, ptr);

        funct();//Menu.Menu Update Method

        this.counter++;
        if (!this.initSound)
        {
            base.PlaySound(SoundID.MENU_Dream_Init);
            this.initSound = true;
        }
        if (this.counter > 35 && this.scene.sceneID == MenuScene.SceneID.SleepScreen && this.dreamID != null)
        {
            this.manager.fadeToBlack = Custom.LerpAndTick(this.manager.fadeToBlack, 1f, 0f, 1f / Mathf.Lerp(450f, 210f, this.manager.fadeToBlack));
            if (this.manager.fadeToBlack > 0.9f)
            {
                base.PlaySound(SoundID.MENU_Dream_Switch);
                this.manager.fadeToBlack = 1f;
                this.scene.RemoveSprites();
                this.pages[0].subObjects.Remove(this.scene);
                this.scene = new InteractiveMenuScene(this, this.pages[0], this.SceneFromDream(this.dreamID.Value));
                this.pages[0].subObjects.Add(this.scene);
                this.dreamID = null;
            }
        }
        else
        {
            this.manager.fadeToBlack = Custom.LerpAndTick(this.manager.fadeToBlack, 0f, 0f, 0.0125f);
            if (this.exitButton != null)
            {
                this.exitButton.buttonBehav.greyedOut = this.FreezeMenuFunctions;
                this.exitButton.black = Math.Max(0f, this.exitButton.black - 0.0125f);
            }
            else if (this.counter > endTime)
            {
                this.exitButton = new SimpleButton(this, this.pages[0], base.Translate("CONTINUE"), "CONTINUE", new Vector2(this.manager.rainWorld.options.ScreenSize.x - 320f + (1366f - this.manager.rainWorld.options.ScreenSize.x), 15f), new Vector2(110f, 30f));
                this.pages[0].subObjects.Add(this.exitButton);
                this.pages[0].lastSelectedObject = this.exitButton;
                this.exitButton.black            = 1f;
            }
        }
    }
Esempio n. 24
0
        private void PrepareDetour()
        {
            // Ensure both methods are JIT compiled

            RuntimeHelpers.PrepareMethod(_originalMethodHandle);

            RuntimeHelpers.PrepareMethod(_targetMethodHandle);

            _detourBytes = Assembler.AssembleJump(_targetMethodHandle.GetFunctionPointer());

            // Save the bytes of the original method

            _originalBytes = new byte[_detourBytes.Length];

            Marshal.Copy(_originalMethodHandle.GetFunctionPointer(), _originalBytes, 0, _detourBytes.Length);
        }
Esempio n. 25
0
        private void Redirect(NativeMethod from, RuntimeMethodHandle to)
        {
            RuntimeHelpers.PrepareMethod(to);


            var fromPtr = from.Address;
            var toPtr   = to.GetFunctionPointer();

            FromPtrData = new byte[32];
            Marshal.Copy(fromPtr, FromPtrData, 0, 32);

            VirtualProtect(fromPtr, (IntPtr)5, 0x40, out uint x);

            if (IntPtr.Size == 8)
            {
                // x64
                _originalPtrData = new byte[13];

                Marshal.Copy(fromPtr, _originalPtrData, 0, 13);

                Marshal.WriteByte(fromPtr, 0, 0x49);
                Marshal.WriteByte(fromPtr, 1, 0xbb);

                Marshal.WriteInt64(fromPtr, 2, toPtr.ToInt64());

                Marshal.WriteByte(fromPtr, 10, 0x41);
                Marshal.WriteByte(fromPtr, 11, 0xff);
                Marshal.WriteByte(fromPtr, 12, 0xe3);
            }
            else if (IntPtr.Size == 4)
            {
                // x86

                _originalPtrData = new byte[6];

                Marshal.Copy(fromPtr, _originalPtrData, 0, 6);

                Marshal.WriteByte(fromPtr, 0, 0xe9);
                Marshal.WriteInt32(fromPtr, 1, toPtr.ToInt32() - fromPtr.ToInt32() - 5);
                Marshal.WriteByte(fromPtr, 5, 0xc3);
            }

            VirtualProtect(fromPtr, (IntPtr)5, x, out x);
        }
Esempio n. 26
0
        private static IntPtr GetDynamicMethodAddress(MethodBase method)
        {
            unsafe
            {
                RuntimeMethodHandle handle = GetDynamicMethodRuntimeHandle(method);
                byte *ptr = (byte *)handle.Value.ToPointer();

                if (IsNet20Sp2OrGreater())
                {
                    RuntimeHelpers.PrepareMethod(handle);
                    return(handle.GetFunctionPointer());

                    //if (IntPtr.Size == 8)
                    //{
                    //    ulong* address = (ulong*)ptr;
                    //    address = (ulong*)*(address + 5);
                    //    return new IntPtr(address + 12);
                    //}
                    //else
                    //{
                    //    uint* address = (uint*)ptr;
                    //    address = (uint*)*(address + 5);
                    //    return new IntPtr(address + 12);
                    //}
                }
                else
                {
                    if (IntPtr.Size == 8)
                    {
                        ulong *address = (ulong *)ptr;
                        address += 6;
                        return(new IntPtr(address));
                    }
                    else
                    {
                        uint *address = (uint *)ptr;
                        address += 6;
                        return(new IntPtr(address));
                    }
                }
            }
        }
Esempio n. 27
0
        /// <summary>
        /// Creates a delegate of the specified type with the specified target from this method.
        /// </summary>
        /// <param name="method">The method to create the delegate from.</param>
        /// <param name="delegateType">The type of the delegate to create.</param>
        /// <param name="target">The object targeted by the delegate.</param>
        /// <returns>The delegate for this method.</returns>
        public static Delegate CreateDelegate(this MethodBase method, Type delegateType, object target)
        {
            if (!typeof(Delegate).IsAssignableFrom(delegateType))
            {
                throw new ArgumentException("Type argument must be a delegate type!");
            }
            if (method is DynamicMethod)
            {
                return(((DynamicMethod)method).CreateDelegate(delegateType, target));
            }

            // TODO: Check delegate Invoke parameters against method parameters.

            RuntimeMethodHandle handle = method.MethodHandle;

            RuntimeHelpers.PrepareMethod(handle);
            IntPtr ptr = handle.GetFunctionPointer();

            return((Delegate)Activator.CreateInstance(delegateType, target, ptr));
        }
Esempio n. 28
0
        private static void MethodResolver(MethodContext context)
        {
            if (context.Method == Utils.GetMethod <DetourMethodAddress>(nameof(Sum)))
            {
                MethodInfo          mulMethod = Utils.GetMethod <DetourMethodAddress>(nameof(Mul));
                RuntimeMethodHandle handle    = mulMethod.MethodHandle;

                RuntimeHelpers.PrepareMethod(handle);

                IntPtr methodPointer = handle.GetFunctionPointer();

                byte jmp = Marshal.ReadByte(methodPointer);

                if (jmp == 0xE9)
                {
                    int jmpSize = Marshal.ReadInt32(methodPointer + 1);
                    methodPointer = new IntPtr(methodPointer.ToInt64() + jmpSize + 5);
                }

                context.ResolveDetour(methodPointer);
            }
        }
Esempio n. 29
0
        /// <summary>
        /// Creates a delegate of the specified type with the specified target from this method.
        /// </summary>
        /// <param name="method">The method to create the delegate from.</param>
        /// <param name="delegateType">The type of the delegate to create.</param>
        /// <param name="target">The object targeted by the delegate.</param>
        /// <returns>The delegate for this method.</returns>
        public static Delegate CreateDelegate(this MethodBase method, Type delegateType, object target)
        {
            if (!typeof(Delegate).IsAssignableFrom(delegateType))
            {
                throw new ArgumentException("Type argument must be a delegate type!");
            }
            if (method is System.Reflection.Emit.DynamicMethod dm)
            {
                return(dm.CreateDelegate(delegateType, target));
            }

#if NETSTANDARD
            // Built-in CreateDelegate is available in .NET Standard
            if (method is System.Reflection.MethodInfo mi)
            {
                return(mi.CreateDelegate(delegateType, target));
            }
#endif

            RuntimeMethodHandle handle = method.MethodHandle;
            RuntimeHelpers.PrepareMethod(handle);
            IntPtr ptr = handle.GetFunctionPointer();
            return((Delegate)Activator.CreateInstance(delegateType, target, ptr));
        }
Esempio n. 30
0
 public _FuncPtr32(RuntimeMethodHandle _method_info_native)
 {
     CTOR((void *)_method_info_native.GetFunctionPointer(), 0);
 }