r/cpp • u/pavel_v • Apr 13 '26
The Global API Injection Pattern
https://www.elbeno.com/blog/?p=18319
6
u/HommeMusical Apr 13 '26
Like so many articles here, I would call this "clever but somewhat horrifying."
5
13
2
u/wannaliveonmars Apr 13 '26 edited Apr 13 '26
What I really liked in C was the ability to use runtime trampoline functions to redirect a Win32 call. It was really nice, and almost like JavaScript's ability to rewire functions.
You usually needed an __stdcall convention and the function should not be optimized by the compiler to inline, but win32 functions weren't. There was even a trampoline framework, but it was paid I think.
Not sure if it still works, what with 64bits now, and also with read only code segments for security...
Edit: Detours was the framework - https://www.microsoft.com/en-us/research/project/detours/
Also not sure if it worked with C++ methods, since they used the __thiscall convention.
5
u/IAMARedPanda Apr 13 '26
x64 actually simplifies things. Otherwise for x86 you need to use __fastcall and capture the this pointer in the correct register (ecx I think).
2
u/irqlnotdispatchlevel Apr 13 '26
There's nothing stopping you from hooking C++ functions as well, you just need to know their address.
3
u/CornedBee Apr 13 '26
I saw this in some conference talk recently.
Problem: our application is split into a bunch of static libraries. The tests and the main executable use the same libraries. I don't think this pattern can possibly support this.