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