Example #1
0
 private static void PreventGarbageCollection(PatchedFunction patchedFunction)
 {
     lock (s_PatchedFunctions)
     {
         s_PatchedFunctions.Add(patchedFunction);
     }
 }
Example #2
0
        private static Patched <TFunction> ApplyPatch <TFunction>(
            ProcessModule module,
            string importedModule,
            string importedName,
            ThunkPredicate isCorrectFunction,
            Func <TFunction, TFunction> buildReplacementFunction)
            where TFunction : class
        {
            AssertDelegate <TFunction>("TFunction");

            module.NotNull("module");
            importedModule.NotEmpty("importedModule");
            isCorrectFunction.NotNull("isCorrectFunction");
            buildReplacementFunction.NotNull("buildReplacementFunction");

            ImageImportDescriptor *descriptors = module.GetImportDescriptors();
            ImageImportDescriptor *descriptor  = module.FindImportedModule(descriptors, importedModule);
            ImageThunkData *       thunk       = module.FindImportedFunction(descriptor, isCorrectFunction);
            MemoryBasicInformation thunkMemory = GetMemoryInformation(thunk);

            MakeWritable(thunkMemory);

            try
            {
                TFunction originalFunction = GetDelegateForFunctionPointer <TFunction>(thunk->Function);

                if (originalFunction == null)
                {
                    throw new ArgumentException("Could not create a delegate for the original function to be patched.");
                }

                TFunction replacementFunction = buildReplacementFunction(originalFunction);
                thunk->Function = GetFunctionPointerForDelegate(replacementFunction);

                return(PatchedFunction.From(
                           importedModule,
                           importedName,
                           replacementFunction,
                           originalFunction));
            }
            finally
            {
                RestoreOriginalProtection(thunkMemory);
            }
        }