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