-
Notifications
You must be signed in to change notification settings - Fork 30
/
test.c
71 lines (47 loc) · 1.55 KB
/
test.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <stdio.h>
#include <dlfcn.h>
#include "mach_hook.h"
void libtest(); //from libtest.dylib
int hooked_puts(char const *s)
{
puts(s); //calls the original puts() from libSystem.B.dylib, because our main executable module called "test" remains intact
return puts("HOOKED!");
}
int main()
{
void *handle = 0; //handle to store hook-related info
mach_substitution original; //original data for restoration
Dl_info info;
if (!dladdr((void const *)libtest, &info)) //gets an address and a path of a target library
{
fprintf(stderr, "Failed to get the base address of a library at `%s`!\n", info.dli_fname);
goto end;
}
handle = mach_hook_init(info.dli_fname, info.dli_fbase);
if (!handle)
{
fprintf(stderr, "Redirection init failed!\n");
goto end;
}
libtest(); //calls puts() from libSystem.B.dylib
puts("-----------------------------");
original = mach_hook(handle, "puts", (mach_substitution)hooked_puts);
if (!original)
{
fprintf(stderr, "Redirection failed!\n");
goto end;
}
libtest(); //calls hooked_puts()
puts("-----------------------------");
original = mach_hook(handle, "puts", original); //restores the original relocation
if (!original)
{
fprintf(stderr, "Restoration failed!\n");
goto end;
}
libtest(); //again calls puts() from libSystem.B.dylib
end:
mach_hook_free(handle);
handle = 0; //no effect here, but just a good advice to prevent double freeing
return 0;
}