todo
[hband-ld-preload-libs.git] / src / pathrewrite.c
blob0ede31a3f78738aded2ed8c0657aa145bf7ed339
1 /**
2 * pathrewrite.c
4 * Compile with: gcc -D _GNU_SOURCE -shared -fPIC -o pathrewrite.so pathrewrite.c
6 * Usage: LD_PRELOAD=./pathrewrite.so PATHREWRITE_FROM=/usr/bin PATHREWRITE_TO=/usr/local/bin someprogramm ...
7 */
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <dlfcn.h>
12 #include <string.h>
13 #include <bits/posix1_lim.h>
16 void pathrewrite_rewrite(const char *orig, char *rw, const char *caller_name)
18 char temp[_POSIX_PATH_MAX];
19 char *pattern;
20 char *newstring;
21 char *index;
23 strcpy(rw, orig);
24 pattern = getenv("PATHREWRITE_FROM");
25 newstring = getenv("PATHREWRITE_TO");
27 if(pattern != NULL && newstring != NULL)
29 index = strstr(rw, pattern);
30 if(index != NULL)
32 //fprintf(stderr, "index = %s\n", index);
33 strcpy(temp, &index[strlen(pattern)]);
34 strcpy(index, newstring);
35 strcpy(&index[strlen(newstring)], temp);
36 fprintf(stderr, "pathrewrite.so: %s(%s -> %s)\n", caller_name, orig, rw);
42 int __xstat(int ver, const char *path, struct stat *buf)
44 char pathrw[_POSIX_PATH_MAX];
46 pathrewrite_rewrite(path, pathrw, __func__);
48 int (*orig___xstat)(int, const char *, struct stat *) = dlsym(RTLD_NEXT, "__xstat");
49 return orig___xstat(ver, pathrw, buf);
52 int __lxstat(int ver, const char *path, struct stat *buf)
54 char pathrw[_POSIX_PATH_MAX];
56 pathrewrite_rewrite(path, pathrw, __func__);
58 int (*orig___lxstat)(int, const char *, struct stat *) = dlsym(RTLD_NEXT, "__lxstat");
59 return orig___lxstat(ver, pathrw, buf);
62 int open(const char *pathname, int flags, mode_t mode)
64 char pathrw[_POSIX_PATH_MAX];
66 pathrewrite_rewrite(pathname, pathrw, __func__);
68 int (*orig_open)(const char *, int, mode_t) = dlsym(RTLD_NEXT, "open");
69 return orig_open(pathrw, flags, mode);
72 int open64(const char *pathname, int flags, mode_t mode)
74 char pathrw[_POSIX_PATH_MAX];
76 pathrewrite_rewrite(pathname, pathrw, __func__);
78 int (*orig_open64)(const char *, int, mode_t) = dlsym(RTLD_NEXT, "open64");
79 return orig_open64(pathrw, flags, mode);
82 int __open_2(const char* pathname, int flags)
84 char pathrw[_POSIX_PATH_MAX];
86 pathrewrite_rewrite(pathname, pathrw, __func__);
88 int (*orig___open_2)(const char *, int) = dlsym(RTLD_NEXT, "__open_2");
89 return orig___open_2(pathrw, flags);
92 FILE *fopen(__const char *__restrict pathname, __const char *__restrict mode)
94 char pathrw[_POSIX_PATH_MAX];
96 pathrewrite_rewrite(pathname, pathrw, __func__);
98 FILE *(*orig_fopen)(__const char *__restrict, __const char *__restrict) = dlsym(RTLD_NEXT, "fopen");
99 return orig_fopen(pathrw, mode);