]> ruderich.org/simon Gitweb - coloredstderr/coloredstderr.git/blob - src/coloredstderr.c
Use likely()/unlikely() macros to improve branch prediction.
[coloredstderr/coloredstderr.git] / src / coloredstderr.c
1 /*
2  * Hook output functions (like printf(3)) with LD_PRELOAD to color stderr (or
3  * other file descriptors).
4  *
5  * Copyright (C) 2013  Simon Ruderich
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation, either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19  */
20
21 #include <config.h>
22
23 /* Must be loaded before the following headers. */
24 #include "ldpreload.h"
25
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <stdarg.h>
29 #include <stdio.h>
30 #include <string.h>
31 #include <unistd.h>
32
33 #ifdef HAVE_ERROR_H
34 # include <error.h>
35 #endif
36
37 /* Conflicting declaration in glibc. */
38 #undef fwrite_unlocked
39
40
41 /* Used by various functions, including debug(). */
42 static ssize_t (*real_write)(int, void const *, size_t);
43 static int (*real_close)(int);
44 static size_t (*real_fwrite)(void const *, size_t, size_t, FILE *);
45
46 /* Did we already (try to) parse the environment and setup the necessary
47  * variables? */
48 static int initialized;
49 /* Force hooked writes even when not writing to a tty. Used for tests. */
50 static int force_write_to_non_tty;
51
52
53 #include "constants.h"
54 #include "compiler.h"
55 #ifdef DEBUG
56 # include "debug.h"
57 #endif
58
59 #include "hookmacros.h"
60 #include "trackfds.h"
61
62
63
64 /* See hookmacros.h for the decision if a function call is colored. */
65
66
67 static void dup_fd(int oldfd, int newfd) {
68 #ifdef DEBUG
69     debug("%3d -> %3d\t\t\t[%d]\n", oldfd, newfd, getpid());
70 #endif
71
72     if (unlikely(!initialized)) {
73         init_from_environment();
74     }
75
76     /* We are already tracking this file descriptor, add newfd to the list as
77      * it will reference the same descriptor. */
78     if (tracked_fds_find(oldfd)) {
79         if (!tracked_fds_find(newfd)) {
80             tracked_fds_add(newfd);
81         }
82     /* We are not tracking this file descriptor, remove newfd from the list
83      * (if present). */
84     } else {
85         tracked_fds_remove(newfd);
86     }
87 }
88
89 static void close_fd(int fd) {
90 #ifdef DEBUG
91     debug("%3d ->   .\t\t\t[%d]\n", fd, getpid());
92 #endif
93
94     if (unlikely(!initialized)) {
95         init_from_environment();
96     }
97
98     tracked_fds_remove(fd);
99 }
100
101
102 /* "Action" handlers called when a file descriptor is matched. */
103
104 static char const *pre_string;
105 static size_t pre_string_size;
106 static char const *post_string;
107 static size_t post_string_size;
108
109 /* Load alternative pre/post strings from the environment if available, fall
110  * back to default values. */
111 inline static void init_pre_post_string(void) {
112     pre_string = getenv(ENV_NAME_PRE_STRING);
113     if (!pre_string) {
114         pre_string = DEFAULT_PRE_STRING;
115     }
116     pre_string_size = strlen(pre_string);
117
118     post_string = getenv(ENV_NAME_POST_STRING);
119     if (!post_string) {
120         post_string = DEFAULT_POST_STRING;
121     }
122     post_string_size = strlen(post_string);
123 }
124
125 static void handle_fd_pre(int fd) {
126     int saved_errno = errno;
127
128     if (unlikely(!pre_string || !post_string)) {
129         init_pre_post_string();
130     }
131
132     DLSYM_FUNCTION(real_write, "write");
133     real_write(fd, pre_string, pre_string_size);
134
135     errno = saved_errno;
136 }
137 static void handle_fd_post(int fd) {
138     int saved_errno = errno;
139
140     /* write() already loaded above in handle_fd_pre(). */
141     real_write(fd, post_string, post_string_size);
142
143     errno = saved_errno;
144 }
145
146 static void handle_file_pre(FILE *stream) {
147     int saved_errno = errno;
148
149     if (unlikely(!pre_string || !post_string)) {
150         init_pre_post_string();
151     }
152
153     DLSYM_FUNCTION(real_fwrite, "fwrite");
154     real_fwrite(pre_string, pre_string_size, 1, stream);
155
156     errno = saved_errno;
157 }
158 static void handle_file_post(FILE *stream) {
159     int saved_errno = errno;
160
161     /* fwrite() already loaded above in handle_file_pre(). */
162     real_fwrite(post_string, post_string_size, 1, stream);
163
164     errno = saved_errno;
165 }
166
167
168
169 /* Hook all important output functions to manipulate their output. */
170
171 HOOK_FD3(ssize_t, write, fd,
172          int, fd, void const *, buf, size_t, count)
173 HOOK_FILE4(size_t, fwrite, stream,
174            void const *, ptr, size_t, size, size_t, nmemb, FILE *, stream)
175
176 /* puts(3) */
177 HOOK_FILE2(int, fputs, stream,
178            char const *, s, FILE *, stream)
179 HOOK_FILE2(int, fputc, stream,
180            int, c, FILE *, stream)
181 HOOK_FILE2(int, putc, stream,
182            int, c, FILE *, stream)
183 HOOK_FILE1(int, putchar, stdout,
184            int, c)
185 HOOK_FILE1(int, puts, stdout,
186            char const *, s)
187
188 /* printf(3), excluding all s*() and vs*() functions (no output) */
189 HOOK_VAR_FILE1(int, printf, stdout, vprintf,
190                char const *, format)
191 HOOK_VAR_FILE2(int, fprintf, stream, vfprintf,
192                FILE *, stream, char const *, format)
193 HOOK_FILE2(int, vprintf, stdout,
194            char const *, format, va_list, ap)
195 HOOK_FILE3(int, vfprintf, stream,
196            FILE *, stream, char const *, format, va_list, ap)
197 /* Hardening functions (-D_FORTIFY_SOURCE=2), only functions from above */
198 HOOK_VAR_FILE2(int, __printf_chk, stdout, __vprintf_chk,
199                int, flag, char const *, format)
200 HOOK_VAR_FILE3(int, __fprintf_chk, fp, __vfprintf_chk,
201                FILE *, fp, int, flag, char const *, format)
202 HOOK_FILE3(int, __vprintf_chk, stdout,
203            int, flag, char const *, format, va_list, ap)
204 HOOK_FILE4(int, __vfprintf_chk, stream,
205            FILE *, stream, int, flag, char const *, format, va_list, ap)
206
207 /* unlocked_stdio(3), only functions from above are hooked */
208 HOOK_FILE4(size_t, fwrite_unlocked, stream,
209            void const *, ptr, size_t, size, size_t, nmemb, FILE *, stream)
210 HOOK_FILE2(int, fputs_unlocked, stream,
211            char const *, s, FILE *, stream)
212 HOOK_FILE2(int, fputc_unlocked, stream,
213            int, c, FILE *, stream)
214 HOOK_FILE2(int, putc_unlocked, stream,
215            int, c, FILE *, stream)
216 HOOK_FILE1(int, putchar_unlocked, stdout,
217            int, c)
218
219 /* perror(3) */
220 HOOK_VOID1(void, perror, STDERR_FILENO,
221            char const *, s)
222
223 /* error(3) */
224 #ifdef HAVE_ERROR_H
225 static void  error_vararg(int status, int errnum,
226                    char const *filename, unsigned int linenum,
227                    char const *format, va_list ap) {
228     static char const *last_filename;
229     static unsigned int last_linenum;
230
231     /* Skip this error message if requested and if there was already an error
232      * in the same file/line. */
233     if (error_one_per_line
234             && filename != NULL && linenum != 0
235             && filename == last_filename && linenum == last_linenum) {
236         return;
237     }
238     last_filename = filename;
239     last_linenum  = linenum;
240
241     error_message_count++;
242
243     fflush(stdout);
244
245     if (error_print_progname) {
246         error_print_progname();
247     } else {
248         fprintf(stderr, "%s:", program_invocation_name);
249     }
250     if (filename != NULL && linenum != 0) {
251         fprintf(stderr, "%s:%u:", filename, linenum);
252         if (error_print_progname) {
253             fprintf(stderr, " ");
254         }
255     }
256     if (!error_print_progname) {
257         fprintf(stderr, " ");
258     }
259
260
261     vfprintf(stderr, format, ap);
262
263     if (errnum != 0) {
264         fprintf(stderr, ": %s", strerror(errnum));
265     }
266
267     fprintf(stderr, "\n");
268
269     if (status != 0) {
270         exit(status);
271     }
272 }
273 void error_at_line(int status, int errnum,
274                    char const *filename, unsigned int linenum,
275                    char const *format, ...) {
276     va_list ap;
277
278     va_start(ap, format);
279     error_vararg(status, errnum, filename, linenum, format, ap);
280     va_end(ap);
281 }
282 void error(int status, int errnum, char const *format, ...) {
283     va_list ap;
284
285     va_start(ap, format);
286     error_vararg(status, errnum, NULL, 0, format, ap);
287     va_end(ap);
288 }
289 #endif
290
291
292 /* Hook functions which duplicate file descriptors to track them. */
293
294 static int (*real_dup)(int);
295 static int (*real_dup2)(int, int);
296 static int (*real_dup3)(int, int, int);
297 int dup(int oldfd) {
298     int newfd;
299
300     DLSYM_FUNCTION(real_dup, "dup");
301
302     newfd = real_dup(oldfd);
303     if (newfd != -1) {
304         dup_fd(oldfd, newfd);
305     }
306
307     return newfd;
308 }
309 int dup2(int oldfd, int newfd) {
310     DLSYM_FUNCTION(real_dup2, "dup2");
311
312     newfd = real_dup2(oldfd, newfd);
313     if (newfd != -1) {
314         dup_fd(oldfd, newfd);
315     }
316
317     return newfd;
318 }
319 int dup3(int oldfd, int newfd, int flags) {
320     DLSYM_FUNCTION(real_dup3, "dup3");
321
322     newfd = real_dup3(oldfd, newfd, flags);
323     if (newfd != -1) {
324         dup_fd(oldfd, newfd);
325     }
326
327     return newfd;
328 }
329
330 static int (*real_fcntl)(int, int, ...);
331 int fcntl(int fd, int cmd, ...) {
332     int result;
333     va_list ap;
334
335     DLSYM_FUNCTION(real_fcntl, "fcntl");
336
337     /* fcntl() takes different types of arguments depending on the cmd type
338      * (int, void and pointers are used at the moment). Handling these
339      * arguments for different systems and with possible changes in the future
340      * is error prone.
341      *
342      * Therefore always retrieve a void-pointer from our arguments (even if it
343      * wasn't there) and pass it to real_fcntl(). This shouldn't cause any
344      * problems because a void-pointer is most-likely bigger than an int
345      * (something which is not true in reverse) and shouldn't cause
346      * truncation. For register based calling conventions an invalid register
347      * content is passed, but ignored by real_fcntl(). Not perfect, but should
348      * work fine.
349      */
350     va_start(ap, cmd);
351     result = real_fcntl(fd, cmd, va_arg(ap, void *));
352     va_end(ap);
353
354     /* We only care about duping fds. */
355     if (cmd == F_DUPFD && result != -1) {
356         dup_fd(fd, result);
357     }
358
359     return result;
360 }
361
362 static int (*real_close)(int);
363 int close(int fd) {
364     DLSYM_FUNCTION(real_close, "close");
365
366     close_fd(fd);
367     return real_close(fd);
368 }
369 static int (*real_fclose)(FILE *);
370 int fclose(FILE *fp) {
371     DLSYM_FUNCTION(real_fclose, "fclose");
372
373     close_fd(fileno(fp));
374     return real_fclose(fp);
375 }
376
377
378 /* Hook functions which are necessary for correct tracking. */
379
380 #if defined(HAVE_VFORK) && defined(HAVE_FORK)
381 pid_t vfork(void) {
382     /* vfork() is similar to fork() but the address space is shared between
383      * father and child. It's designed for fork()/exec() usage because it's
384      * faster than fork(). However according to the POSIX standard the "child"
385      * isn't allowed to perform any memory-modifications before the exec()
386      * (except the pid_t result variable of vfork()).
387      *
388      * As some programs don't adhere to the standard (e.g. the "child" closes
389      * or dups a descriptor before the exec()) and this breaks our tracking of
390      * file descriptors (e.g. it gets closed in the parent as well), we just
391      * fork() instead. This is in compliance with the POSIX standard and as
392      * most systems use copy-on-write anyway not a performance issue. */
393     return fork();
394 }
395 #endif
396
397
398 /* Hook execve() and the other exec*() functions. Some shells use exec*() with
399  * a custom environment which doesn't necessarily contain our updates to
400  * ENV_NAME_FDS. It's also faster to update the environment only when
401  * necessary, right before the exec() to pass it to the new process. */
402
403 static int (*real_execve)(char const *filename, char * const argv[], char * const env[]);
404 int execve(char const *filename, char * const argv[], char * const env[]) {
405     DLSYM_FUNCTION(real_execve, "execve");
406
407     int found = 0;
408     size_t index = 0;
409
410     /* Count arguments and search for existing ENV_NAME_FDS environment
411      * variable. */
412     size_t count = 0;
413     char * const *x = env;
414     while (*x) {
415         if (!strncmp(*x, ENV_NAME_FDS "=", strlen(ENV_NAME_FDS) + 1)) {
416             found = 1;
417             index = count;
418         }
419
420         x++;
421         count++;
422     }
423     /* Terminating NULL. */
424     count++;
425
426     char *env_copy[count + 1 /* space for our new entry if necessary */];
427     memcpy(env_copy, env, count * sizeof(char *));
428
429     /* Make sure the information from the environment is loaded. We can't just
430      * do nothing (like update_environment()) because the caller might pass a
431      * different environment which doesn't include any of our settings. */
432     if (!initialized) {
433         init_from_environment();
434     }
435
436     char fds_env[strlen(ENV_NAME_FDS) + 1 + update_environment_buffer_size()];
437     strcpy(fds_env, ENV_NAME_FDS "=");
438     update_environment_buffer(fds_env + strlen(ENV_NAME_FDS) + 1);
439
440     if (found) {
441         env_copy[index] = fds_env;
442     } else {
443         /* If the process removed ENV_NAME_FDS from the environment, re-add
444          * it. */
445         env_copy[count-1] = fds_env;
446         env_copy[count] = NULL;
447     }
448
449     return real_execve(filename, argv, env_copy);
450 }
451
452 #define EXECL_COPY_VARARGS_START(args) \
453     va_list ap; \
454     char *x; \
455     \
456     /* Count arguments. */ \
457     size_t count = 1; /* arg */ \
458     va_start(ap, arg); \
459     while (va_arg(ap, char const *)) { \
460         count++; \
461     } \
462     va_end(ap); \
463     \
464     /* Copy varargs. */ \
465     char *args[count + 1 /* terminating NULL */]; \
466     args[0] = (char *)arg; \
467     \
468     size_t i = 1; \
469     va_start(ap, arg); \
470     while ((x = va_arg(ap, char *))) { \
471         args[i++] = x; \
472     } \
473     args[i] = NULL;
474 #define EXECL_COPY_VARARGS_END(args) \
475     va_end(ap);
476 #define EXECL_COPY_VARARGS(args) \
477     EXECL_COPY_VARARGS_START(args); \
478     EXECL_COPY_VARARGS_END(args);
479
480 int execl(char const *path, char const *arg, ...) {
481     EXECL_COPY_VARARGS(args);
482
483     update_environment();
484     return execv(path, args);
485 }
486
487 int execlp(char const *file, char const *arg, ...) {
488     EXECL_COPY_VARARGS(args);
489
490     update_environment();
491     return execvp(file, args);
492 }
493
494 int execle(char const *path, char const *arg, ... /*, char * const envp[] */) {
495     EXECL_COPY_VARARGS_START(args);
496     /* Get envp[] located after arguments. */
497     char * const *envp = va_arg(ap, char * const *);
498     EXECL_COPY_VARARGS_END(args);
499
500     return execve(path, args, envp);
501 }
502
503 static int (*real_execv)(char const *path, char * const argv[]);
504 int execv(char const *path, char * const argv[]) {
505     DLSYM_FUNCTION(real_execv, "execv");
506
507     update_environment();
508     return real_execv(path, argv);
509 }
510
511 static int (*real_execvp)(char const *path, char * const argv[]);
512 int execvp(char const *path, char * const argv[]) {
513     DLSYM_FUNCTION(real_execvp, "execvp");
514
515     update_environment();
516     return real_execvp(path, argv);
517 }