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