Windows API Hooking/DLL Injection/Function Hooking - Need some pointers lazarus / 34-Windows ---------------------------------------------------------------------- tooknox · 2026-04-23 17:55 Greetings Everyone !! I have been stuck on hooking a function in memory. I went through all the posts related to API hooking and found the DDetour library and it seems like a good start. However, I saw that the last commit in the GitHub repo was 6 years back. Is DDetour still maintained or is it still the recommended way to do it?? Just need some pointers on how to proceed here... Thanks in advance tooknox ---------------------------------------------------------------------- LeP · 2026-04-23 18:19 I use in Delphi some components that use that library for hooks. No issues by now. Hooks are not new in Windows, so I don't think there are a lot to change. ---------------------------------------------------------------------- H₂SO₄ · 2026-04-24 05:13 There's also Microsoft's official Detours library (written in C++) - you could just link to that instead if you're concerned about maintenance. The core concept of detouring, though, is very simple and bound to the target architecture (which doesn't change unless you swap out your CPU and is very stable in general with regards to backward compatibility). If all you want is to irreversibly detour a function, the following function works for x86 and x86_64: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i uses  Windows; {$push}{$warn 4055 off : Conversion between ordinals and pointers is not portable} /// Irreversibly changes the first instruction of `Original` into an unconditional jump to `Replacement`.////// `Original` must provide at least 5 bytes of space; otherwise, adjacent code may silently become corrupted./// The absolute difference between `Original` and `Replacement` must be less than ~2 GiB, or the function will fail.////// On failure, the function returns one of the following non-zero error codes:///   -1 : Relative jump range exceeded (2 GiB limit)///   -2 : Failed to remove page write protection///    1 : Failed to restore original page protection////// Negative error codes indicate that no instruction data was modified./// On success, the function returns 0.function PatchFunction(Original, Replacement: Pointer): Integer;var  Jump: array[0..4] of Byte = ($E9, $00, $00, $00, $00); // jmp rel32  Protection: DWORD;  Offset: Int64;begin   // Calculate relative jump target address, taking instruction size into account  Offset := Int64(PtrUInt(Replacement)) - PtrUInt(Original) - SizeOf(Jump);  if (Offset > $7FFFFFFF) or (Offset < -$80000000) then Exit(-1);   Move(Offset, Jump[1], SizeOf(DWORD)); // Works in 64-bit mode too (since x86 is little-endian)   // Briefly disable write protection    if not VirtualProtect(Original, SizeOf(Jump), PAGE_EXECUTE_READWRITE, @Protection) then Exit(-2);   // Overwrite first instruction and restore original protection  Move(Jump[0], Original^, SizeOf(Jump));  if not VirtualProtect(Original, SizeOf(Jump), Protection, @Protection) then Exit(1);   Result := 0;end; {$pop} ---------------------------------------------------------------------- tooknox · 2026-04-24 07:27 Quote from: LeP on April 23, 2026, 08:19:49 pmI use in Delphi some components that use that library for hooks. No issues by now. Hooks are not new in Windows, so I don't think there are a lot to change. @LeP Well if it's good enough for Delphi Component(s), should be good enough for me. BTW I started with the hook itself and it was quiet pleasant to write with DDetour, However,  I couldn't find a way to inject the hook (dll) via DDetour; What's the standard/recommended to actually inject the DLL hook or if I was careless enough to miss an inject routine in DDetour library just let me know. Quote from: Khrys on April 24, 2026, 07:13:49 amThere's also Microsoft's official Detours library (written in C++) - you could just link to that instead if you're concerned about maintenance. The core concept of detouring, though, is very simple and bound to the target architecture (which doesn't change unless you swap out your CPU and is very stable in general with regards to backward compatibility). If all you want is to irreversibly detour a function, the following function works for x86 and x86_64: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i uses  Windows; {$push}{$warn 4055 off : Conversion between ordinals and pointers is not portable} /// Irreversibly changes the first instruction of `Original` into an unconditional jump to `Replacement`.////// `Original` must provide at least 5 bytes of space; otherwise, adjacent code may silently become corrupted./// The absolute difference between `Original` and `Replacement` must be less than ~2 GiB, or the function will fail.////// On failure, the function returns one of the following non-zero error codes:///   -1 : Relative jump range exceeded (2 GiB limit)///   -2 : Failed to remove page write protection///    1 : Failed to restore original page protection////// Negative error codes indicate that no instruction data was modified./// On success, the function returns 0.function PatchFunction(Original, Replacement: Pointer): Integer;var  Jump: array[0..4] of Byte = ($E9, $00, $00, $00, $00); // jmp rel32  Protection: DWORD;  Offset: Int64;begin   // Calculate relative jump target address, taking instruction size into account  Offset := Int64(PtrUInt(Replacement)) - PtrUInt(Original) - SizeOf(Jump);  if (Offset > $7FFFFFFF) or (Offset < -$80000000) then Exit(-1);   Move(Offset, Jump[1], SizeOf(DWORD)); // Works in 64-bit mode too (since x86 is little-endian)   // Briefly disable write protection    if not VirtualProtect(Original, SizeOf(Jump), PAGE_EXECUTE_READWRITE, @Protection) then Exit(-2);   // Overwrite first instruction and restore original protection  Move(Jump[0], Original^, SizeOf(Jump));  if not VirtualProtect(Original, SizeOf(Jump), Protection, @Protection) then Exit(1);   Result := 0;end; {$pop} Wow that's nice. It would also be a good exercise to use C++ detour lib in FPC. Got something to do on weekend . I will try to replicate the hook I wrote in DDetour with MS Detour. ---------------------------------------------------------------------- Thaddy · 2026-04-24 08:06 Well the old ddetours is good enough. I have similar to Khrys:Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i // courtesy Roberto Della Pasquauses windows;type  // must be fixed. size is arbitrary but usually sufficient  // alternatively use allocmem to the PByteArray and   // don't forget to free the memory at program end.   TByteArray = array [0 .. 32767] of Byte;  PByteArray = ^TByteArray; procedure PatchCode(Old, New: Pointer; Size: Integer);var  NP, IR: DWORD;  I: Integer;begin  if VirtualProtect(Old, Size, PAGE_EXECUTE_READWRITE, NP) then  begin    for I := 0 to Size - 1 do      PByteArray(Old)^[I] := PByteArray(New)^[I];    VirtualProtect(Old, Size, NP, IR);    FlushInstructionCache(GetCurrentProcess, Old, Size);  end;end; { this is the function you actually use }procedure RedirectCode(Func, RedirectFunc: Pointer);var  NewJump: packed record    Code: Byte;    Distance: NativeInt;  end;begin  if (Func = nil) or (RedirectFunc = nil) then Exit;  NewJump.Code := $E9;  NewJump.Distance := NativeInt(NativeUint(RedirectFunc) - NativeUint(Func) - Sizeof(NewJump));  PatchCode(Func, @NewJump, Sizeof(NewJump));end; // demoprocedure MyFillChar(var X;count:integer;value:char);begin  writeln('Sorry, I am indisposed');end;  var s:string; begin  RedirectCode(@System.Fillchar,@MyFillChar);  Fillchar(s,10,#65);end.Only used on x64_86, but I think the jump instruction is the same on i386. @Khrys If you patch the code like we do, you need to call FlushInstructionCache on modern processors, because the actual function may be in the cache, thus still executing old code. [Edit] Both the code from Khrys and from me is destructive, permanent for the duration of the program. Detours (the oldest) or DDetours are non-destructive, patching can be done and undone at runtime. Our code can be made non-destructive, though, by storing the patched byte and address. I can give an example for my code. ---------------------------------------------------------------------- tooknox · 2026-04-26 06:41 @Thaddy Well I started with small/humble API hooking exercise but have now raised the stakes . What I am trying to do now is write a small program (say in C) with a test function and run it. Then hook/inject another DLL (in Pascal ofc) into the running process and hook one of it's function with a function from this DLL. I can write the DLL in DDetour, what I am struggling with now is actually how to hook/inject that DLL and overwrite the function in a running program. Am I missing something with DDetour?? ---------------------------------------------------------------------- Remy Lebeau · 2026-04-26 21:28 Quote from: tooknox on April 26, 2026, 08:41:35 amWell I started with small/humble API hooking exercise but have now raised the stakes . What I am trying to do now is write a small program (say in C) with a test function and run it. Then hook/inject another DLL (in Pascal ofc) into the running process and hook one of it's function with a function from this DLL. I can write the DLL in DDetour, what I am struggling with now is actually how to hook/inject that DLL and overwrite the function in a running program. Am I missing something with DDetour?? Injecting a DLL into a running process is one thing. There are several techniques available for that purpose, such as using CreateRemoteThread() to call LoadLibrary(), etc. But, hooking a random function in a running process is another thing, especially if that function is not exposed such as in an EXPORTS table. Without knowing the memory address of that function, there is no way to hook it. Also, injecting into a process and hooking random functions is likely to trigger anti-virus/anti-malware programs. ---------------------------------------------------------------------- 440bx · 2026-04-26 22:07 Quote from: Remy Lebeau on April 26, 2026, 11:28:50 pmInjecting a DLL into a running process is one thing. There are several techniques available for that purpose, such as using CreateRemoteThread(), etc. But, hooking a random function in a running process is another thing It sure is. Quote from: Remy Lebeau on April 26, 2026, 11:28:50 pmespecially if that function is not exposed such as in an EXPORTS table. Without knowing the memory address of that function, there is no way to hook it. Indeed.  I was tempted to say something about that but, the OP's description of what he's trying to do leaves a lot of important information out.  I would recommend hooking only exported functions by patching the IAT because other methods can quickly become quite problematic and difficult to handle correctly but, I don't know if that is enough for whatever the OP really wants to do.  Patching the IAT is fairly simple and there aren't too many "gotcha's" in that method. Quote from: Remy Lebeau on April 26, 2026, 11:28:50 pmAlso, injecting into a process and hooking random functions is likely to trigger anti- virus/anti-malware programs. That too. ---------------------------------------------------------------------- tooknox · 2026-04-27 04:35 I think I might have been a bit ambitious or amature. I now recall why I can call LoadLibraryA from kernel32.dll to create remote thread "It is mapped to same address in every process space". So injection part is pretty simple mentioning here for future me.... 1. OpenProcess with "PROCESS_ALL_ACCESS" 2. VirtualAllocEx to allocate space for DLL path 3. WriteProcessMemory to write DLL path 4. GetProcAddress to get the address of LoadLibraryA (Correct me if I am wrong, This would be the address in the source process but because it's mapped at the same {virtual} address in every process, it works) 5. Finally CreateRemoteThread to execute LoadLibraryA with the allocated memory address as argument and we are done. You both are right unless I have address of the target function I can't do anything. What I want to achieve...more of what I want to learn is this, There is an open source program "SecureUXTheme" for modern windows OS to allow applying custom themes by bypassing the theme signature verification. There are other tools that achieve the same thing by patching the uxtheme.dll directly (on disk) and overwriting the signature verification function to always return true. However, SecureUXTheme does this by patching the signature verification function in memory and I wanted to figure out how?? Yes I know I can look at the source code (it's C++) but will give my self a few days more to figure out before I look at the source code. Any idea on how they might be doing it?? ---------------------------------------------------------------------- Thaddy · 2026-04-27 04:43 It is done in the way Khrys and I showed. (and probably storing the patch byte, which we forgot to show) Using the VirtualProtect api should not trigger any anti-virus, because that is a legitimate api. (people who think otherwise played too much doom) Some languages like C# internally rely on it in its reflection implementation. This api is also created precisely to do what you want: patching code at runtime with a legitimate purpose. The code is patched in memory and not on disk: it un/protects the in-memory readonly data and only executes after the patched area is protected again. Also: Windows itself uses it a lot internally for all kind of purposes, including Defender. ---------------------------------------------------------------------- tooknox · 2026-04-27 05:51 Thanks @Thaddy, I am kinda arranging different pieces of the puzzle now... 1. so I have injected my DLL in the target process (DONE) 2. This dll will contain the code you mentioned, to actually hook the function in the target process 3. The DLL should also contain the target function declaration (I think it should??) with exact signature 4. What I am stuck on is how do I get/access the address of target function in the target process inside the injected DLL code which I can then use with your code. ---------------------------------------------------------------------- Thaddy · 2026-04-27 06:05 Well, after a dll is loaded and initialized it is within the same memory space as the program itself. E.g. if you put my hooking code in a dll, it would still patch the fillchar system procedure in exactly the same way: you take the address simply the same as in the demo. It is safe to call it from within dllmain(). See here for ins and outs: https://learn.microsoft.com/en-us/windows/win32/dlls/dynamic-link- library-best-practices In the dll, put it in the initialization section. ---------------------------------------------------------------------- tooknox · 2026-04-27 08:21 Ok for fillchar yes cuz it's available in the injected DLL too. How about this (not using the original uxtheme.dll, will do that myself) Say I have a c binary compiled from Code: C  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i #include#include int sum(int a, int b) {    return a + b;}int main(){    int x,y;    printf("Please input the number:\n");    printf("a = ");scanf("%d",&x);    printf("b = ");scanf("%d",&y);    printf("output = %d\n", sum(x,y));    printf("Press enter to exit");  getch();}  And I want to patch the sum function in memory to say multiply instead of add, say by injecting my dll before entering the scanf values. How to I get the pointer to sum function from my dll. can't wrap my head around this. Or may be I am misunderstanding something about in memory patching. ---------------------------------------------------------------------- 440bx · 2026-04-27 10:37 if you are reasonably well versed in assembler, what you want to do is not really hard BUT, it will take a little bit of work. The thing that causes extra work is that whenever you change executable code in memory, the code is changed only in that process because Windows will normally do a copy-on-write.  You should expect that. The first thing you need to know is the address to patch.  The way to determine that is using IDA (the free version), you disassemble the uxtheme thing after looking around a bit, you'll figure out the location you need to patch.  Make a note of the bytes you need to patch along with the surrounding bytes. Use a memory viewer, the one built into Process Hacker or System Informer (same thing, different name) to inspect the in-memory copy of uxtheme.  Find the address in-memory.  if the address you determined using IDA free is correct, you should see the same bytes in memory as those in the IDA decompilation. Presuming the address is correct.  That's the address of interest.  Once you know the address, the rest is a piece of cake. First, you use OpenProcess to open the process you want to modify. Second, you use WriteProcessMemory to overwrite the bytes at that address with whatever bytes you want. At least in theory, you should be all done. There is an easy way of testing all this stuff, simply write your own GUI program that loads the dll of interest, uxtheme in your case.  Since uxtheme is in your own process space, OpenProcess is guaranteed to be successful (unless you code it wrong), still use WriteProcessMemory because it will take care of writing to the non- writable code segment (it does all the busy-work for you), once that is done, your program should be able to use whatever pirated theme you wish to load. Since you're doing everything in your own process, you can debug locally.  Once you know it is bug free, all you have to do is get the target process id to open the process.  Toolhelp is typical used to get a snapshot of the processes in the system.  Walk that snapshot, altering their uxtheme.  that's it, you're done.  Well... almost done... don't forget to close the process handle after you've written the new bytes in their proper place. HTH. ---------------------------------------------------------------------- Thaddy · 2026-04-27 14:54 @440bx I don't think he means a permanently patched executable: otherwise I would have answered differently and cautiously. Such answers are to be found though, at https://www.delphibasics.info Note that is mostly for 32 bit windows - your favourite - , but I guess that it if you feed it into DeepSeek or Claude.ai you will get a working 64 bit version too. (Even in the free versions) Look for the Func snippets, covers both runtime patching as exe patching, IIRW. If you have learned all the code on that website - and understand it - you are sufficiently trained to do an attempt at writing malware. A C function in a C program will simply also be patched with my Pascal code when put in a dll: it is a jump instruction.....It will jump.... ---------------------------------------------------------------------- tooknox · 2026-04-27 15:29 Yeah I did not mean a permanently patched executable. Honestly looked at the SecureUXTheme project and wondered how the guy did it and have spent 2 weekends try to figure it out that's the whole gist of it. Quote from: Thaddy on April 27, 2026, 04:54:35 pmSuch answers are to be found though, at https://www.delphibasics.info Note that is mostly for 32 bit windows - your favourite - , but I guess that it if you feed it into DeepSeek or Claude.ai you will get a working 64 bit version too. (Even in the free versions) Look for the Func snippets, covers both runtime patching as exe patching, IIRW. If you have learned all the code on that website - and understand it - you are sufficiently trained to do an attempt at writing malware. Thanks for sharing this  , good to learn more of this while I am at it. Quote from: Thaddy on April 27, 2026, 04:54:35 pmA C function in a C program will simply also be patched with my Pascal code when put in a dll: it is a jump instruction.....It will jump.... Ohh ok, I thought I would have to go through a ritual but if I can refer to it by name in DLL then it should be straight forward. Will test after work Also really appreciate you guys helping me out ---------------------------------------------------------------------- 440bx · 2026-04-27 17:33 Quote from: Thaddy on April 27, 2026, 04:54:35 pmNote that is mostly for 32 bit windows that works equally well in 64 bit as it does in 32 bit.  The only difference is the code the programmer has to inspect to determine the address to patch. The simplest, which should be the choice, is patching the IAT which is available if the function is exported, if it is not then the disassembly avenue is the way to determine the target address. ---------------------------------------------------------------------- Thaddy · 2026-04-28 04:08 The post important thing that is not in the older code, but is necessary nowadays, is flushing the instruction cache as per my example. That should be added to any of the other examples too. ---------------------------------------------------------------------- tooknox · 2026-05-04 13:00 @Thaddy I think I am close, have done the boilerplate work. Testing in progress. Just a quick query once my DLL is injected, it should technically have full access to the target process, how do I get the base address of the target process in memory, should calling GetModuleHandle(nil) get me the address?? Thanks, tooknox ---------------------------------------------------------------------- Thaddy · 2026-05-04 16:35 You don't need the address before hand: you are patching @runtime. That means the pointer is known and you can simply take the address of the procedure or function you want to patch. As per my example. ---------------------------------------------------------------------- tooknox · 2026-05-04 19:49 Ok so I have successfully done the runtime patching will share the details/code once I have cleaned the scattered mess in my code, here is the gist though 1. I have a 'C' binary called "target.exe" compiled from the C source code I shared. I want to patch the "sum" function in this exe at runtime to multiply instead of adding the scanf values. 2. I write an injector in Lazarus that does the boilerplate work of LoadLibrary, WriteProcessMemory etc...the whole shebang for injecting the DLL. 3. Then there is the library/DLL in Pascal/Lazarus which once injected will hook the sum function with a function defined in the DLL. How I did it 1. Since DLL is in the process itself GetModuleHandle(nil) will return the base address of the target.exe. (I verified it does) 2. Got the relative virtual address of the sum function in target.exe via disassembler and added it to base address and then called the intercept/hook function from DDetour Library and voila it works as expected, after scanf values, the printf outputs the multiplication instead of sum like magic. And since the base address is dynamically calculated, the code works with address randomization. My questions 1. what do you mean by getting pointer directly in my DLL code?? I mean can you share short snippet on how to refer to the "sum" function from target.exe in my DLL pascal code. This would have saved me a lot of head scratching. Either way learned a lot in the process though. 2. I was trying to avoid DDetour CUZ I understood @Khrys and your code and tried to use the functions as is. @Khrys code returns -1 (more 2G Rel Address) and yours forced the target.exe to exit after second scanf. Doesn't mean anything is wrong with your code, just sharing the observation on what I have done till now. Next thing I am trying to do is to use your function instead of the intercept function from DDetour to make it work now that I have a baseline. ---------------------------------------------------------------------- H₂SO₄ · 2026-05-05 04:47 Quote from: tooknox on May 04, 2026, 09:49:50 pm2. I was trying to avoid DDetour CUZ I understood @Khrys and your code and tried to use the functions as is. @Khrys code returns -1 (more 2G Rel Address) and yours forced the target.exe to exit after second scanf. Doesn't mean anything is wrong with your code, just sharing the observation on what I have done till now. Next thing I am trying to do is to use your function instead of the intercept function from DDetour to make it work now that I have a baseline. That's strange... how exactly are you calling the function? ---------------------------------------------------------------------- tooknox · 2026-05-05 08:41 So here is the code with steps to follow. 1. FPCDLLInjector.zip: This is a small tool/project I wrote during my testing. It's just for DLL injection and has nothing to do with hooking code/DLL. Helped simplify the testing process.. Just select the Payload DLL from OpenDialog button at the bottom, then select the process from the ListView and hit Inject. You can keep this window opened and just refresh to keep testing. Built with Lazarus 4.6/FPC 3.2.2 Compiled on x86_64 works fine. 2. PayloadDLL.zip: Contains the code for the DLL to be injected. Once you open the *.lpi file in lazarus, go to Project Options > Compiler Options > Paths > Other Unit Files (-Fu) and add the DDetours Library to path. Ofc there are other ways to do this, if you want. @Khrys, I have included both yours and Thaddy's code in the DLL source along with how I was calling them. I didn't debug any further because it worked right away with DDetour. Compiled on x86_64 works fine. 3. TargetCBinary.zip: contains the c source file and the binary compiled using MSVC compiler (had to use MSVC instead of GCC cuz DWARF symbols were not working with x64dbg). I suggest you use the binary directly because the offset address is hardcoded in the DLL code for this binary. Recompiling may or may not change this. If you are paranoid like me and don't wanna use the .exe file, build the C source file yourself and replace the offset address in the Payload DLL. Steps: Run "target.exe" and input the two numbers, you should see the sum of the number by default. Run again and let the CLI stay on the first scanf, try injecting the "payload.dll", once done continue entering the scanf values and you will see a MessageBox along with the sum replaced by multiplication. ---------------------------------------------------------------------- H₂SO₄ · 2026-05-06 06:02 Code: Text  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i Patch Result: -1 | Target Func at: 00007FF7EBC015E2 | Hooked Func at: 0000000110001750 Oh, now I see - look at the addresses! They are almost 128 terabytes apart because the  .exe  and the  .dll  have completely different base addresses. Both @Thaddy's version and mine use a simplistic  jmp rel32,  which can't handle such large jumps. I stuck with the relative jump because (1) it works independently of architecture & ABI and (2) I mostly used it to debug/profile 32-bit code. You could try replacing that instruction with  mov rax, imm64  followed by  jmp rax  (should be fine on x64 Windows). ---------------------------------------------------------------------- tooknox · 2026-05-06 07:31 @Khrys, Yeah I dumped the addresses and they were too far apart. Just wanted to double-check If I was doing anything wrong. Will replace jmp rel32 with mov rax, imm64 and test it out. However I am trying a few other things 1. The Detour:     a) I tried to use the Microsoft Detours (My OCD kicked in and now I wanna try it) now that I have the boilerplate stuff in place. The thing is, it is designed to be built/used as a static library and the default Makefile provided only works with MSVC. Is there any way to make MSVC *.lib work with FPC/Lazarus? Parallelly I wrote my own Makefile and compiled it with MinGW got the libdetours.a, but trying to link it with {$LINKLIB} throws a lot of undefined symbols in libdetours.a itself. Tried adding libkernel32.a and got most of them fixed but in the end can't get a few symbols resolved, linking libstdc++.a fails with some COFF error.     https://github.com/microsoft/detours     How do I proceed with this now??     b) Will also try to modify your code with mov rax, imm64, just so I have a way to do it without any external dependency. 2. The Payload:     a) Is there any other way to get the address/pointer of the sum function from payload code besides what I did?     b) Is it possbile to calculate even the offset dynamically at runtime?? BTW, in case someone wants to setup (Only the) MSVC compiler without the full visual studio BS, helped me setup an MSVC build environment quickly and easy to get rid off. https://gist.github.com/mmozeiko/7f3162ec2988e81e56d5c4e22cde9977 ---------------------------------------------------------------------- tooknox · 2026-05-08 06:56 @Khrys, I changed the jmp rel32 to 64-bit indirect absolute RIP relative jump, JMP [RIP+0] (6-Bytes: FF 25 00 00 00 00) followed by 8-Bytes of address of jump to. I also wrote a procedure to restore patch too. There are a few drawbacks through 1. The target function should be bigger than 14 bytes (duh!!) 2. The restore patch only works if the 14-bytes overwritten don't contain any RIP relative instruction cuz that will change for obvious reasons and I haven't taken that into account. Here is the excerpt from the zip attached. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i // @tooknox's implementation ///////////////////////////////////////////////////procedure SetMemoryWritable(Addr: Pointer; Size: Integer; Enable: Boolean; var OldProtect: DWORD);begin  if Enable then    VirtualProtect(Addr, Size, PAGE_EXECUTE_READWRITE, @OldProtect)  else    VirtualProtect(Addr, Size, OldProtect, @OldProtect);end; procedure ApplyPatch(Source: Pointer; Destination: Pointer; out Backup: TPatchBackup);var  Patch: array[0..13] of Byte;  OldProtect: DWORD;begin  // Step 1: 14-byte indirect absolute RIP-Relative JMP [RIP+0]  Patch[0] := $FF; Patch[1] := $25;  Patch[2] := $00; Patch[3] := $00; Patch[4] := $00; Patch[5] := $00;  PPointer(@Patch[6])^ := Destination;   // Step 2: Backup the original bytes  Move(Source^, Backup, 14);   // Step 3: Apply the patch  SetMemoryWritable(Source, 14, True, OldProtect);  Move(Patch, Source^, 14);  SetMemoryWritable(Source, 14, False, OldProtect);end; procedure RemovePatch(Source: Pointer; const Backup: TPatchBackup);var  OldProtect: DWORD;begin  // Restore the original bytes from the backup  SetMemoryWritable(Source, 14, True, OldProtect);  Move(Backup, Source^, 14);  SetMemoryWritable(Source, 14, False, OldProtect);end; ////////////////////////////////////////// //////////////////////////////////////  Attached the new payload DLL code, still contains everything it had before, just added my implementation. ---------------------------------------------------------------------- H₂SO₄ · 2026-05-08 07:30 Good to know you solved it. Do note however that  RIP-relative addressing is  x86_64-only (there is no such thing as  EIP-relative addressing on plain x86). An architecture-independent method would be to use  48 B8 00 00 00 00 90 90 90 90 FF E0  (12 bytes) as the patch, inserting the target address using  PPointer(@Patch[2])^ := Destination.  This yields the following instruction sequences on  x86_64  and  x86,  respectively: Code: ASM  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i movabs rax, jmp    rax Code: ASM  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i dec eaxmov eax, nopnopnopnopjmp eax ---------------------------------------------------------------------- tooknox · 2026-05-08 08:08 @Khrys Wow this is way better, added it to PayloadDLL code (tested and works great) along with everything else, in case someone wants to try all the ways to hook. Also copied the procedure to restore just like with RIP relative, and unlike RIP-Relative, this restore patch won't have the previous restrictions (target function must be >= 12 bytes ofc) A few things still bothering me though . 1. How do i go about using the Microsoft Detour library with freepascal??. I mean this is purely academic ofc. 2. Is there any other recommended way to get the address of the target function because what I have done now seems a bit janky....?? I think NOW I will go ahead and look at the "SecureUXTheme" source code to see how they did it Edit: Also added some QoL improvements to FPCDLLInjector ---------------------------------------------------------------------- tooknox · 2026-05-10 09:42 Just to update I have been trying to use the MS Detours (static) library https://github.com/microsoft/detours. Fortunately I found a recent merge request from @Coldzer0 to support MSVC static libraries; built the compiler merging his PR and voilà I can link detours.lib static library and the payload code builds successfully https://forum.lazarus.freepascal.org/index.php/topic,73757.0.html https://gitlab.com/freepascal.org/fpc/source/-/merge_requests/1385 He also helped me with a silly mistake of mine. However MS Detours is not working the way it's supposed to, will attach the code to share my OCD with others ---------------------------------------------------------------------- Thaddy · 2026-05-10 11:08 I think, just think, but I guess Khrys will agree, that you are really overcomplicating things for yourself. That MS library does nothing more than we showed. (apart from our omission of restoring, which I pointed out, but hey, that's not really relevant because it is a runtime patch) There is only one (1) way to create a trampoline and that is patching the entry point. The rest is housekeeping. If what we wrote did not help you, please provide real code, like we did. I am afraid you are doing something horribly wrong. Our code looks simple because it is simple. Maybe not for beginners, but certainly for a software engineer. ---------------------------------------------------------------------- tooknox · 2026-05-11 15:38 I think you didn't read the whole thread. I have already made it work, wrote my own version of it along with others and the real code is attached on the thread too. Also Please read @Khrys' commentary on your code I am just ALSO trying the MS Detour Library to see if it works and links properly with free pascal. To consolidate all the different ways (In terms options, I understand that it's just simple patching in the background)  to do hooking just for academic reasons (I also mentioned this in a previous comment) ---------------------------------------------------------------------- tooknox · 2026-05-11 18:25 Just to update, I have been in touch with @Coldzer0, and he has just pushed a commit (fixed a linker bug) that makes linking Microsoft "detour.lib" successful. I will create and share a separate MSDetoursPayloadDLL as it won't compile with the current FPC; the changes are yet to be merged. https://gitlab.com/Coldzer0/FPC (commit 91d9a596c892a4af04680e74a46fd35ca8b68eab) Or https://gitlab.com/freepascal.org/fpc/source/- /merge_requests/1385/diffs?commit_id=91d9a596c892a4af04680e74a46fd35ca 8b68eab The payload DLL builds successfully and the function hooks without any issues. I will add the code here too in some time This marks the completion of my hooking adventure. I hope his PR gets merges as soon as possible. Thanks @Coldzer0 you have been awesome Thanks to @Khrys and @Thaddy too ---------------------------------------------------------------------- tooknox · 2026-05-12 04:49 Here is the code 1. Checkout MS Detours library from GitHub and build the library 2. Checkout @ColdZer0's latest commit (mentioned above) from GitLab and build FPC. 3. Add the new compiler path(s) to Lazarus and you should be able to build the project. 4. Use the TargetCBinary and FPCDLLInjector from previous comments to test function hooking. Note: I have only defined external functions absolutely needed for hooking, detours library has tons of APIs. You can look at detour.h and define others if you want to experiment. It has APIs to find target functions, to insert payload in new process etc. Argument types are simple and easily translated from c++ to pas. I have included the DLL in the zip in case you don't want to build stuff. Edit: Figured out a way to get (runtime) address of any target function in any binary dynamically (assuming the symbols/debug file exists). https://forum.lazarus.freepascal.org/index.php?topic=74031.msg582712#m sg582712 works flawlessly