subhook/README.md

73 lines
1.6 KiB
Markdown
Raw Normal View History

2013-06-26 14:15:37 +07:00
[SubHook][github] is a super-simple hooking library for C/C++ that works on
2013-12-05 23:51:57 +07:00
both Linux and Windows. It currently supports only x86 and x86-64.
2013-06-26 14:15:37 +07:00
2013-01-14 00:02:16 +07:00
Examples
--------
2013-09-26 20:44:02 +00:00
In the following examples `foo` is some function or a function pointer that
takes a single argument of type `int` and uses the same calling convention
as `my_foo` (depends on compiler).
2013-01-15 04:40:12 +07:00
2013-01-14 00:02:16 +07:00
### C
```c
2013-01-15 04:40:12 +07:00
#include <stdio.h>
2013-01-14 00:02:16 +07:00
#include <subhook.h>
2013-12-06 00:00:59 +07:00
subhook_t foo_hook;
2013-01-14 00:02:16 +07:00
2013-01-15 04:40:12 +07:00
void my_foo(int x) {
2013-01-14 00:02:16 +07:00
/* Sometimes you want to call the original function. */
subhook_remove(foo_hook);
2013-01-15 04:40:12 +07:00
printf("foo(%d) called\n", x);
foo(x);
2013-01-14 00:02:16 +07:00
/* Install the hook back again to intercept further calls. */
subhook_install(foo_hook);
}
int main() {
foo_hook = subhook_new();
2013-01-15 04:40:12 +07:00
/* The "source" is the function that we want to hook. */
2013-01-15 04:02:06 +07:00
subhook_set_src((void*)foo);
2013-01-14 00:02:16 +07:00
2013-01-15 04:40:12 +07:00
/* The "destination" is the function that will get called instead of the
* original function. */
2013-01-15 04:02:06 +07:00
subhook_set_dst((void*)my_foo);
2013-01-14 00:02:16 +07:00
/* Install our newly created hook so from now on any call to foo()
2013-12-05 02:04:59 +07:00
* will be redirected to my_foo(). */
2013-01-14 00:02:16 +07:00
subhook_install(foo_hook);
2013-12-05 02:04:59 +07:00
/* Free the memory when you're done. */
subhook_free(foo_hook);
2013-01-14 00:02:16 +07:00
}
```
### C++
```c++
2013-01-15 04:40:12 +07:00
#include <iostream>
2013-01-14 00:02:16 +07:00
#include <subhook.h>
SubHook foo_hook;
2013-01-15 04:40:12 +07:00
void my_foo(int x) {
2013-01-15 05:14:54 +07: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-14 00:02:16 +07:00
2013-01-15 04:40:12 +07:00
std::cout << "foo(" << x < ") called" << std::endl;
foo(x);
2013-01-14 00:02:16 +07:00
}
int main() {
2013-05-17 19:57:53 +03:00
foo_hook.Install((void*)foo, (void*)my_foo);
2013-01-14 00:02:16 +07:00
}
```
2013-01-15 04:40:12 +07:00
[github]: https://github.com/Zeex/subhook