1 | #include <stdint.h> |
---|---|
2 | #include <stdio.h> |
3 | #include <string.h> |
4 | #include <sys/mman.h> |
5 | #include <unistd.h> |
6 | |
7 | extern uint8_t __start_target_section[]; |
8 | extern uint8_t __stop_target_section[]; |
9 | |
10 | __attribute__((used, section("target_section"))) int target_function(void) { |
11 | return 42; |
12 | } |
13 | |
14 | typedef int (*target_function_t)(void); |
15 | |
16 | int main(void) { |
17 | size_t target_function_size = __stop_target_section - __start_target_section; |
18 | size_t page_size = sysconf(_SC_PAGESIZE); |
19 | size_t page_aligned_size = |
20 | (target_function_size + page_size - 1) & ~(page_size - 1); |
21 | |
22 | void *executable_memory = |
23 | mmap(NULL, len: page_aligned_size, PROT_READ | PROT_WRITE | PROT_EXEC, |
24 | MAP_PRIVATE | MAP_ANONYMOUS, fd: -1, offset: 0); |
25 | if (executable_memory == MAP_FAILED) { |
26 | perror(s: "mmap"); |
27 | return 1; |
28 | } |
29 | |
30 | memcpy(dest: executable_memory, src: __start_target_section, n: target_function_size); |
31 | |
32 | target_function_t func = (target_function_t)executable_memory; |
33 | int result = func(); // Break here |
34 | printf(format: "Result from target function: %d\n", result); |
35 | |
36 | return 0; |
37 | } |
38 |