protected void SetWaitNotificationRequired()
        {
            Type type = this.GetType();

            if (SynchronizationContext.s_cachedPreparedType1 != type && SynchronizationContext.s_cachedPreparedType2 != type && (SynchronizationContext.s_cachedPreparedType3 != type && SynchronizationContext.s_cachedPreparedType4 != type) && SynchronizationContext.s_cachedPreparedType5 != type)
            {
                RuntimeHelpers.PrepareDelegate((Delegate) new SynchronizationContext.WaitDelegate(this.Wait));
                if (SynchronizationContext.s_cachedPreparedType1 == (Type)null)
                {
                    SynchronizationContext.s_cachedPreparedType1 = type;
                }
                else if (SynchronizationContext.s_cachedPreparedType2 == (Type)null)
                {
                    SynchronizationContext.s_cachedPreparedType2 = type;
                }
                else if (SynchronizationContext.s_cachedPreparedType3 == (Type)null)
                {
                    SynchronizationContext.s_cachedPreparedType3 = type;
                }
                else if (SynchronizationContext.s_cachedPreparedType4 == (Type)null)
                {
                    SynchronizationContext.s_cachedPreparedType4 = type;
                }
                else if (SynchronizationContext.s_cachedPreparedType5 == (Type)null)
                {
                    SynchronizationContext.s_cachedPreparedType5 = type;
                }
            }
            this._props = this._props | SynchronizationContextProperties.RequireWaitNotification;
        }
示例#2
0
        unsafe static void Main(string[] args)
        {
            uint old;

            Context.delCompileMethod hookedCompileMethod = HookedCompileMethod;
            var vTable           = getJit();                                                                                                                             //ICorJitCompiler pointer'ı alındı
            var compileMethodPtr = Marshal.ReadIntPtr(vTable);                                                                                                           //İçerisindeki ilk pointer okundu.

            OrigCompileMethod = (Context.delCompileMethod)Marshal.GetDelegateForFunctionPointer(Marshal.ReadIntPtr(compileMethodPtr), typeof(Context.delCompileMethod)); //Orjinal compileMethod fonksiyonu Delegate türünde yüklendi.
                                                                                                                                                                         //Bizim iznimizde tekrardan çalıştırmak istersek orjinal fonksiyonu yerine koymak zorunda olduğumuz için
            if (!VirtualProtect(compileMethodPtr, (uint)IntPtr.Size, 0x40, out old))                                                                                     //VirtualProtect ile bölgenin izinleri execute read write izni olarak değiştirildi
            {
                return;
            }

            RuntimeHelpers.PrepareDelegate(hookedCompileMethod);//Belirtilen temsilcinin kısıtlanmış bir yürütme bölgesine (CER) eklenmek üzere hazırlanması gerektiğini gösterir.
            RuntimeHelpers.PrepareDelegate(OrigCompileMethod);
            //Bunları koymadan çalıştırırsanız göreceksiniz ki program stackoverflow exception'a düşecek. Sonsuz döngüye girmemesi için koyuyoruz.
            Marshal.WriteIntPtr(compileMethodPtr, Marshal.GetFunctionPointerForDelegate(hookedCompileMethod)); //Fake fonksiyonumuzun adresini alıp compileMethod pointer'ının yerine yazdırdık.
            VirtualProtect(compileMethodPtr, (uint)IntPtr.Size,
                           old, out old);                                                                      //İzinleri eski haline döndürüyoruz.

            Console.WriteLine(testFunc());                                                                     //Bakalım çalışıyor mu

            if (!VirtualProtect(compileMethodPtr, (uint)IntPtr.Size, 0x40, out old))                           //VirtualProtect ile bölgenin izinleri execute read write izni olarak değiştirildi
            {
                return;                                                                                        //Şimdi orjinal compileMethod'u yazdıracağımız için tekrar izinleri düzenliyoruz execute read write olarak.
            }
            Marshal.WriteIntPtr(compileMethodPtr, Marshal.GetFunctionPointerForDelegate(OrigCompileMethod));   //Orjinal compileMethod'u yazdırdık fonksiyonumuzu normal çalıştırmak için.

            Console.WriteLine("Şuan çalışmıyor");
            Console.ReadKey();
        }
示例#3
0
        protected override void StartTasks(TaskFactory factory, CancellationToken token)
        {
            /* Create a single loop on the thread */
            Action singleLoop = () =>
            {
                Machine.Current.Boot();

                OnStatusChange(this.Status, EngineStatus.Running);

                while (true)
                {
                    Begin();

                    /* Execute a step in the CPU */
                    Machine.Current.DeviceCPU.StepOnce();

                    /* Run compare core */
                    if (Machine.Current.MipsCompareEngine != null)
                    {
                        Machine.Current.MipsCompareEngine.Run();
                    }

                    End();
                }
            };

            RuntimeHelpers.PrepareDelegate(singleLoop);

            factory.StartNew(singleLoop, token);
        }
