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