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