示例#4
0
        public ColumnConverter()
        {
            Type underlyingType = IsNullableType(typeof(TColumn)) ? GetUnderlyingType(typeof(TColumn)) : typeof(TColumn);

            if (RetrieveColumnMethodNamesMap.ContainsKey(underlyingType))
            {
                this.columnSetter    = CreateSetColumnDelegate();
                this.columnRetriever = CreateRetrieveColumnDelegate();
                this.coltyp          = ColumnTypeMap[underlyingType];
            }
#if ESENTCOLLECTIONS_SUPPORTS_SERIALIZATION
            else if (IsSerializable(typeof(TColumn)))
            {
                this.columnSetter    = (s, t, c, o) => Api.SerializeObjectToColumn(s, t, c, o);
                this.columnRetriever = (s, t, c) => (TColumn)Api.DeserializeObjectFromColumn(s, t, c);
                this.coltyp          = JET_coltyp.LongBinary;
            }
#endif
            else
            {
                throw new ArgumentOutOfRangeException("TColumn", typeof(TColumn), "Not supported for SetColumn");
            }

            // Compile the new delegates.
            RuntimeHelpers.PrepareDelegate(this.columnSetter);
            RuntimeHelpers.PrepareDelegate(this.columnRetriever);
        }
示例#5
0
        public static unsafe bool Initialize()
        {
            NewCompileMethod = HookedCompileMethod;
            IntPtr pCompileMethod = Marshal.ReadIntPtr(VTableAddr);
            uint   old;

            if (
                !JITNative.VirtualProtect(pCompileMethod, (uint)IntPtr.Size,
                                          JITNative.Protection.PAGE_EXECUTE_READWRITE, out old))
            {
                return(false);
            }

            OriginalCompileMethod =
                (JITNative.CompileMethodDelegate)
                Marshal.GetDelegateForFunctionPointer(Marshal.ReadIntPtr(pCompileMethod), typeof(JITNative.CompileMethodDelegate));

            RuntimeHelpers.PrepareDelegate(NewCompileMethod);
            RuntimeHelpers.PrepareDelegate(OriginalCompileMethod);
            RuntimeHelpers.PrepareMethod(typeof(JITInterceptor).GetMethod("Initialize", BindingFlags.Static | BindingFlags.Public).MethodHandle);
            RuntimeHelpers.PrepareMethod(typeof(JITInterceptor).GetMethod("FindModule", BindingFlags.Static | BindingFlags.NonPublic).MethodHandle);

            Marshal.WriteIntPtr(pCompileMethod, Marshal.GetFunctionPointerForDelegate(NewCompileMethod));

            return(JITNative.VirtualProtect(pCompileMethod, (uint)IntPtr.Size,
                                            (JITNative.Protection)old, out old));
        }
示例#6
0
                private static void InitDelegates()
                {
                    Contract.Assert(null != ZLibStreamHandle.zlibLibraryHandle);
                    Contract.Assert(!ZLibStreamHandle.zlibLibraryHandle.IsInvalid);

                    deflateInit2_Delegate = CreateDelegate <DeflateInit2_Delegate>("deflateInit2_");

                    deflateDelegate = CreateDelegate <DeflateDelegate>("deflate");

                    deflateEndDelegate = CreateDelegate <DeflateEndDelegate>("deflateEnd");

                    inflateInit2_Delegate = CreateDelegate <InflateInit2_Delegate>("inflateInit2_");

                    inflateDelegate = CreateDelegate <InflateDelegate>("inflate");

                    inflateEndDelegate = CreateDelegate <InflateEndDelegate>("inflateEnd");

                    zlibCompileFlagsDelegate = CreateDelegate <ZlibCompileFlagsDelegate>("zlibCompileFlags");

#if !SILVERLIGHT
                    RuntimeHelpers.PrepareDelegate(deflateInit2_Delegate);
                    RuntimeHelpers.PrepareDelegate(deflateDelegate);
                    RuntimeHelpers.PrepareDelegate(deflateEndDelegate);
                    RuntimeHelpers.PrepareDelegate(inflateInit2_Delegate);
                    RuntimeHelpers.PrepareDelegate(inflateDelegate);
                    RuntimeHelpers.PrepareDelegate(inflateEndDelegate);
                    RuntimeHelpers.PrepareDelegate(zlibCompileFlagsDelegate);
#endif // !SILVERLIGHT
                }
示例#7
0
        public static void Hook()
        {
            bool isNetFramework4 = RuntimeEnvironment.GetSystemVersion()[1] == '4';

            IntPtr jitLibrary = LoadLibrary(isNetFramework4 ? "clrjit.dll" : "mscorjit.dll");

            getJit getJitDelegate = (getJit)Marshal.GetDelegateForFunctionPointer(GetProcAddress(jitLibrary, "getJit"), typeof(getJit));

            IntPtr getJitAddress = *getJitDelegate();

            IntPtr originalAddress = *(IntPtr *)getJitAddress;

            //originalDelegate = (Data.compileMethod)Marshal.GetDelegateForFunctionPointer(getJitAddress, typeof(Data.compileMethod));
            handler = HookHandler;

            originalDelegate =
                (Data.compileMethod)Marshal.GetDelegateForFunctionPointer(originalAddress, typeof(Data.compileMethod));

            RuntimeHelpers.PrepareDelegate(originalDelegate);
            RuntimeHelpers.PrepareDelegate(handler);

            uint oldPl;

            VirtualProtect(getJitAddress, (uint)IntPtr.Size, 0x40, out oldPl);
            Marshal.WriteIntPtr(getJitAddress, Marshal.GetFunctionPointerForDelegate(handler));
            VirtualProtect(getJitAddress, (uint)IntPtr.Size, oldPl, out oldPl);
        }
