]> ruderich.org/simon Gitweb - coloredstderr/coloredstderr.git/blob - src/trackfds.h
1eede800ddcd745f7e8eb1a4595157260bf74131
[coloredstderr/coloredstderr.git] / src / trackfds.h
1 /*
2  * Utility functions to track file descriptors.
3  *
4  * Copyright (C) 2013  Simon Ruderich
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 #ifndef TRACKFDS_H
21 #define TRACKFDS_H 1
22
23 /* Array of tracked file descriptors. Used for fast lookups for the normally
24  * used file descriptors (0 <= fd < TRACKFDS_STATIC_COUNT). */
25 static int tracked_fds[TRACKFDS_STATIC_COUNT];
26
27 /* List of tracked file descriptors >= TRACKFDS_STATIC_COUNT. */
28 static int *tracked_fds_list;
29 /* Current number of items in the list. */
30 static size_t tracked_fds_list_count;
31 /* Allocated items, used to reduce realloc()s. */
32 static size_t tracked_fds_list_space;
33
34
35 #ifdef DEBUG
36 static void tracked_fds_debug(void) {
37     size_t i;
38
39     for (i = 0; i < TRACKFDS_STATIC_COUNT; i++) {
40         if (tracked_fds[i]) {
41             debug("    tracked_fds[%d]: %d\n", i, tracked_fds[i]);
42         }
43     }
44     debug("    tracked_fds_list: %d/%d\t[%d]\n", tracked_fds_list_count,
45                                                  tracked_fds_list_space,
46                                                  getpid());
47     for (i = 0; i < tracked_fds_list_count; i++) {
48         debug("    tracked_fds_list[%d]: %d\n", i, tracked_fds_list[i]);
49     }
50 }
51 #endif
52
53 static int init_tracked_fds_list(size_t count) {
54     /* Reduce reallocs. */
55     count += TRACKFDS_REALLOC_STEP;
56
57     tracked_fds_list = malloc(count * sizeof(*tracked_fds_list));
58     if (!tracked_fds_list) {
59 #ifdef WARNING
60         warning("malloc(tracked_fds_list, %d) failed [%d]\n",
61                 count * sizeof(*tracked_fds_list), getpid());
62 #endif
63         return 0;
64     }
65
66     tracked_fds_list_space = count;
67     return 1;
68 }
69
70 /* Load tracked file descriptors from the environment. The environment is used
71  * to pass the information to child processes.
72  *
73  * ENV_NAME_FDS has the following format: Each descriptor as string followed
74  * by a comma; there's a trailing comma. Example: "2,4,". */
75 static void init_from_environment(void) {
76 #ifdef DEBUG
77     debug("init_from_environment()\t\t[%d]\n", getpid());
78 #endif
79     char const *env;
80
81     int saved_errno = errno;
82
83     initialized = 1;
84     tracked_fds_list_count = 0;
85
86     /* If ENV_NAME_FORCE_WRITE is set and not empty, allow writes to a non-tty
87      * device. Use with care! Mainly used for the test suite. */
88     env = getenv(ENV_NAME_FORCE_WRITE);
89     if (env && env[0] != '\0') {
90         force_write_to_non_tty = 1;
91     }
92
93     env = getenv(ENV_NAME_FDS);
94     if (!env) {
95         errno = saved_errno;
96         return;
97     }
98     /* Environment is read-only. */
99     char env_copy[strlen(env) + 1];
100     strcpy(env_copy, env);
101
102     char *x;
103
104     size_t count = 0;
105     for (x = env_copy; *x; x++) {
106         if (*x == ',') {
107             count++;
108         }
109     }
110
111     size_t i = 0;
112
113     /* Parse file descriptor numbers from environment string and store them as
114      * integers in tracked_fds and tracked_fds_list. */
115     char *last;
116     for (x = env_copy, last = env_copy; *x; x++) {
117         if (*x != ',') {
118             continue;
119         }
120         /* ',' at the beginning or double ',' - ignore. */
121         if (x == last) {
122             last = x + 1;
123             continue;
124         }
125
126         if (i == count) {
127             break;
128         }
129
130         *x = 0;
131
132         int fd = atoi(last);
133         if (fd < TRACKFDS_STATIC_COUNT) {
134             tracked_fds[fd] = 1;
135         } else {
136             if (!tracked_fds_list) {
137                 /* Pessimistic count estimate, but allocating a few more
138                  * elements doesn't hurt. */
139                 if (!init_tracked_fds_list(count)) {
140                     /* Couldn't allocate memory, skip this entry. */
141                     goto next;
142                 }
143             }
144             tracked_fds_list[i++] = fd;
145 #ifdef DEBUG
146             debug("  large fd: %d\n", fd);
147 #endif
148         }
149
150 next:
151         last = x + 1;
152     }
153
154     tracked_fds_list_count = i;
155
156 #ifdef DEBUG
157     tracked_fds_debug();
158 #endif
159
160     errno = saved_errno;
161 }
162
163 static char *update_environment_buffer_entry(char *x, int fd) {
164     int length = snprintf(x, 10 + 1, "%d", fd);
165     if (length >= 10 + 1) {
166         /* Integer too big to fit the buffer, skip it. */
167 #ifdef WARNING
168         warning("update_environment_buffer_entry(): truncated fd: %d [%d]\n",
169                 fd, getpid());
170 #endif
171         return x;
172     }
173
174     /* Write comma after number. */
175     x += length;
176     *x++ = ',';
177     /* Make sure the string is always zero terminated. */
178     *x = 0;
179
180     return x;
181 }
182 static void update_environment_buffer(char *x) {
183     size_t i;
184     for (i = 0; i < TRACKFDS_STATIC_COUNT; i++) {
185         if (tracked_fds[i]) {
186             x = update_environment_buffer_entry(x, (int)i);
187         }
188     }
189     for (i = 0; i < tracked_fds_list_count; i++) {
190         x = update_environment_buffer_entry(x, tracked_fds_list[i]);
191     }
192 }
193 inline static size_t update_environment_buffer_size(void) {
194     /* Use the maximum count (TRACKFDS_STATIC_COUNT) of used descriptors
195      * because it's simple and small enough not to be a problem.
196      *
197      * An integer (32-bit) has at most 10 digits, + 1 for the comma after each
198      * number. Bigger file descriptors (which shouldn't occur in reality) are
199      * skipped. */
200     return (TRACKFDS_STATIC_COUNT + tracked_fds_list_count)
201                * (10 + 1) + 1 /* to fit '\0' */;
202 }
203 static void update_environment(void) {
204 #ifdef DEBUG
205     debug("update_environment()\t\t[%d]\n", getpid());
206 #endif
207
208     /* If we haven't parsed the environment we also haven't modified it - so
209      * nothing to do. */
210     if (!initialized) {
211         return;
212     }
213
214     char env[update_environment_buffer_size()];
215     env[0] = 0;
216
217     update_environment_buffer(env);
218
219 #if 0
220     debug("    setenv('%s', '%s', 1)\n", ENV_NAME_FDS, env);
221 #endif
222
223     setenv(ENV_NAME_FDS, env, 1 /* overwrite */);
224 }
225
226
227
228 static void tracked_fds_add(int fd) {
229     if (fd < TRACKFDS_STATIC_COUNT) {
230         tracked_fds[fd] = 1;
231 #if 0
232         debug("tracked_fds_add(): %-3d\t\t[%d]\n", fd, getpid());
233         tracked_fds_debug();
234 #endif
235         return;
236     }
237
238     if (tracked_fds_list_count >= tracked_fds_list_space) {
239         int saved_errno = errno;
240
241         size_t new_space = tracked_fds_list_space + TRACKFDS_REALLOC_STEP;
242         int *tmp = realloc(tracked_fds_list,
243                            sizeof(*tracked_fds_list) * new_space);
244         if (!tmp) {
245             /* We can do nothing, just ignore the error. We made sure not to
246              * destroy our state, so the new descriptor is ignored without any
247              * other consequences. */
248 #ifdef WARNING
249             warning("realloc(tracked_fds_list, %zu) failed! [%d]\n",
250                     sizeof(*tracked_fds_list) * new_space, getpid());
251 #endif
252             errno = saved_errno;
253             return;
254         }
255         errno = saved_errno;
256
257         tracked_fds_list = tmp;
258         tracked_fds_list_space = new_space;
259     }
260
261     tracked_fds_list[tracked_fds_list_count++] = fd;
262
263 #ifdef DEBUG
264     debug("tracked_fds_add(): %-3d\t\t[%d]\n", fd, getpid());
265     tracked_fds_debug();
266 #endif
267 }
268 static int tracked_fds_remove(int fd) {
269     if (fd < TRACKFDS_STATIC_COUNT) {
270         int old_value = tracked_fds[fd];
271         tracked_fds[fd] = 0;
272
273 #if 0
274         debug("tracked_fds_remove(): %-3d\t[%d]\n", fd, getpid());
275         tracked_fds_debug();
276 #endif
277         return old_value; /* Found vs. not found. */
278     }
279
280     size_t i;
281     for (i = 0; i < tracked_fds_list_count; i++) {
282         if (fd != tracked_fds_list[i]) {
283             continue;
284         }
285
286         memmove(tracked_fds_list + i, tracked_fds_list + i + 1,
287                 sizeof(*tracked_fds_list) * (tracked_fds_list_count - i - 1));
288         tracked_fds_list_count--;
289
290 #ifdef DEBUG
291         debug("tracked_fds_remove(): %-3d\t[%d]\n", fd, getpid());
292         tracked_fds_debug();
293 #endif
294
295         /* Found. */
296         return 1;
297     }
298
299     /* Not found. */
300     return 0;
301 }
302
303 static int tracked_fds_find_slow(int fd) noinline;
304 /*
305  * tracked_fds_find() is called for each hook call and should be as fast as
306  * possible. As most file descriptors are < TRACKFDS_STATIC_COUNT, force the
307  * compiler to inline that part which is almost exclusively used.
308  *
309  * Inlining tracked_fds_add()/tracked_fds_remove() isn't worth the effort as
310  * they are not called often enough.
311  */
312 inline static int tracked_fds_find(int fd) always_inline;
313 static int tracked_fds_find(int fd) {
314     if (fd < TRACKFDS_STATIC_COUNT) {
315         return tracked_fds[fd];
316     }
317
318     return tracked_fds_find_slow(fd);
319 }
320 static int tracked_fds_find_slow(int fd) {
321     if (tracked_fds_list_count == 0) {
322         return 0;
323     }
324
325     size_t i;
326     for (i = 0; i < tracked_fds_list_count; i++) {
327         if (fd == tracked_fds_list[i]) {
328             return 1;
329         }
330     }
331     return 0;
332 }
333
334 #endif