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