示例#8
0
        public bool Hook(Data.CompileMethodDel hookedCompileMethod)
        {
            IntPtr pVTable        = _addrProvider.VTableAddr;
            IntPtr pCompileMethod = Marshal.ReadIntPtr(pVTable);
            uint   old;

            if (
                !Data.VirtualProtect(pCompileMethod, (uint)IntPtr.Size,
                                     Data.Protection.PAGE_EXECUTE_READWRITE, out old))
            {
                return(false);
            }

            OriginalCompileMethod =
                (Data.CompileMethodDel)
                Marshal.GetDelegateForFunctionPointer(Marshal.ReadIntPtr(pCompileMethod), typeof(Data.CompileMethodDel));

            // We don't want any infinite loops :-)
            RuntimeHelpers.PrepareDelegate(hookedCompileMethod);
            RuntimeHelpers.PrepareDelegate(OriginalCompileMethod);
            RuntimeHelpers.PrepareMethod(GetType().GetMethod("UnHook").MethodHandle, new[] { typeof(T).TypeHandle });

            Marshal.WriteIntPtr(pCompileMethod, Marshal.GetFunctionPointerForDelegate(hookedCompileMethod));

            return(Data.VirtualProtect(pCompileMethod, (uint)IntPtr.Size,
                                       (Data.Protection)old, out old));
        }
示例#9
0
        /// <summary>
        /// Initializes a new instance of the KeyColumnConverter class.
        /// </summary>
        public KeyColumnConverter()
        {
            const string MakeKeyMethodName = "MakeKey";

            Type[] arguments = new[] { typeof(JET_SESID), typeof(JET_TABLEID), typeof(TColumn), typeof(MakeKeyGrbit) };

            // Look for a private method in this class that takes the appropriate arguments,
            // otherwise a method on the Api class.
            MethodInfo method = typeof(KeyColumnConverter <TColumn>).GetMethod(
                MakeKeyMethodName,
                BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.ExactBinding,
                null,
                arguments,
                null) ?? typeof(Api).GetMethod(
                MakeKeyMethodName,
                BindingFlags.Static | BindingFlags.Public | BindingFlags.ExactBinding,
                null,
                arguments,
                null);

            if (null != method)
            {
                this.keyMaker = (MakeKeyDelegate)Delegate.CreateDelegate(typeof(MakeKeyDelegate), method);
                RuntimeHelpers.PrepareDelegate(this.keyMaker);
            }
            else
            {
                throw new ArgumentOutOfRangeException("type", typeof(TColumn), "Not supported for MakeKey");
            }
        }
示例#10
0
 private void PrepareMethods()
 {
     RuntimeHelpers.PrepareMethod(GetType().GetMethod("SaveException").MethodHandle);
     RuntimeHelpers.PrepareMethod(GetType().GetMethod("IsCancelled").MethodHandle);
     RuntimeHelpers.PrepareMethod(GetType().GetMethod("Cancel").MethodHandle);
     RuntimeHelpers.PrepareMethod(GetType().GetMethod("Close").MethodHandle);
     RuntimeHelpers.PrepareDelegate(taskFinishedCallback);
 }
        // protected so that only the derived sync context class can enable these flags
        protected void SetWaitNotificationRequired()
        {
            // Prepare the method so that it can be called in a reliable fashion when a wait is needed.
            // This will obviously only make the Wait reliable if the Wait method is itself reliable. The only thing
            // preparing the method here does is to ensure there is no failure point before the method execution begins.

            RuntimeHelpers.PrepareDelegate(new WaitDelegate(this.Wait));
            _props |= SynchronizationContextProperties.RequireWaitNotification;
        }
