/// <summary> /// Hijacks new operator. Hijacked new operator should be restored before AppDomain being unloaded. /// </summary> public static unsafe void Hijack() { BindingFlags bindingFlag = BindingFlags.NonPublic | BindingFlags.Static; try { NewOperatorHijackContext = new HijackFuncContext <IntPtr, Object>(); NewOperatorHijackContext.MigrateInstruction += NewOperatorMigrateInstruction; MethodInfo newOperatorHook = typeof(MemoryRestrictor).GetMethod(nameof(NewOperatorHook), bindingFlag); HijackHelper.HijackUnmanagedMethod(MemoryCrawler.RetrieveMethod(DynamicJitHelperEnum.NewSFast), newOperatorHook, NewOperatorHijackContext); } catch { NewOperatorHijackContext.Dispose(); NewOperatorHijackContext = null; throw; } try { FastAllocateStringHijackContext = new HijackFuncContext <Int32, String>(); FastAllocateStringHijackContext.MigrateInstruction += FastAllocateStringMigrateInstruction; MethodInfo fastAllocateStringHook = typeof(MemoryRestrictor).GetMethod(nameof(FastAllocateStringHook), bindingFlag); MethodInfo fastAllocateStringMethodInfo = typeof(String).GetMethod("FastAllocateString", bindingFlag); HijackHelper.HijackManagedMethod(fastAllocateStringMethodInfo, fastAllocateStringHook, FastAllocateStringHijackContext); } catch { FastAllocateStringHijackContext.Dispose(); FastAllocateStringHijackContext = null; } try { BoxHijackContext = new HijackFuncContext <IntPtr, IntPtr, Object>(); BoxHijackContext.MigrateInstruction += BoxMigrateInstruction; MethodInfo boxHook = typeof(MemoryRestrictor).GetMethod(nameof(BoxHook), bindingFlag); HijackHelper.HijackUnmanagedMethod(MemoryCrawler.RetrieveMethod(DynamicJitHelperEnum.HelpBox), boxHook, BoxHijackContext); } catch { BoxHijackContext.Dispose(); BoxHijackContext = null; } }
/// <summary> /// Restores new operator. /// </summary> public static unsafe void Restore() { BindingFlags bindingFlag = BindingFlags.NonPublic | BindingFlags.Static; MethodInfo fastAllocateStringMethodInfo = typeof(String).GetMethod("FastAllocateString", bindingFlag); if (NewOperatorHijackContext != null) { HijackHelper.RestoreUnmanagedMethod(MemoryCrawler.RetrieveMethod(DynamicJitHelperEnum.NewSFast), NewOperatorHijackContext); } if (FastAllocateStringHijackContext != null) { HijackHelper.RestoreManagedMethod(fastAllocateStringMethodInfo, FastAllocateStringHijackContext); } if (BoxHijackContext != null) { HijackHelper.RestoreUnmanagedMethod(MemoryCrawler.RetrieveMethod(DynamicJitHelperEnum.HelpBox), BoxHijackContext); } }