Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to intercept a free function call like hippomocks does?

Tags:

c++

hippomocks

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());
like image 463
Guillaume Paris Avatar asked Dec 19 '22 12:12

Guillaume Paris


2 Answers

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 .

like image 135
dascandy Avatar answered Jan 25 '23 23:01

dascandy


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.

like image 22
Dark Falcon Avatar answered Jan 25 '23 23:01

Dark Falcon