subhook/README.md

77 lines
1.8 KiB
Markdown
Raw Normal View History

2013-01-14 21:40:12 +00:00
[SubHook][github] is a super-simple library for setting function hooks at run
time and it works on both Linux and Windows. Currently only x86 is supported
but the API is easily portable to other architectures.
2013-01-13 15:15:49 +00:00
2013-01-13 17:02:16 +00:00
Examples
--------
2013-01-14 21:40:12 +00:00
In the following examples `foo` is a hypothetical function or function pointer
that takes a single argument `int x` and uses the same calling convention as
`my_foo` (for instance, on x86 most compilers use the [`cdecl`][cdecl] calling
convention unless you specify otherwise).
2013-01-13 17:02:16 +00:00
### C
```c
2013-01-14 21:40:12 +00:00
#include <stdio.h>
2013-01-13 17:02:16 +00:00
#include <subhook.h>
struct subhook *foo_hook;
2013-01-14 21:40:12 +00:00
void my_foo(int x) {
2013-01-13 17:02:16 +00:00
/* Sometimes you want to call the original function. */
subhook_remove(foo_hook);
2013-01-14 21:40:12 +00:00
printf("foo(%d) called\n", x);
foo(x);
2013-01-13 17:02:16 +00:00
/* Install the hook back again to intercept further calls. */
subhook_install(foo_hook);
}
int main() {
foo_hook = subhook_new();
2013-01-14 21:40:12 +00:00
/* The "source" is the function that we want to hook. */
2013-01-14 21:02:06 +00:00
subhook_set_src((void*)foo);
2013-01-13 17:02:16 +00:00
2013-01-14 21:40:12 +00:00
/* The "destination" is the function that will get called instead of the
* original function. */
2013-01-14 21:02:06 +00:00
subhook_set_dst((void*)my_foo);
2013-01-13 17:02:16 +00:00
/* Install our newly created hook so from now on any call to foo()
* will be redirected to my_foo(). */
subhook_install(foo_hook);
/* Free the memory when you're done. */
subhook_free(foo_hook);
2013-01-13 17:02:16 +00:00
}
```
### C++
```c++
2013-01-14 21:40:12 +00:00
#include <iostream>
2013-01-13 17:02:16 +00:00
#include <subhook.h>
SubHook foo_hook;
2013-01-14 21:40:12 +00:00
void my_foo(int x) {
2013-01-14 22:14:54 +00:00
// ScopedRemove removes the specified hook and automatically re-installs it
// when it goes out of scope (thanks to C++ destructors).
SubHook::ScopedRemove remove(&foo_hook);
2013-01-13 17:02:16 +00:00
2013-01-14 21:40:12 +00:00
std::cout << "foo(" << x < ") called" << std::endl;
foo(x);
2013-01-13 17:02:16 +00:00
}
int main() {
hook.Install((void*)foo, (void*)my_foo);
}
```
2013-01-14 21:40:12 +00:00
[github]: https://github.com/Zeex/subhook
[cdecl]: http://en.wikipedia.org/wiki/X86_calling_conventions#cdecl