]> ruderich.org/simon Gitweb - coloredstderr/coloredstderr.git/blob - src/trackfds.h
5720b0cca54cc6d159ec8d760d35ae5883878509
[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     assert(count > 0);
55
56     /* Reduce reallocs. */
57     count += TRACKFDS_REALLOC_STEP;
58
59     tracked_fds_list = malloc(count * sizeof(*tracked_fds_list));
60     if (!tracked_fds_list) {
61 #ifdef WARNING
62         warning("malloc(tracked_fds_list, %d) failed [%d]\n",
63                 count * sizeof(*tracked_fds_list), getpid());
64 #endif
65         return 0;
66     }
67
68     tracked_fds_list_space = count;
69     return 1;
70 }
71
72 /* Load tracked file descriptors from the environment. The environment is used
73  * to pass the information to child processes.
74  *
75  * ENV_NAME_FDS and ENV_NAME_PRIVATE_FDS have the following format: Each
76  * descriptor as string followed by a comma; there's a trailing comma.
77  * Example: "2,4,". */
78 static void init_from_environment(void) {
79 #ifdef DEBUG
80     debug("init_from_environment()\t\t[%d]\n", getpid());
81 #endif
82     char const *env;
83
84     int saved_errno = errno;
85
86     assert(!initialized);
87
88     initialized = 1;
89     tracked_fds_list_count = 0;
90
91     /* If ENV_NAME_FORCE_WRITE is set and not empty, allow writes to a non-tty
92      * device. Use with care! Mainly used for the test suite. */
93     env = getenv(ENV_NAME_FORCE_WRITE);
94     if (env && env[0] != '\0') {
95         force_write_to_non_tty = 1;
96     }
97
98     /* Prefer user defined list of file descriptors, fall back to file
99      * descriptors passed through the environment from the parent process. */
100     env = getenv(ENV_NAME_FDS);
101     if (env) {
102         used_fds_set_by_user = 1;
103     } else {
104         env = getenv(ENV_NAME_PRIVATE_FDS);
105     }
106     if (!env) {
107         errno = saved_errno;
108         return;
109     }
110 #ifdef DEBUG
111     debug("  getenv(\"%s\"): \"%s\"\n", ENV_NAME_FDS, env);
112     debug("  getenv(\"%s\"): \"%s\"\n", ENV_NAME_PRIVATE_FDS, env);
113 #endif
114
115     /* Environment must be treated read-only. */
116     char env_copy[strlen(env) + 1];
117     strcpy(env_copy, env);
118
119     char *x;
120
121     size_t count = 0;
122     for (x = env_copy; *x; x++) {
123         if (*x == ',') {
124             count++;
125         }
126     }
127
128     size_t i = 0;
129
130     /* Parse file descriptor numbers from environment string and store them as
131      * integers in tracked_fds and tracked_fds_list. */
132     char *last;
133     for (x = env_copy, last = env_copy; *x; x++) {
134         if (*x != ',') {
135             continue;
136         }
137         /* ',' at the beginning or double ',' - ignore. */
138         if (x == last) {
139             goto next;
140         }
141
142         if (i == count) {
143             break;
144         }
145
146         /* Replace ',' to null-terminate number for atoi(). */
147         *x = 0;
148
149         int fd = atoi(last);
150         if (fd < 0) {
151             goto next;
152
153         } else if (fd < TRACKFDS_STATIC_COUNT) {
154             tracked_fds[fd] = 1;
155         } else {
156             if (!tracked_fds_list) {
157                 /* Pessimistic count estimate, but allocating a few more
158                  * elements doesn't hurt. */
159                 if (!init_tracked_fds_list(count)) {
160                     /* Couldn't allocate memory, skip this entry. */
161                     goto next;
162                 }
163             }
164             tracked_fds_list[i++] = fd;
165 #ifdef DEBUG
166             debug("  large fd: %d\n", fd);
167 #endif
168         }
169
170 next:
171         last = x + 1;
172     }
173
174     tracked_fds_list_count = i;
175
176 #ifdef DEBUG
177     tracked_fds_debug();
178 #endif
179
180     errno = saved_errno;
181 }
182
183 static char *update_environment_buffer_entry(char *x, int fd) {
184     assert(fd >= 0);
185
186     int length = snprintf(x, 10 + 1, "%d", fd);
187     if (length >= 10 + 1 || length <= 0 /* shouldn't happen */) {
188         /* Integer too big to fit the buffer, skip it. */
189 #ifdef WARNING
190         warning("update_environment_buffer_entry(): truncated fd: %d [%d]\n",
191                 fd, getpid());
192 #endif
193         return x;
194     }
195
196     /* Write comma after number. */
197     x += length;
198     *x++ = ',';
199     /* Make sure the string is always null-terminated. */
200     *x = 0;
201
202     return x;
203 }
204 static void update_environment_buffer(char *x) {
205     assert(initialized);
206
207     size_t i;
208     for (i = 0; i < TRACKFDS_STATIC_COUNT; i++) {
209         if (tracked_fds[i]) {
210             x = update_environment_buffer_entry(x, (int)i);
211         }
212     }
213     for (i = 0; i < tracked_fds_list_count; i++) {
214         x = update_environment_buffer_entry(x, tracked_fds_list[i]);
215     }
216 }
217 inline static size_t update_environment_buffer_size(void) {
218     assert(initialized);
219
220     /* Use the maximum count (TRACKFDS_STATIC_COUNT) of used descriptors
221      * because it's simple and small enough not to be a problem.
222      *
223      * An integer (32-bit) has at most 10 digits, + 1 for the comma after each
224      * number. Bigger file descriptors (which shouldn't occur in reality) are
225      * skipped. */
226     return (TRACKFDS_STATIC_COUNT + tracked_fds_list_count)
227                * (10 + 1) + 1 /* to fit '\0' */;
228 }
229 static void update_environment(void) {
230 #ifdef DEBUG
231     debug("update_environment()\t\t[%d]\n", getpid());
232 #endif
233
234     /* If we haven't parsed the environment we also haven't modified it - so
235      * nothing to do. */
236     if (!initialized) {
237         return;
238     }
239
240     int saved_errno = errno;
241
242     char env[update_environment_buffer_size()];
243     env[0] = 0;
244
245     update_environment_buffer(env);
246
247 #if 0
248     debug("    setenv(\"%s\", \"%s\", 1)\n", ENV_NAME_PRIVATE_FDS, env);
249 #endif
250     setenv(ENV_NAME_PRIVATE_FDS, env, 1 /* overwrite */);
251
252     /* Child processes must use ENV_NAME_PRIVATE_FDS to get the updated list
253      * of tracked file descriptors, not the static list provided by the user
254      * in ENV_NAME_FDS.
255      *
256      * But only remove it if the static list in ENV_NAME_FDS was loaded by
257      * init_from_environment() and merged into ENV_NAME_PRIVATE_FDS. */
258     if (used_fds_set_by_user) {
259         unsetenv(ENV_NAME_FDS);
260     }
261
262     errno = saved_errno;
263 }
264
265
266
267 static void tracked_fds_add(int fd) {
268     assert(fd >= 0);
269
270     if (fd < TRACKFDS_STATIC_COUNT) {
271         tracked_fds[fd] = 1;
272 #if 0
273         debug("tracked_fds_add(): %-3d\t\t[%d]\n", fd, getpid());
274         tracked_fds_debug();
275 #endif
276         return;
277     }
278
279     if (tracked_fds_list_count >= tracked_fds_list_space) {
280         int saved_errno = errno;
281
282         size_t new_space = tracked_fds_list_space + TRACKFDS_REALLOC_STEP;
283         int *tmp = realloc(tracked_fds_list,
284                            sizeof(*tracked_fds_list) * new_space);
285         if (!tmp) {
286             /* We can do nothing, just ignore the error. We made sure not to
287              * destroy our state, so the new descriptor is ignored without any
288              * other consequences. */
289 #ifdef WARNING
290             warning("realloc(tracked_fds_list, %zu) failed! [%d]\n",
291                     sizeof(*tracked_fds_list) * new_space, getpid());
292 #endif
293             errno = saved_errno;
294             return;
295         }
296         errno = saved_errno;
297
298         tracked_fds_list = tmp;
299         tracked_fds_list_space = new_space;
300     }
301
302     tracked_fds_list[tracked_fds_list_count++] = fd;
303
304 #ifdef DEBUG
305     debug("tracked_fds_add(): %-3d\t\t[%d]\n", fd, getpid());
306     tracked_fds_debug();
307 #endif
308 }
309 static int tracked_fds_remove(int fd) {
310     assert(fd >= 0);
311
312     if (fd < TRACKFDS_STATIC_COUNT) {
313         int old_value = tracked_fds[fd];
314         tracked_fds[fd] = 0;
315
316 #if 0
317         debug("tracked_fds_remove(): %-3d\t[%d]\n", fd, getpid());
318         tracked_fds_debug();
319 #endif
320         return old_value; /* Found vs. not found. */
321     }
322
323     size_t i;
324     for (i = 0; i < tracked_fds_list_count; i++) {
325         if (fd != tracked_fds_list[i]) {
326             continue;
327         }
328
329         memmove(tracked_fds_list + i, tracked_fds_list + i + 1,
330                 sizeof(*tracked_fds_list) * (tracked_fds_list_count - i - 1));
331         tracked_fds_list_count--;
332
333 #ifdef DEBUG
334         debug("tracked_fds_remove(): %-3d\t[%d]\n", fd, getpid());
335         tracked_fds_debug();
336 #endif
337
338         /* Found. */
339         return 1;
340     }
341
342     /* Not found. */
343     return 0;
344 }
345
346 static int tracked_fds_find_slow(int fd) noinline;
347 /*
348  * tracked_fds_find() is called for each hook call and should be as fast as
349  * possible. As most file descriptors are < TRACKFDS_STATIC_COUNT, force the
350  * compiler to inline that part which is almost exclusively used.
351  *
352  * Inlining tracked_fds_add()/tracked_fds_remove() isn't worth the effort as
353  * they are not called often enough.
354  */
355 inline static int tracked_fds_find(int fd) always_inline;
356 inline static int tracked_fds_find(int fd) {
357     /* Invalid file descriptor. No assert() as we're called from the hooked
358      * macro. */
359     if (unlikely(fd < 0)) {
360         return 0;
361     }
362
363     if (fd < TRACKFDS_STATIC_COUNT) {
364         return tracked_fds[fd];
365     }
366
367     return tracked_fds_find_slow(fd);
368 }
369 static int tracked_fds_find_slow(int fd) {
370     assert(initialized);
371     assert(fd >= 0);
372
373     if (tracked_fds_list_count == 0) {
374         return 0;
375     }
376
377     size_t i;
378     for (i = 0; i < tracked_fds_list_count; i++) {
379         if (fd == tracked_fds_list[i]) {
380             return 1;
381         }
382     }
383     return 0;
384 }
385
386 #endif