perl version of histogram prog
[tridge/junkcode.git] / preload_open.c
1 /*
2   compile like this:
3
4   gcc -c -fPIC preload_open.c
5   ld -shared -o preload_open.so preload_open.o -ldl
6   
7   export LD_PRELOAD=/etc/magic/preload_open.so 
8   myapp ARGS
9
10 */
11
12
13 #include <sys/mman.h>
14 #include <sys/types.h>
15 #include <dlfcn.h>
16 #include <fcntl.h>
17 #include <stdarg.h>
18 #include <stdlib.h>
19 #include <errno.h>
20 #include <stdio.h>
21
22 static void do_magic(const char *pathname)
23 {
24         const char *magic_script;
25         char *s = NULL;
26         magic_script = getenv("MAGIC_SCRIPT");
27
28         unlink("xxx.dat");
29
30         if (!magic_script) {
31                 return;
32         }
33
34         asprintf(&s, "%s '%s'", magic_script, pathname);
35
36         if (!s) {
37                 return;
38         }
39         
40         printf("doing magic '%s'\n", magic_script);
41
42         system(s);
43         free(s);
44 }
45
46 int open64(const char *pathname, int flags, ...)
47 {
48         static int in_open;
49         va_list ap;
50         static int (*real_open)(const char *, int, mode_t );
51         int ret;
52         mode_t mode;
53
54         va_start(ap, flags);
55         mode = va_arg(ap, mode_t);
56         va_end(ap);
57
58         if (in_open) {
59                 return real_open(pathname, flags, mode);
60         }
61
62         in_open = 1;
63
64         if (!real_open) {
65                 real_open = dlsym((void *)-1, "open64");
66         }
67
68         ret = real_open(pathname, flags, mode);
69
70                 do_magic(pathname);
71
72         if (ret == -1 && errno == ENOENT) {
73                 do_magic(pathname);
74                 ret = real_open(pathname, flags, mode);
75         }
76
77         in_open = 0;
78
79         return ret;
80 }
81
82
83 int open(const char *pathname, int flags, ...)
84 {
85         static int in_open;
86         va_list ap;
87         static int (*real_open)(const char *, int, mode_t );
88         int ret;
89         mode_t mode;
90
91         va_start(ap, flags);
92         mode = va_arg(ap, mode_t);
93         va_end(ap);
94
95         if (in_open) {
96                 return real_open(pathname, flags, mode);
97         }
98
99         in_open++;
100
101         if (!real_open) {
102                 real_open = dlsym((void *)-1, "open");
103         }
104
105         ret = real_open(pathname, flags, mode);
106
107                 do_magic(pathname);
108
109         if (ret == -1 && errno == ENOENT) {
110                 do_magic(pathname);
111                 ret = real_open(pathname, flags, mode);
112         }
113
114         in_open--;
115
116         return ret;
117 }