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