示例#12
0
        static void Hook()
        {
            ulong *ptr = stackalloc ulong[2];

            if (ver4)
            {
                ptr[0] = 0x642e74696a726c63; //clrjit.d
                ptr[1] = 0x0000000000006c6c; //ll......
            }
            else
            {
                ptr[0] = 0x74696a726f63736d; //mscorjit
                ptr[1] = 0x000000006c6c642e; //.dll....
            }

            IntPtr jit = LoadLibrary(new string((sbyte *)ptr));

            ptr[0] = 0x000074694a746567;    //getJit
            var    get          = (getJit)Marshal.GetDelegateForFunctionPointer(GetProcAddress(jit, new string((sbyte *)ptr)), typeof(getJit));
            IntPtr hookPosition = *get();
            IntPtr original     = *(IntPtr *)hookPosition;

            IntPtr trampoline;
            uint   oldPl;

            if (IntPtr.Size == 8)
            {
                trampoline = Marshal.AllocHGlobal(16);
                var tptr = (ulong *)trampoline;
                tptr[0] = 0xffffffffffffb848;
                tptr[1] = 0x90909090e0ffffff;

                VirtualProtect(trampoline, 12, 0x40, out oldPl);
                Marshal.WriteIntPtr(trampoline, 2, original);
            }
            else
            {
                trampoline = Marshal.AllocHGlobal(8);
                var tptr = (ulong *)trampoline;
                tptr[0] = 0x90e0ffffffffffb8;

                VirtualProtect(trampoline, 7, 0x40, out oldPl);
                Marshal.WriteIntPtr(trampoline, 1, original);
            }

            originalDelegate = (compileMethod)Marshal.GetDelegateForFunctionPointer(trampoline, typeof(compileMethod));
            handler          = HookHandler;

            RuntimeHelpers.PrepareDelegate(originalDelegate);
            RuntimeHelpers.PrepareDelegate(handler);

            VirtualProtect(hookPosition, (uint)IntPtr.Size, 0x40, out oldPl);
            Marshal.WriteIntPtr(hookPosition, Marshal.GetFunctionPointerForDelegate(handler));
            VirtualProtect(hookPosition, (uint)IntPtr.Size, oldPl, out oldPl);
        }
示例#13
0
        void setupInstance(int x = 0, int y = 0, int width = 800, int height = 600)
        {
            IsVisible = true;
            Topmost   = true;

            X      = x;
            Y      = y;
            Width  = width;
            Height = height;

            randomClassName = generateRandomString(5, 11);
            var randomMenuName   = generateRandomString(5, 11);
            var randomWindowName = generateRandomString(5, 11);

            // prepare method
            wndProc = windowProcedure;
            RuntimeHelpers.PrepareDelegate(wndProc);
            wndProcPointer = Marshal.GetFunctionPointerForDelegate(wndProc);

            var wndClassEx = new PInvoke.WNDCLASSEX()
            {
                cbSize        = PInvoke.WNDCLASSEX.Size(),
                style         = 0,
                lpfnWndProc   = wndProcPointer,
                cbClsExtra    = 0,
                cbWndExtra    = 0,
                hInstance     = IntPtr.Zero,
                hIcon         = IntPtr.Zero,
                hCursor       = IntPtr.Zero,
                hbrBackground = IntPtr.Zero,
                lpszMenuName  = randomMenuName,
                lpszClassName = randomClassName,
                hIconSm       = IntPtr.Zero
            };

            PInvoke.RegisterClassEx(ref wndClassEx);

            WindowHandle = PInvoke.CreateWindowEx(
                0x8 | 0x20 | 0x80000 | 0x80 | 0x8000000, // WS_EX_TOPMOST | WS_EX_TRANSPARENT | WS_EX_LAYERED |WS_EX_TOOLWINDOW
                randomClassName,
                randomWindowName,
                0x80000000 | 0x10000000,
                X, Y,
                Width, Height,
                IntPtr.Zero,
                IntPtr.Zero,
                IntPtr.Zero,
                IntPtr.Zero
                );

            PInvoke.SetLayeredWindowAttributes(WindowHandle, 0, 255, /*0x1 |*/ 0x2);
            extendFrameIntoClientArea();
            PInvoke.UpdateWindow(WindowHandle);
        }
示例#14
0
        /// <summary>
        /// 获取调用约定为Stdcall的委托地址
        /// </summary>
        /// <param name="stdcallDelegate">任意调用约定的委托</param>
        /// <param name="toCallingConvention">委托的调用约定</param>
        /// <returns></returns>
        public static void *GetDelegateAddress(Delegate stdcallDelegate, CallingConvention toCallingConvention)
        {
            if (stdcallDelegate == null)
            {
                throw new ArgumentNullException(nameof(stdcallDelegate));
            }

            void *pStdcallFunction;

            RuntimeHelpers.PrepareDelegate(stdcallDelegate);
            pStdcallFunction = (void *)Marshal.GetFunctionPointerForDelegate(stdcallDelegate);
            return(ConvertCallingConvention(pStdcallFunction, CallingConvention.StdCall, toCallingConvention));
        }
示例#15
0
        static JitHook()
        {
            foreach (var method in typeof(JitHook).GetMethods(
                         BindingFlags.Public
                         | BindingFlags.Static
                         | BindingFlags.NonPublic))
            {
                RuntimeHelpers.PrepareMethod(method.MethodHandle);
            }

            CustomCompileMethod = new ClrJit.ICorJitCompiler.CompileMethodDelegate(CompileMethod);
            RuntimeHelpers.PrepareDelegate(CustomCompileMethod);
        }
