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