-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.c
91 lines (81 loc) · 1.94 KB
/
main.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/mman.h>
#include <err.h>
#include <dasm_proto.h>
#include <dasm_x86.h>
Dst_DECL;
#include "dummy.c"
#define GLOB__MAX 8
static long get_page_size()
{
static long sz;
if (0 == sz)
sz = sysconf(_SC_PAGESIZE);
return sz;
}
static size_t round_up_to_page_size(size_t size)
{
long sz = get_page_size();
size_t remainder;
remainder = size % sz;
return size + sz - remainder;
}
static void *create_code_mapping(size_t size)
{
void *ptr;
size = round_up_to_page_size(size);
ptr = mmap(NULL, size, PROT_READ | PROT_WRITE,
MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
if (MAP_FAILED == ptr)
err(EXIT_FAILURE, "mmap");
return ptr;
}
static void protect_code_mapping(void *addr, size_t size)
{
int retval;
size = round_up_to_page_size(size);
retval = mprotect(addr, size, PROT_READ | PROT_EXEC);
if (retval)
err(EXIT_FAILURE, "mprotect");
}
static void destroy_code_mapping(void *ptr, size_t size)
{
int retval;
size = round_up_to_page_size(size);
retval = munmap(ptr, size);
if (retval)
err(EXIT_FAILURE, "munmap");
}
int main() {
int retval;
void *buf;
size_t size;
int i;
int nglob = GLOB__MAX;
void **glob = (void **)malloc(nglob * sizeof(void *));
int (*my_function)();
memset(glob, 0x00, nglob * sizeof(void *));
Dst = malloc(sizeof(*Dst));
dasm_init(Dst, 10);
dasm_setupglobal(Dst, glob, GLOB__MAX);
dasm_setup(Dst, my_actionlist);
create_my_function();
retval = dasm_link(Dst, &size);
printf("dasm_link returned %d\n", retval);
buf = create_code_mapping(size);
retval = dasm_encode(Dst, buf);
printf("dasm_encode returned %d\n", retval);
protect_code_mapping(buf, size);
for (i = 0; i < nglob; i++)
printf("glob[%d] = %p\n", i, glob[i]);
my_function = (int (*)())glob[0];
printf("going to call my_function\n");
retval = my_function();
printf("my_function has returned: %d\n", retval);
destroy_code_mapping(buf, size);
dasm_free(Dst);
free(Dst);
return 0;
}