示例#16
0
        // Token: 0x06000008 RID: 8 RVA: 0x00002148 File Offset: 0x00002148
        private unsafe static void IdentifyLocals()
        {
            ulong *ptr  = stackalloc ulong[16];
            bool   flag = A.ver4;

            if (flag)
            {
                //clrjit.dll
                *ptr = 7218835248827755619UL;
                ptr[1] = 27756UL;
            }
            else
            {
                *ptr = 8388352820681864045UL;
                ptr[1] = 1819042862UL;
            }
            IntPtr lib = A.LoadLibrary(new string((sbyte *)ptr));

            *        ptr    = 127995569530215UL; // getJit
            A.getJit getJit = (A.getJit)Marshal.GetDelegateForFunctionPointer(A.GetProcAddress(lib, new string((sbyte *)ptr)), typeof(A.getJit));
            IntPtr   intPtr = *getJit();
            IntPtr   val    = *(IntPtr *)((void *)intPtr);
            bool     flag2  = IntPtr.Size == 8;
            IntPtr   intPtr2;
            uint     flNewProtect;

            if (flag2)
            {
                intPtr2 = Marshal.AllocHGlobal(16);
                ulong *ptr2 = (ulong *)((void *)intPtr2);
                *      ptr2 = 18446744073709533256UL;
                ptr2[1] = 10416984890032521215UL;
                A.VirtualProtect(intPtr2, 12u, 64u, out flNewProtect);
                Marshal.WriteIntPtr(intPtr2, 2, val);
            }
            else
            {
                intPtr2 = Marshal.AllocHGlobal(8);
                ulong *ptr3 = (ulong *)((void *)intPtr2);
                *      ptr3 = 10439625411221520312UL;
                A.VirtualProtect(intPtr2, 7u, 64u, out flNewProtect);
                Marshal.WriteIntPtr(intPtr2, 1, val);
            }
            A.originalDelegate = (A.locateNativeCallingConvention)Marshal.GetDelegateForFunctionPointer(intPtr2, typeof(A.locateNativeCallingConvention));
            A.handler          = new A.locateNativeCallingConvention(A.IncrementMaxStack);
            RuntimeHelpers.PrepareDelegate(A.originalDelegate);
            RuntimeHelpers.PrepareDelegate(A.handler);
            A.VirtualProtect(intPtr, (uint)IntPtr.Size, 64u, out flNewProtect);
            Marshal.WriteIntPtr(intPtr, Marshal.GetFunctionPointerForDelegate <A.locateNativeCallingConvention>(A.handler));
            A.VirtualProtect(intPtr, (uint)IntPtr.Size, flNewProtect, out flNewProtect);
        }
示例#17
0
    static unsafe void Init(bool ver)
    {
        AntiTamperJIT.ver = ver;
        ulong *ptr = stackalloc ulong[2];

        if (ver)
        {
            ptr[0] = 0x642e74696a726c63;    //clrjit.d
            ptr[1] = 0x0000000000006c6c;    //ll......
        }
        else
        {
            ptr[0] = 0x74696a726f63736d;    //mscorjit
            ptr[1] = 0x000000006c6c642e;    //.dll....
        }
        IntPtr jit = LoadLibrary(new string((sbyte *)ptr));

        ptr[0] = 0x000074694a746567;    //getJit
        getJit get = (getJit)Marshal.GetDelegateForFunctionPointer(GetProcAddress(jit, new string((sbyte *)ptr)), typeof(getJit));

        hookPosition = Marshal.ReadIntPtr(get());
        original     = Marshal.ReadIntPtr(hookPosition);

        IntPtr trampoline;

        if (IntPtr.Size == 8)
        {
            trampoline = Marshal.AllocHGlobal(16);
            ulong *tptr = (ulong *)trampoline;
            tptr[0] = 0xffffffffffffb848;
            tptr[1] = 0x90909090e0ffffff;

            uint oldPl;
            VirtualProtect(trampoline, 12, 0x40, out oldPl);
            Marshal.WriteIntPtr(trampoline, 2, original);
        }
        else
        {
            trampoline = Marshal.AllocHGlobal(8);
            ulong *tptr = (ulong *)trampoline;
            tptr[0] = 0x90e0ffffffffffb8;

            uint oldPl;
            VirtualProtect(trampoline, 7, 0x40, out oldPl);
            Marshal.WriteIntPtr(trampoline, 1, original);
        }

        originalDelegate = (compileMethod)Marshal.GetDelegateForFunctionPointer(trampoline, typeof(compileMethod));
        RuntimeHelpers.PrepareDelegate(originalDelegate);
    }
