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