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