]> ruderich.org/simon Gitweb - coloredstderr/coloredstderr.git/blob - src/coloredstderr.c
Also hook un-macroed putc when it's a macro.
[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 #include "compiler.h"
24
25 /* Must be loaded before the following headers. */
26 #include "ldpreload.h"
27
28 /* Disable assert()s if not compiled with --enable-debug. */
29 #ifndef DEBUG
30 # define NDEBUG
31 #endif
32
33 #include <assert.h>
34 #include <errno.h>
35 #include <fcntl.h>
36 #include <stdarg.h>
37 #include <stdio.h>
38 #include <string.h>
39 #include <sys/stat.h>
40 #include <unistd.h>
41
42 #ifdef HAVE_ERR_H
43 # include <err.h>
44 #endif
45 #ifdef HAVE_ERROR_H
46 # include <error.h>
47 #endif
48 #ifdef HAVE_STRUCT__IO_FILE__FILENO
49 # include <libio.h>
50 #endif
51
52 /* The following functions may be macros. Undefine them or they cause build
53  * failures when used in our hook macros below. */
54
55 /* In glibc, real fwrite_unlocked() is called in macro. */
56 #ifdef HAVE_FWRITE_UNLOCKED
57 # undef fwrite_unlocked
58 #endif
59 /* In Clang when compiling with hardening flags (fortify) on Debian Wheezy. */
60 #undef printf
61 #undef fprintf
62 /* On FreeBSD (9.1), __swbuf() is used instead of these macros. */
63 #ifdef HAVE___SWBUF
64 # undef putc
65 # undef putc_unlocked
66 # undef putchar
67 # undef putchar_unlocked
68 #endif
69
70
71 /* Used by various functions, including debug(). */
72 static ssize_t (*real_write)(int, void const *, size_t);
73 static int (*real_close)(int);
74 static size_t (*real_fwrite)(void const *, size_t, size_t, FILE *);
75
76 /* Did we already (try to) parse the environment and setup the necessary
77  * variables? */
78 static int initialized;
79 /* Force hooked writes even when not writing to a tty. Used for tests. */
80 static int force_write_to_non_tty;
81 /* Was ENV_NAME_FDS found and used when init_from_environment() was called?
82  * This is not true if the process set it manually after initialization. */
83 static int used_fds_set_by_user;
84
85
86 #include "constants.h"
87 #ifdef WARNING
88 # include "debug.h"
89 #endif
90
91 #include "hookmacros.h"
92 #include "trackfds.h"
93
94
95
96 /* See hookmacros.h for the decision if a function call is colored. */
97
98
99 /* Prevent inlining into hook functions because it may increase the number of
100  * spilled registers unnecessarily. As it's not called very often accept the
101  * additional call. */
102 static int isatty_noinline(int fd) noinline;
103 static int isatty_noinline(int fd) {
104     assert(fd >= 0);
105
106     int saved_errno = errno;
107     int result = isatty(fd);
108     errno = saved_errno;
109
110     return result;
111 }
112
113
114 static void dup_fd(int oldfd, int newfd) {
115 #ifdef DEBUG
116     debug("%3d -> %3d\t\t\t[%d]\n", oldfd, newfd, getpid());
117 #endif
118
119     assert(oldfd >= 0 && newfd >= 0);
120
121     if (unlikely(!initialized)) {
122         init_from_environment();
123     }
124
125     /* We are already tracking this file descriptor, add newfd to the list as
126      * it will reference the same descriptor. */
127     if (tracked_fds_find(oldfd)) {
128         if (!tracked_fds_find(newfd)) {
129             tracked_fds_add(newfd);
130         }
131     /* We are not tracking this file descriptor, remove newfd from the list
132      * (if present). */
133     } else {
134         tracked_fds_remove(newfd);
135     }
136 }
137
138 static void close_fd(int fd) {
139 #ifdef DEBUG
140     debug("%3d ->   .\t\t\t[%d]\n", fd, getpid());
141 #endif
142
143     assert(fd >= 0);
144
145     if (unlikely(!initialized)) {
146         init_from_environment();
147     }
148
149     tracked_fds_remove(fd);
150 }
151
152
153 /* "Action" handlers called when a file descriptor is matched. */
154
155 static char const *pre_string;
156 static size_t pre_string_size;
157 static char const *post_string;
158 static size_t post_string_size;
159
160 /* Load alternative pre/post strings from the environment if available, fall
161  * back to default values. */
162 static void init_pre_post_string(void) {
163     pre_string = getenv(ENV_NAME_PRE_STRING);
164     if (!pre_string) {
165         pre_string = DEFAULT_PRE_STRING;
166     }
167     pre_string_size = strlen(pre_string);
168
169     post_string = getenv(ENV_NAME_POST_STRING);
170     if (!post_string) {
171         post_string = DEFAULT_POST_STRING;
172     }
173     post_string_size = strlen(post_string);
174 }
175
176 /* Don't inline any of the pre/post functions. Keep the hook function as small
177  * as possible for speed reasons. */
178 static void handle_fd_pre(int fd) noinline;
179 static void handle_fd_post(int fd) noinline;
180 static void handle_file_pre(FILE *stream) noinline;
181 static void handle_file_post(FILE *stream) noinline;
182
183 static void handle_fd_pre(int fd) {
184     int saved_errno = errno;
185
186     if (unlikely(!pre_string || !post_string)) {
187         init_pre_post_string();
188     }
189
190     DLSYM_FUNCTION(real_write, "write");
191     real_write(fd, pre_string, pre_string_size);
192
193     errno = saved_errno;
194 }
195 static void handle_fd_post(int fd) {
196     int saved_errno = errno;
197
198     /* write() already loaded above in handle_fd_pre(). */
199     real_write(fd, post_string, post_string_size);
200
201     errno = saved_errno;
202 }
203
204 static void handle_file_pre(FILE *stream) {
205     int saved_errno = errno;
206
207     if (unlikely(!pre_string || !post_string)) {
208         init_pre_post_string();
209     }
210
211     DLSYM_FUNCTION(real_fwrite, "fwrite");
212     real_fwrite(pre_string, pre_string_size, 1, stream);
213
214     errno = saved_errno;
215 }
216 static void handle_file_post(FILE *stream) {
217     int saved_errno = errno;
218
219     /* fwrite() already loaded above in handle_file_pre(). */
220     real_fwrite(post_string, post_string_size, 1, stream);
221
222     errno = saved_errno;
223 }
224
225
226
227 /* Hook all important output functions to manipulate their output. */
228
229 HOOK_FD3(ssize_t, write, fd,
230          int, fd, void const *, buf, size_t, count)
231 HOOK_FILE4(size_t, fwrite, stream,
232            void const *, ptr, size_t, size, size_t, nmemb, FILE *, stream)
233
234 /* puts(3) */
235 HOOK_FILE2(int, fputs, stream,
236            char const *, s, FILE *, stream)
237 HOOK_FILE2(int, fputc, stream,
238            int, c, FILE *, stream)
239 HOOK_FILE2(int, putc, stream,
240            int, c, FILE *, stream)
241 /* The glibc uses a macro for putc() which expands to _IO_putc(). However
242  * sometimes the raw putc() is used as well, not sure why. Make sure to hook
243  * it too. */
244 #ifdef putc
245 # undef putc
246 HOOK_FILE2(int, putc, stream,
247            int, c, FILE *, stream)
248 #endif
249 HOOK_FILE1(int, putchar, stdout,
250            int, c)
251 HOOK_FILE1(int, puts, stdout,
252            char const *, s)
253
254 /* printf(3), excluding all s*() and vs*() functions (no output) */
255 HOOK_VAR_FILE1(int, printf, stdout, vprintf,
256                char const *, format)
257 HOOK_VAR_FILE2(int, fprintf, stream, vfprintf,
258                FILE *, stream, char const *, format)
259 HOOK_FILE2(int, vprintf, stdout,
260            char const *, format, va_list, ap)
261 HOOK_FILE3(int, vfprintf, stream,
262            FILE *, stream, char const *, format, va_list, ap)
263 /* Hardening functions (-D_FORTIFY_SOURCE=2), only functions from above */
264 HOOK_VAR_FILE2(int, __printf_chk, stdout, __vprintf_chk,
265                int, flag, char const *, format)
266 HOOK_VAR_FILE3(int, __fprintf_chk, fp, __vfprintf_chk,
267                FILE *, fp, int, flag, char const *, format)
268 HOOK_FILE3(int, __vprintf_chk, stdout,
269            int, flag, char const *, format, va_list, ap)
270 HOOK_FILE4(int, __vfprintf_chk, stream,
271            FILE *, stream, int, flag, char const *, format, va_list, ap)
272
273 /* unlocked_stdio(3), only functions from above are hooked */
274 #ifdef HAVE_FWRITE_UNLOCKED
275 HOOK_FILE4(size_t, fwrite_unlocked, stream,
276            void const *, ptr, size_t, size, size_t, nmemb, FILE *, stream)
277 #endif
278 #ifdef HAVE_FPUTS_UNLOCKED
279 HOOK_FILE2(int, fputs_unlocked, stream,
280            char const *, s, FILE *, stream)
281 #endif
282 #ifdef HAVE_FPUTC_UNLOCKED
283 HOOK_FILE2(int, fputc_unlocked, stream,
284            int, c, FILE *, stream)
285 #endif
286 HOOK_FILE2(int, putc_unlocked, stream,
287            int, c, FILE *, stream)
288 HOOK_FILE1(int, putchar_unlocked, stdout,
289            int, c)
290 /* glibc defines (_IO_)putc_unlocked() to a macro which either updates the
291  * output buffer or calls __overflow(). As this code is inlined we can't
292  * handle the first case, but if __overflow() is called we can color that
293  * part. As writes to stderr are never buffered, __overflow() is always called
294  * and everything works fine. This is only a problem if stdout is dupped to
295  * stderr (which shouldn't be the case too often). */
296 #if defined(HAVE_STRUCT__IO_FILE__FILENO) && defined(HAVE___OVERFLOW)
297 /* _IO_FILE is glibc's representation of FILE. */
298 HOOK_FILE2(int, __overflow, f, _IO_FILE *, f, int, ch)
299 #endif
300 /* Same for FreeBSD's libc. However it's more aggressive: The inline writing
301  * and __swbuf() are also used for normal output (e.g. putc()). Writing to
302  * stderr is still fine; it always calls __swbuf() as stderr is always
303  * unbufferd. */
304 #ifdef HAVE___SWBUF
305 HOOK_FILE2(int, __swbuf, f, int, c, FILE *, f)
306 #endif
307
308 /* perror(3) */
309 HOOK_VOID1(void, perror, STDERR_FILENO,
310            char const *, s)
311
312 /* err(3), non standard BSD extension */
313 #ifdef HAVE_ERR_H
314 HOOK_VAR_VOID2(void, err, STDERR_FILENO, verr,
315                int, eval, char const *, fmt)
316 HOOK_VAR_VOID2(void, errx, STDERR_FILENO, verrx,
317                int, eval, char const *, fmt)
318 HOOK_VAR_VOID1(void, warn, STDERR_FILENO, vwarn,
319                char const *, fmt)
320 HOOK_VAR_VOID1(void, warnx, STDERR_FILENO, vwarnx,
321                char const *, fmt)
322 HOOK_FUNC_SIMPLE3(void, verr, int, eval, const char *, fmt, va_list, args) {
323     /* Can't use verr() directly as it terminates the process which prevents
324      * the post string from being printed. */
325     vwarn(fmt, args);
326     exit(eval);
327 }
328 HOOK_FUNC_SIMPLE3(void, verrx, int, eval, const char *, fmt, va_list, args) {
329     /* See verr(). */
330     vwarnx(fmt, args);
331     exit(eval);
332 }
333 HOOK_VOID2(void, vwarn, STDERR_FILENO,
334            char const *, fmt, va_list, args)
335 HOOK_VOID2(void, vwarnx, STDERR_FILENO,
336            char const *, fmt, va_list, args)
337 #endif
338
339 /* error(3), non-standard GNU extension */
340 #ifdef HAVE_ERROR_H
341 static void error_vararg(int status, int errnum,
342                          char const *filename, unsigned int linenum,
343                          char const *format, va_list ap) {
344     static char const *last_filename;
345     static unsigned int last_linenum;
346
347     /* Skip this error message if requested and if there was already an error
348      * in the same file/line. */
349     if (error_one_per_line
350             && filename != NULL && linenum != 0
351             && filename == last_filename && linenum == last_linenum) {
352         return;
353     }
354     last_filename = filename;
355     last_linenum  = linenum;
356
357     error_message_count++;
358
359     fflush(stdout);
360
361     if (error_print_progname) {
362         error_print_progname();
363     } else {
364         fprintf(stderr, "%s:", program_invocation_name);
365     }
366     if (filename != NULL && linenum != 0) {
367         fprintf(stderr, "%s:%u:", filename, linenum);
368         if (error_print_progname) {
369             fprintf(stderr, " ");
370         }
371     }
372     if (!error_print_progname) {
373         fprintf(stderr, " ");
374     }
375
376
377     vfprintf(stderr, format, ap);
378
379     if (errnum != 0) {
380         fprintf(stderr, ": %s", strerror(errnum));
381     }
382
383     fprintf(stderr, "\n");
384
385     if (status != 0) {
386         exit(status);
387     }
388 }
389 void error_at_line(int status, int errnum,
390                    char const *filename, unsigned int linenum,
391                    char const *format, ...) {
392     va_list ap;
393
394     va_start(ap, format);
395     error_vararg(status, errnum, filename, linenum, format, ap);
396     va_end(ap);
397 }
398 void error(int status, int errnum, char const *format, ...) {
399     va_list ap;
400
401     va_start(ap, format);
402     error_vararg(status, errnum, NULL, 0, format, ap);
403     va_end(ap);
404 }
405 #endif
406
407
408 /* Hook functions which duplicate file descriptors to track them. */
409
410 /* int dup(int) */
411 HOOK_FUNC_DEF1(int, dup, int, oldfd) {
412     int newfd;
413
414     DLSYM_FUNCTION(real_dup, "dup");
415
416     newfd = real_dup(oldfd);
417     if (newfd > -1) {
418         dup_fd(oldfd, newfd);
419     }
420
421     return newfd;
422 }
423 /* int dup2(int, int) */
424 HOOK_FUNC_DEF2(int, dup2, int, oldfd, int, newfd) {
425     DLSYM_FUNCTION(real_dup2, "dup2");
426
427     newfd = real_dup2(oldfd, newfd);
428     if (newfd > -1) {
429         dup_fd(oldfd, newfd);
430     }
431
432     return newfd;
433 }
434 /* int dup3(int, int, int) */
435 HOOK_FUNC_DEF3(int, dup3, int, oldfd, int, newfd, int, flags) {
436     DLSYM_FUNCTION(real_dup3, "dup3");
437
438     newfd = real_dup3(oldfd, newfd, flags);
439     if (newfd > -1) {
440         dup_fd(oldfd, newfd);
441     }
442
443     return newfd;
444 }
445
446 /* int fcntl(int, int, ...) */
447 HOOK_FUNC_VAR_DEF2(int, fcntl, int, fd, int, cmd /*, ... */) {
448     int result;
449     va_list ap;
450
451     DLSYM_FUNCTION(real_fcntl, "fcntl");
452
453     /* fcntl() takes different types of arguments depending on the cmd type
454      * (int, void and pointers are used at the moment). Handling these
455      * arguments for different systems and with possible changes in the future
456      * is error prone.
457      *
458      * Therefore always retrieve a void-pointer from our arguments (even if it
459      * wasn't there) and pass it to real_fcntl(). This shouldn't cause any
460      * problems because a void-pointer is most-likely bigger than an int
461      * (something which is not true in reverse) and shouldn't cause
462      * truncation. For register based calling conventions an invalid register
463      * content is passed, but ignored by real_fcntl(). Not perfect, but should
464      * work fine.
465      */
466     va_start(ap, cmd);
467     result = real_fcntl(fd, cmd, va_arg(ap, void *));
468     va_end(ap);
469
470     /* We only care about duping fds. */
471     if (cmd == F_DUPFD && result > -1) {
472         dup_fd(fd, result);
473     }
474
475     return result;
476 }
477
478 /* int close(int) */
479 HOOK_FUNC_DEF1(int, close, int, fd) {
480     DLSYM_FUNCTION(real_close, "close");
481
482     if (fd >= 0) {
483         close_fd(fd);
484     }
485     return real_close(fd);
486 }
487 /* int fclose(FILE *) */
488 HOOK_FUNC_DEF1(int, fclose, FILE *, fp) {
489     int fd;
490
491     DLSYM_FUNCTION(real_fclose, "fclose");
492
493     if (fp != NULL && (fd = fileno(fp)) >= 0) {
494         close_fd(fd);
495     }
496     return real_fclose(fp);
497 }
498
499
500 /* Hook functions which are necessary for correct tracking. */
501
502 #if defined(HAVE_VFORK) && defined(HAVE_FORK)
503 pid_t vfork(void) {
504     /* vfork() is similar to fork() but the address space is shared between
505      * father and child. It's designed for fork()/exec() usage because it's
506      * faster than fork(). However according to the POSIX standard the "child"
507      * isn't allowed to perform any memory-modifications before the exec()
508      * (except the pid_t result variable of vfork()).
509      *
510      * As some programs don't adhere to the standard (e.g. the "child" closes
511      * or dups a descriptor before the exec()) and this breaks our tracking of
512      * file descriptors (e.g. it gets closed in the parent as well), we just
513      * fork() instead. This is in compliance with the POSIX standard and as
514      * most systems use copy-on-write anyway not a performance issue. */
515     return fork();
516 }
517 #endif
518
519
520 /* Hook execve() and the other exec*() functions. Some shells use exec*() with
521  * a custom environment which doesn't necessarily contain our updates to
522  * ENV_NAME_PRIVATE_FDS. It's also faster to update the environment only when
523  * necessary, right before the exec(), to pass it to the new program. */
524
525 /* int execve(char const *, char * const [], char * const []) */
526 HOOK_FUNC_DEF3(int, execve, char const *, filename, char * const *, argv, char * const *, env) {
527     DLSYM_FUNCTION(real_execve, "execve");
528
529     /* Count environment variables. */
530     size_t count = 0;
531     char * const *x = env;
532     while (*x++) {
533         count++;
534     }
535     /* Terminating NULL. */
536     count++;
537
538     char *env_copy[count + 1 /* space for our new entry if necessary */];
539
540     /* Make sure the information from the environment is loaded. We can't just
541      * do nothing (like update_environment()) because the caller might pass a
542      * different environment which doesn't include any of our settings. */
543     if (!initialized) {
544         init_from_environment();
545     }
546
547     char fds_env[strlen(ENV_NAME_PRIVATE_FDS)
548                  + 1 + update_environment_buffer_size()];
549     strcpy(fds_env, ENV_NAME_PRIVATE_FDS "=");
550     update_environment_buffer(fds_env + strlen(ENV_NAME_PRIVATE_FDS) + 1);
551
552     int found = 0;
553     char **x_copy = env_copy;
554
555     /* Copy the environment manually; allows skipping elements. */
556     x = env;
557     while ((*x_copy = *x)) {
558         /* Remove ENV_NAME_FDS if we've already used its value. The new
559          * program must use the updated list from ENV_NAME_PRIVATE_FDS. */
560         if (used_fds_set_by_user
561                 && !strncmp(*x, ENV_NAME_FDS "=", strlen(ENV_NAME_FDS) + 1)) {
562             x++;
563             continue;
564         /* Update ENV_NAME_PRIVATE_FDS. */
565         } else if (!strncmp(*x, ENV_NAME_PRIVATE_FDS "=",
566                             strlen(ENV_NAME_PRIVATE_FDS) + 1)) {
567             *x_copy = fds_env;
568             found = 1;
569         }
570
571         x++;
572         x_copy++;
573     }
574     /* The loop "condition" NULL-terminates env_copy. */
575
576     if (!found) {
577         /* If the process removed ENV_NAME_PRIVATE_FDS from the environment,
578          * re-add it. */
579         *x_copy++ = fds_env;
580         *x_copy++ = NULL;
581     }
582
583     return real_execve(filename, argv, env_copy);
584 }
585
586 #define EXECL_COPY_VARARGS_START(args) \
587     va_list ap; \
588     char *x; \
589     \
590     /* Count arguments. */ \
591     size_t count = 1; /* arg */ \
592     va_start(ap, arg); \
593     while (va_arg(ap, char *)) { \
594         count++; \
595     } \
596     va_end(ap); \
597     \
598     /* Copy varargs. */ \
599     char *args[count + 1 /* terminating NULL */]; \
600     args[0] = (char *)arg; /* there's no other way around the cast */ \
601     \
602     size_t i = 1; \
603     va_start(ap, arg); \
604     while ((x = va_arg(ap, char *))) { \
605         args[i++] = x; \
606     } \
607     args[i] = NULL;
608 #define EXECL_COPY_VARARGS_END(args) \
609     va_end(ap);
610 #define EXECL_COPY_VARARGS(args) \
611     EXECL_COPY_VARARGS_START(args); \
612     EXECL_COPY_VARARGS_END(args);
613
614 int execl(char const *path, char const *arg, ...) {
615     EXECL_COPY_VARARGS(args);
616
617     /* execv() updates the environment. */
618     return execv(path, args);
619 }
620 int execlp(char const *file, char const *arg, ...) {
621     EXECL_COPY_VARARGS(args);
622
623     /* execvp() updates the environment. */
624     return execvp(file, args);
625 }
626 int execle(char const *path, char const *arg, ... /*, char * const envp[] */) {
627     char * const *envp;
628
629     EXECL_COPY_VARARGS_START(args);
630     /* Get envp[] located after arguments. */
631     envp = va_arg(ap, char * const *);
632     EXECL_COPY_VARARGS_END(args);
633
634     /* execve() updates the environment. */
635     return execve(path, args, envp);
636 }
637
638 /* int execv(char const *, char * const []) */
639 HOOK_FUNC_DEF2(int, execv, char const *, path, char * const *, argv) {
640     DLSYM_FUNCTION(real_execv, "execv");
641
642     update_environment();
643     return real_execv(path, argv);
644 }
645
646 /* int execvp(char const *, char * const []) */
647 HOOK_FUNC_DEF2(int, execvp, char const *, file, char * const *, argv) {
648     DLSYM_FUNCTION(real_execvp, "execvp");
649
650     update_environment();
651     return real_execvp(file, argv);
652 }
653
654 #ifdef HAVE_EXECVPE
655 extern char **environ;
656 int execvpe(char const *file, char * const argv[], char * const envp[]) {
657     int result;
658     char **old_environ = environ;
659
660     /* Fake the environment so we can reuse execvp(). */
661     environ = (char **)envp;
662
663     /* execvp() updates the environment. */
664     result = execvp(file, argv);
665
666     environ = old_environ;
667     return result;
668 }
669 #endif