I'm wondering what hippomocks does to intercept the exit
call function for example as shown in the below code:
MockRepository mocks;
mocks.ExpectCallFunc(exit).With(2).Throw(std::exception());
It casts the function passed in (in this case a simple function pointer) to a char *, asks the OS nicely to be allowed to write to it (using mprotect on Unices and VirtualProtect on Windows) and then modifies the first 5 to 14 bytes to be an unconditional jump instruction. It puts the address of a generated (using templates) function with identical signature in the place, effectively overriding the function.
If you want you can reuse HippoMocks' code directly, by constructing an object of class Replace on the stack with the right arguments. You can also copy out the code (in the newest hippomocks.h on GitHub both 32/64 bit x86, ARM and thumb are supported). It is around line 200, so relatively high up. You'll need to also copy out the horrible_cast class and the Unprotect class; the first allows it to cast a member function pointer to any other type (which is not possible with reinterpret_cast) and the second wraps the OS-specific unprotect (and reprotect) calls.
In cleaning up the code for C++11 I've also extracted exactly this subset, so you can now use the detail/replace.h file to get just the code that does this. For a direct link, look at https://github.com/dascandy/hippomocks/blob/cpp11/HippoMocks/detail/replace.h .
The code which does the interception is in hippomocks.h
. It modifies the memory protection flags to allow writing to the address of the provided function pointer, then writes a jump instruction in place of the initial bytes of the function. When the hook is no longer needed, the original bytes are restored. This is the same approach used, for example, by the Microsoft Detours library.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With