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