summaryrefslogtreecommitdiff
path: root/libcap/execable.h
blob: 3dff1e99a76118150c2a451c38fa7a009bca304d (plain)
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
/*
 * Copyright (c) 2021 Andrew G. Morgan <morgan@kernel.org>
 *
 * Some header magic to help make a shared object run-able as a stand
 * alone executable binary.
 *
 * This is a slightly more sophisticated implementation than the
 * answer I posted here:
 *
 *    https://stackoverflow.com/a/68339111/14760867
 *
 * Compile your shared library with:
 *
 *   -DSHARED_LOADER="\"ld-linux...\"" (loader for your target system)
 *   ...
 *   --entry=__so_start
 */
#include <stdlib.h>
#include <string.h>

#ifdef __EXECABLE_H
#error "only inlcude execable.h once"
#endif
#define __EXECABLE_H

const char __execable_dl_loader[] __attribute((section(".interp"))) =
    SHARED_LOADER ;

static void __execable_parse_args(int *argc_p, char ***argv_p)
{
    int argc = 0;
    char **argv = NULL;
    FILE *f = fopen("/proc/self/cmdline", "rb");
    if (f != NULL) {
	char *mem = NULL, *p;
	size_t size = 32, offset;
	for (offset=0; ; size *= 2) {
	    mem = realloc(mem, size+1);
	    if (mem == NULL) {
		perror("unable to parse arguments");
		exit(1);
	    }
	    offset += fread(mem+offset, 1, size-offset, f);
	    if (offset < size) {
		size = offset;
		mem[size] = '\0';
		break;
	    }
	}
	fclose(f);
	for (argc=1, p=mem+size-2; p >= mem; p--) {
	    argc += (*p == '\0');
	}
	argv = calloc(argc+1, sizeof(char *));
	if (argv == NULL) {
	    perror("failed to allocate memory for argv");
	    exit(1);
	}
	for (p=mem, argc=0, offset=0; offset < size; argc++) {
	    argv[argc] = mem+offset;
	    offset += strlen(mem+offset)+1;
	}
    }
    *argc_p = argc;
    *argv_p = argv;
}

/*
 * Note, to avoid any runtime confusion, SO_MAIN is a void static
 * function.
 */

#define SO_MAIN						        \
static void __execable_main(int, char**);                       \
extern void __so_start(void);		                	\
void __so_start(void)                                           \
{                                                               \
    int argc;                                                   \
    char **argv;                                                \
    __execable_parse_args(&argc, &argv);                        \
    __execable_main(argc, argv);				\
    exit(0);                                                    \
}                                                               \
static void __execable_main