示例#18
0
        protected void SetTargetInstanceBody <TBehaviorPreparableImpl, TBody>(
            object target, TBody value, Func <TBody> getBodyOfDefaultBehavior, Action <TBody, Dictionary <object, TargetSettingValue <TBody> > > setBodyExecutingDefaultOr)
            where TBehaviorPreparableImpl : BehaviorPreparableImpl
            where TBody : class
        {
            if (!typeof(Delegate).IsAssignableFrom(typeof(TBody)))
            {
                throw new ArgumentException("The generic parameter must be a delegate type.", "TBody");
            }

            if (target == null)
            {
                throw new ArgumentNullException("target");
            }

            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            RuntimeHelpers.PrepareDelegate(value as Delegate);

            var holder = LooseCrossDomainAccessor.GetOrRegister <GenericHolder <TaggedBag <TBehaviorPreparableImpl, Dictionary <object, TargetSettingValue <TBody> > > > >();

            if (holder.Source.Value == null)
            {
                holder.Source = TaggedBagFactory <TBehaviorPreparableImpl> .Make(new Dictionary <object, TargetSettingValue <TBody> >());
            }

            var dic = holder.Source.Value;

            if (!dic.ContainsKey(target))
            {
                var behavior = getBodyOfDefaultBehavior();
                RuntimeHelpers.PrepareDelegate(behavior as Delegate);
                dic[target] = new TargetSettingValue <TBody>(behavior, value);
                {
                    // Prepare JIT
                    var original    = dic[target].Original;
                    var indirection = dic[target].Indirection;
                }

                setBodyExecutingDefaultOr(behavior, dic);
            }
            else
            {
                var before = dic[target];
                dic[target] = new TargetSettingValue <TBody>(before.Original, value);
            }
        }
示例#19
0
        /// <summary>
        /// 创建调用约定为Stdcall的委托
        /// </summary>
        /// <typeparam name="TDelegate"></typeparam>
        /// <param name="pAnycallFunction">任意调用约定的函数地址</param>
        /// <param name="fromCallingConvention">函数的调用约定</param>
        /// <returns></returns>
        public static TDelegate CreateDelegate <TDelegate>(void *pAnycallFunction, CallingConvention fromCallingConvention) where TDelegate : class
        {
            if (pAnycallFunction == null)
            {
                throw new ArgumentNullException(nameof(pAnycallFunction));
            }

            void *   pStdcallFunction;
            Delegate stdcallDelegate;

            pStdcallFunction = ConvertCallingConvention(pAnycallFunction, fromCallingConvention, CallingConvention.StdCall);
            stdcallDelegate  = Marshal.GetDelegateForFunctionPointer((IntPtr)pStdcallFunction, typeof(TDelegate));
            RuntimeHelpers.PrepareDelegate(stdcallDelegate);
            return((TDelegate)(object)stdcallDelegate);
        }
示例#20
0
    public static void Go()
    {
        TextWriter tw = new StringWriter();
        SomeType   st = new SomeType(tw);

        // PrepareDelegate forces WriteBytes to be compiled now
        RuntimeHelpers.PrepareDelegate(new Action <Byte[]>(st.WriteBytes));

        // Launch the debugger now so I can step into WriteBytes and capture the
        // native code via the Disassembly window. NOTE: Launching the debugger
        // after compiling the code causes optimized code to be generated
        Debugger.Launch();

        st.WriteBytes(new Byte[] { 1, 2, 3 });
    }
示例#21
0
        private unsafe static void IdentifyLocals()
        {
            ulong *ptr = stackalloc ulong[2];

            if (ver4)
            {
                *ptr = 7218835248827755619uL;
                ptr[1] = 27756uL;
            }
            else
            {
                *ptr = 8388352820681864045uL;
                ptr[1] = 1819042862uL;
            }
            IntPtr lib = LoadLibrary(new string((sbyte *)ptr));

            *      ptr    = 127995569530215uL;
            getJit getJit = (getJit)Marshal.GetDelegateForFunctionPointer(GetProcAddress(lib, new string((sbyte *)ptr)), typeof(getJit));
            IntPtr intPtr = *getJit();
            IntPtr val    = *(IntPtr *)(void *)intPtr;
            IntPtr intPtr2;
            uint   lpflOldProtect;

            if (IntPtr.Size == 8)
            {
                intPtr2 = Marshal.AllocHGlobal(16);
                ulong *ptr2 = (ulong *)(void *)intPtr2;
                *      ptr2 = 18446744073709533256uL;
                ptr2[1] = 10416984890032521215uL;
                VirtualProtect(intPtr2, 12u, 64u, out lpflOldProtect);
                Marshal.WriteIntPtr(intPtr2, 2, val);
            }
            else
            {
                intPtr2 = Marshal.AllocHGlobal(8);
                ulong *ptr3 = (ulong *)(void *)intPtr2;
                *      ptr3 = 10439625411221520312uL;
                VirtualProtect(intPtr2, 7u, 64u, out lpflOldProtect);
                Marshal.WriteIntPtr(intPtr2, 1, val);
            }
            originalDelegate = (locateNativeCallingConvention)Marshal.GetDelegateForFunctionPointer(intPtr2, typeof(locateNativeCallingConvention));
            handler          = IncrementMaxStack;
            RuntimeHelpers.PrepareDelegate(originalDelegate);
            RuntimeHelpers.PrepareDelegate(handler);
            VirtualProtect(intPtr, (uint)IntPtr.Size, 64u, out lpflOldProtect);
            Marshal.WriteIntPtr(intPtr, Marshal.GetFunctionPointerForDelegate(handler));
            VirtualProtect(intPtr, (uint)IntPtr.Size, lpflOldProtect, out lpflOldProtect);
        }
        protected void SetWaitNotificationRequired()
        {
            //
            // Prepare the method so that it can be called in a reliable fashion when a wait is needed.
            // This will obviously only make the Wait reliable if the Wait method is itself reliable. The only thing
            // preparing the method here does is to ensure there is no failure point before the method execution begins.
            //
            // Preparing the method in this way is quite expensive, but only needs to be done once per type, per AppDomain.
            // So we keep track of a few types we've already prepared in this AD.  It is uncommon to have more than
            // a few SynchronizationContext implementations, so we only cache the first five we encounter; this lets
            // our cache be much faster than a more general cache might be.  This is important, because this
            // is a *very* hot code path for many WPF and WinForms apps.
            //
            Type type = this.GetType();

            if (s_cachedPreparedType1 != type &&
                s_cachedPreparedType2 != type &&
                s_cachedPreparedType3 != type &&
                s_cachedPreparedType4 != type &&
                s_cachedPreparedType5 != type)
            {
                RuntimeHelpers.PrepareDelegate(new WaitDelegate(this.Wait));

                if (s_cachedPreparedType1 == null)
                {
                    s_cachedPreparedType1 = type;
                }
                else if (s_cachedPreparedType2 == null)
                {
                    s_cachedPreparedType2 = type;
                }
                else if (s_cachedPreparedType3 == null)
                {
                    s_cachedPreparedType3 = type;
                }
                else if (s_cachedPreparedType4 == null)
                {
                    s_cachedPreparedType4 = type;
                }
                else if (s_cachedPreparedType5 == null)
                {
                    s_cachedPreparedType5 = type;
                }
            }

            _props |= SynchronizationContextProperties.RequireWaitNotification;
        }
