1 #define _GNU_SOURCE
3 #include <dirent.h>
4 #include <dlfcn.h>
5 #include <errno.h>
6 #include <error.h>
7 #include <stdio.h>
8 #include <string.h>
10 #define PREFIX "/rootfs"
11 #define BUFSIZE 256
13 const char *add_prefix(const char *orig, char *prefixed) {
14 if ((strncmp(orig, "/proc", strlen("/proc")) != 0) &&
15 (strncmp(orig, "/sys", strlen("/sys")) != 0))
16 return orig;
18 int status = snprintf(prefixed, BUFSIZE, "%s%s", PREFIX, orig);
19 if (status < 1) {
20 error(status, errno, "adding '%s' prefix to file path failed: '%s' -> '%s'",
21 PREFIX, orig, prefixed);
22 return orig;
23 } else if ((unsigned int)status >= BUFSIZE) {
24 error(status, ENAMETOOLONG,
25 "'%s' got truncated when adding '%s' prefix: '%s'", orig, PREFIX,
26 prefixed);
27 return orig;
28 } else {
29 return (const char *)prefixed;
30 }
31 }
33 FILE *fopen(const char *path, const char *mode) {
34 char filename[BUFSIZE] = "\0";
36 FILE *(*original_fopen)(const char *, const char *);
37 original_fopen = dlsym(RTLD_NEXT, "fopen");
39 return (*original_fopen)(add_prefix(path, filename), mode);
40 }
42 DIR *opendir(const char *name) {
43 char filename[BUFSIZE] = "\0";
45 DIR *(*original_opendir)(const char *);
46 original_opendir = dlsym(RTLD_NEXT, "opendir");
48 return (*original_opendir)(add_prefix(name, filename));
49 }
51 int *open(const char *pathname, int flags) {
52 char filename[BUFSIZE] = "\0";
54 int *(*original_open)(const char *, int);
55 original_open = dlsym(RTLD_NEXT, "open");
57 return (*original_open)(add_prefix(pathname, filename), flags);
58 }