Ticket #12427: relocation-test.c

File relocation-test.c, 2.0 KB (added by simonsouth, 9 years ago)

Demonstration program that illustrates runtime_loader's relocation behaviour

Line 
1#include <kernel/OS.h>
2#include <kernel/image.h>
3
4#include <stdio.h>
5
6/* This program outputs information about its own areas, illustrating how
7 * runtime_loader randomly positions (or not) program segments read
8 * from executables on disk.
9 *
10 * To compile as a position-independent ("DYN") executable:
11 *
12 * gcc -o relocation-test relocation-test.c
13 *
14 * To compile as a fixed-position ("EXEC") executable (until gcc is patched):
15 *
16 * gcc -### -fno-pie -o relocation-test relocation-test.c 2>&1 \
17 * | grep '^\s' | sed -e 's/-shared//g' | bash -s
18 *
19 * The current runtime_loader will execute the program when it is built as a
20 * position-independent executable. When it's built as a fixed-position
21 * executable runtime_loader will erroneously insist on relocating the
22 * program's code anyway, leading to a crash.
23 *
24 * With the patch applied runtime_loader will execute the program correctly in
25 * both cases.
26 *
27 * Compare this program's output to the output of "readelf -l relocation-test"
28 * to see how this program's LOAD segments (prefixed in memory with
29 * "relocation-test_seg") are randomly positioned in the first case but loaded
30 * at a fixed address (matching the position specified in the ELF header,
31 * rounded down to the closest page boundary) in the latter.
32 */
33
34int
35main (int argc, char **argv) {
36 int32 image_cookie = 0;
37 image_info i_info;
38
39 ssize_t area_cookie = 0;
40 area_info a_info;
41 uint area_number = 0;
42
43 /* Find our app image */
44 while (get_next_image_info(0, &image_cookie, &i_info) == B_OK)
45 if (i_info.type == B_APP_IMAGE)
46 /* Output information about where our areas (including our text and
47 * data segments) were loaded */
48 while (get_next_area_info (0, &area_cookie, &a_info) == B_OK)
49 printf (" %2i: %s (%s%s)\n"
50 " Addr: %018p Size: 0x%08zx RAM: 0x%08x\n"
51 "\n",
52 ++area_number,
53 a_info.name,
54 (a_info.protection & B_READ_AREA ? "r" : ""),
55 (a_info.protection & B_WRITE_AREA ? "w" : "o"),
56 a_info.address,
57 a_info.size,
58 a_info.ram_size);
59
60 return 0;
61}