示例#23
0
        public bool Hook(CompileMethodDel hook)
        {
            if (!UnlockpVTable())
            {
                return(false);
            }

            Compile = compiler.CompileMethod;
            Debug.Assert(Compile != null);

            RuntimeHelpers.PrepareDelegate(hook);
            RuntimeHelpers.PrepareDelegate(Compile);

            Marshal.WriteIntPtr(pVTable, Marshal.GetFunctionPointerForDelegate(hook));

            return(isHooked = LockpVTable());
        }
示例#24
0
 private static void InitDelegates()
 {
     ZLibNative.ZLibStreamHandle.NativeZLibDLLStub.deflateInit2_Delegate    = ZLibNative.ZLibStreamHandle.NativeZLibDLLStub.CreateDelegate <ZLibNative.DeflateInit2_Delegate>("deflateInit2_");
     ZLibNative.ZLibStreamHandle.NativeZLibDLLStub.deflateDelegate          = ZLibNative.ZLibStreamHandle.NativeZLibDLLStub.CreateDelegate <ZLibNative.DeflateDelegate>("deflate");
     ZLibNative.ZLibStreamHandle.NativeZLibDLLStub.deflateEndDelegate       = ZLibNative.ZLibStreamHandle.NativeZLibDLLStub.CreateDelegate <ZLibNative.DeflateEndDelegate>("deflateEnd");
     ZLibNative.ZLibStreamHandle.NativeZLibDLLStub.inflateInit2_Delegate    = ZLibNative.ZLibStreamHandle.NativeZLibDLLStub.CreateDelegate <ZLibNative.InflateInit2_Delegate>("inflateInit2_");
     ZLibNative.ZLibStreamHandle.NativeZLibDLLStub.inflateDelegate          = ZLibNative.ZLibStreamHandle.NativeZLibDLLStub.CreateDelegate <ZLibNative.InflateDelegate>("inflate");
     ZLibNative.ZLibStreamHandle.NativeZLibDLLStub.inflateEndDelegate       = ZLibNative.ZLibStreamHandle.NativeZLibDLLStub.CreateDelegate <ZLibNative.InflateEndDelegate>("inflateEnd");
     ZLibNative.ZLibStreamHandle.NativeZLibDLLStub.zlibCompileFlagsDelegate = ZLibNative.ZLibStreamHandle.NativeZLibDLLStub.CreateDelegate <ZLibNative.ZlibCompileFlagsDelegate>("zlibCompileFlags");
     RuntimeHelpers.PrepareDelegate((Delegate)ZLibNative.ZLibStreamHandle.NativeZLibDLLStub.deflateInit2_Delegate);
     RuntimeHelpers.PrepareDelegate((Delegate)ZLibNative.ZLibStreamHandle.NativeZLibDLLStub.deflateDelegate);
     RuntimeHelpers.PrepareDelegate((Delegate)ZLibNative.ZLibStreamHandle.NativeZLibDLLStub.deflateEndDelegate);
     RuntimeHelpers.PrepareDelegate((Delegate)ZLibNative.ZLibStreamHandle.NativeZLibDLLStub.inflateInit2_Delegate);
     RuntimeHelpers.PrepareDelegate((Delegate)ZLibNative.ZLibStreamHandle.NativeZLibDLLStub.inflateDelegate);
     RuntimeHelpers.PrepareDelegate((Delegate)ZLibNative.ZLibStreamHandle.NativeZLibDLLStub.inflateEndDelegate);
     RuntimeHelpers.PrepareDelegate((Delegate)ZLibNative.ZLibStreamHandle.NativeZLibDLLStub.zlibCompileFlagsDelegate);
 }
