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