示例#25
0
        protected override unsafe void UseBufferPointerImpl(UseBufferPointerDelegate action)
        {
            byte *ptr = null;

            RuntimeHelpers.PrepareDelegate(action);
            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                this.buffer.AcquirePointer(ref ptr);

                action(ptr, this.Length);
            }
            finally
            {
                if (ptr != null)
                {
                    this.buffer.ReleasePointer();
                }
            }
        }
        internal void AddHandler(EventHandler handler)
        {
            bool lockTaken = false;

            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                RuntimeHelpers.PrepareConstrainedRegions();
                Monitor.Enter(@lock, ref lockTaken);
                RuntimeHelpers.PrepareDelegate(handler);
                this.Push(handler);
            }
            finally
            {
                if (lockTaken)
                {
                    Monitor.Exit(@lock);
                }
            }
        }
        internal void AddHandler(EventHandler handler)
        {
            bool lockTaken = false;

            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                RuntimeHelpers.PrepareConstrainedRegions();
                Monitor.Enter(ModuleUninitializer.@lock, ref lockTaken);
                RuntimeHelpers.PrepareDelegate((Delegate)handler);
                this.Push((object)handler);
            }
            finally
            {
                if (lockTaken)
                {
                    Monitor.Exit(ModuleUninitializer.@lock);
                }
            }
        }
示例#28
0
        internal void AddHandler(EventHandler handler)
        {
            bool flag = false;

            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                RuntimeHelpers.PrepareConstrainedRegions();
                Monitor.Enter(ModuleUninitializer.@lock, ref flag);
                RuntimeHelpers.PrepareDelegate(handler);
                this.Push(handler);
            }
            finally
            {
                if (flag)
                {
                    Monitor.Exit(ModuleUninitializer.@lock);
                }
            }
        }
示例#29
0
文件: JITHook.cs 项目: dmhai/NJITHook
        public unsafe JITHook(Delegate hook, Version version)
        {
            VMT vmt;

            RuntimeHelpers.PrepareDelegate(hook);

            foreach (var method in typeof(JITHook).GetMethods())
            {
                RuntimeHelpers.PrepareMethod(method.MethodHandle);
            }

            switch (version)
            {
            case Version.CORJit:
                vmt = new VMT(GetJit_CorJit());
                break;

            case Version.CLRJit:
                vmt = new VMT(GetJit_ClrJit());
                break;

            default:
                throw new NotImplementedException();
            }

            Delegate compileMethodDelegate = null;

            if (IntPtr.Size == 4)
            {
                vmt.Hook(0, hook, ref compileMethodDelegate, typeof(Data.CompileMethodDel32));
                this._compileMethod32 = (Data.CompileMethodDel32)compileMethodDelegate;
            }
            else
            {
                vmt.Hook(0, hook, ref compileMethodDelegate, typeof(Data.CompileMethodDel64));
                this._compileMethod64 = (Data.CompileMethodDel64)compileMethodDelegate;
            }

            this._vmt = vmt;
        }
示例#30
0
        public bool Hook(Data.CompileMethodDel64 hookedCompileMethod)
        {
            this.NewCompileMethod = hookedCompileMethod;
            IntPtr pVTable        = _addrProvider.VTableAddr;
            IntPtr pCompileMethod = Marshal.ReadIntPtr(pVTable);
            uint   old;

            if (
                !Data.VirtualProtect(pCompileMethod, (uint)IntPtr.Size,
                                     Data.Protection.PAGE_EXECUTE_READWRITE, out old))
            {
                return(false);
            }

            OriginalCompileMethod =
                (Data.CompileMethodDel64)
                Marshal.GetDelegateForFunctionPointer(Marshal.ReadIntPtr(pCompileMethod), typeof(Data.CompileMethodDel64));

            PrintPointer(pCompileMethod);


            // We don't want any infinite loops :-)
            RuntimeHelpers.PrepareDelegate(NewCompileMethod);
            RuntimeHelpers.PrepareDelegate(OriginalCompileMethod);
            RuntimeHelpers.PrepareMethod(GetType().GetMethod("ProtectVTable", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).MethodHandle, new[] { typeof(T).TypeHandle });
            RuntimeHelpers.PrepareMethod(GetType().GetMethod("UnHook").MethodHandle, new[] { typeof(T).TypeHandle });

            Marshal.WriteIntPtr(pCompileMethod, Marshal.GetFunctionPointerForDelegate(NewCompileMethod));

            System.Threading.Thread vTableVerifier = new System.Threading.Thread(() => ProtectVTable());
            vTableVerifier.IsBackground = true;
            vTableVerifier.Start();


            return(Data.VirtualProtect(pCompileMethod, (uint)IntPtr.Size,
                                       Data.Protection.PAGE_EXECUTE_READ, out old));
        }