2 * Hook output functions (like printf(3)) with LD_PRELOAD to color stderr (or
3 * other file descriptors).
5 * Copyright (C) 2013 Simon Ruderich
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.
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.
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/>.
25 /* Must be loaded before the following headers. */
26 #include "ldpreload.h"
28 /* Disable assert()s if not compiled with --enable-debug. */
48 #ifdef HAVE_STRUCT__IO_FILE__FILENO
52 /* The following functions may be macros. Undefine them or they cause build
53 * failures when used in our hook macros below. */
55 /* In glibc, real fwrite_unlocked() is called in macro. */
56 #ifdef HAVE_FWRITE_UNLOCKED
57 # undef fwrite_unlocked
59 /* In Clang when compiling with hardening flags (fortify) on Debian Wheezy. */
62 /* On FreeBSD (9.1), __swbuf() is used instead of these macros. */
67 # undef putchar_unlocked
71 /* Used by various functions, including debug(). */
72 static ssize_t (*real_write)(int, void const *, size_t);
73 static int (*real_close)(int);
74 static size_t (*real_fwrite)(void const *, size_t, size_t, FILE *);
76 /* Did we already (try to) parse the environment and setup the necessary
78 static int initialized;
79 /* Force hooked writes even when not writing to a tty. Used for tests. */
80 static int force_write_to_non_tty;
81 /* Was ENV_NAME_FDS found and used when init_from_environment() was called?
82 * This is not true if the process set it manually after initialization. */
83 static int used_fds_set_by_user;
86 #include "constants.h"
91 #include "hookmacros.h"
96 /* See hookmacros.h for the decision if a function call is colored. */
99 /* Prevent inlining into hook functions because it may increase the number of
100 * spilled registers unnecessarily. As it's not called very often accept the
101 * additional call. */
102 static int isatty_noinline(int fd) noinline;
103 static int isatty_noinline(int fd) {
106 int saved_errno = errno;
107 int result = isatty(fd);
114 static void dup_fd(int oldfd, int newfd) {
116 debug("%3d -> %3d\t\t\t[%d]\n", oldfd, newfd, getpid());
119 assert(oldfd >= 0 && newfd >= 0);
121 if (unlikely(!initialized)) {
122 init_from_environment();
125 /* We are already tracking this file descriptor, add newfd to the list as
126 * it will reference the same descriptor. */
127 if (tracked_fds_find(oldfd)) {
128 if (!tracked_fds_find(newfd)) {
129 tracked_fds_add(newfd);
131 /* We are not tracking this file descriptor, remove newfd from the list
134 tracked_fds_remove(newfd);
138 static void close_fd(int fd) {
140 debug("%3d -> .\t\t\t[%d]\n", fd, getpid());
145 if (unlikely(!initialized)) {
146 init_from_environment();
149 tracked_fds_remove(fd);
153 /* "Action" handlers called when a file descriptor is matched. */
155 static char const *pre_string;
156 static size_t pre_string_size;
157 static char const *post_string;
158 static size_t post_string_size;
160 /* Load alternative pre/post strings from the environment if available, fall
161 * back to default values. */
162 static void init_pre_post_string(void) {
163 pre_string = getenv(ENV_NAME_PRE_STRING);
165 pre_string = DEFAULT_PRE_STRING;
167 pre_string_size = strlen(pre_string);
169 post_string = getenv(ENV_NAME_POST_STRING);
171 post_string = DEFAULT_POST_STRING;
173 post_string_size = strlen(post_string);
176 /* Don't inline any of the pre/post functions. Keep the hook function as small
177 * as possible for speed reasons. */
178 static void handle_fd_pre(int fd) noinline;
179 static void handle_fd_post(int fd) noinline;
180 static void handle_file_pre(FILE *stream) noinline;
181 static void handle_file_post(FILE *stream) noinline;
183 static void handle_fd_pre(int fd) {
184 int saved_errno = errno;
186 if (unlikely(!pre_string || !post_string)) {
187 init_pre_post_string();
190 DLSYM_FUNCTION(real_write, "write");
191 real_write(fd, pre_string, pre_string_size);
195 static void handle_fd_post(int fd) {
196 int saved_errno = errno;
198 /* write() already loaded above in handle_fd_pre(). */
199 real_write(fd, post_string, post_string_size);
204 static void handle_file_pre(FILE *stream) {
205 int saved_errno = errno;
207 if (unlikely(!pre_string || !post_string)) {
208 init_pre_post_string();
211 DLSYM_FUNCTION(real_fwrite, "fwrite");
212 real_fwrite(pre_string, pre_string_size, 1, stream);
216 static void handle_file_post(FILE *stream) {
217 int saved_errno = errno;
219 /* fwrite() already loaded above in handle_file_pre(). */
220 real_fwrite(post_string, post_string_size, 1, stream);
227 /* Hook all important output functions to manipulate their output. */
229 HOOK_FD3(ssize_t, write, fd,
230 int, fd, void const *, buf, size_t, count)
231 HOOK_FILE4(size_t, fwrite, stream,
232 void const *, ptr, size_t, size, size_t, nmemb, FILE *, stream)
235 HOOK_FILE2(int, fputs, stream,
236 char const *, s, FILE *, stream)
237 HOOK_FILE2(int, fputc, stream,
238 int, c, FILE *, stream)
239 HOOK_FILE2(int, putc, stream,
240 int, c, FILE *, stream)
241 HOOK_FILE1(int, putchar, stdout,
243 HOOK_FILE1(int, puts, stdout,
246 /* printf(3), excluding all s*() and vs*() functions (no output) */
247 HOOK_VAR_FILE1(int, printf, stdout, vprintf,
248 char const *, format)
249 HOOK_VAR_FILE2(int, fprintf, stream, vfprintf,
250 FILE *, stream, char const *, format)
251 HOOK_FILE2(int, vprintf, stdout,
252 char const *, format, va_list, ap)
253 HOOK_FILE3(int, vfprintf, stream,
254 FILE *, stream, char const *, format, va_list, ap)
255 /* Hardening functions (-D_FORTIFY_SOURCE=2), only functions from above */
256 HOOK_VAR_FILE2(int, __printf_chk, stdout, __vprintf_chk,
257 int, flag, char const *, format)
258 HOOK_VAR_FILE3(int, __fprintf_chk, fp, __vfprintf_chk,
259 FILE *, fp, int, flag, char const *, format)
260 HOOK_FILE3(int, __vprintf_chk, stdout,
261 int, flag, char const *, format, va_list, ap)
262 HOOK_FILE4(int, __vfprintf_chk, stream,
263 FILE *, stream, int, flag, char const *, format, va_list, ap)
265 /* unlocked_stdio(3), only functions from above are hooked */
266 #ifdef HAVE_FWRITE_UNLOCKED
267 HOOK_FILE4(size_t, fwrite_unlocked, stream,
268 void const *, ptr, size_t, size, size_t, nmemb, FILE *, stream)
270 #ifdef HAVE_FPUTS_UNLOCKED
271 HOOK_FILE2(int, fputs_unlocked, stream,
272 char const *, s, FILE *, stream)
274 #ifdef HAVE_FPUTC_UNLOCKED
275 HOOK_FILE2(int, fputc_unlocked, stream,
276 int, c, FILE *, stream)
278 HOOK_FILE2(int, putc_unlocked, stream,
279 int, c, FILE *, stream)
280 HOOK_FILE1(int, putchar_unlocked, stdout,
282 /* glibc defines (_IO_)putc_unlocked() to a macro which either updates the
283 * output buffer or calls __overflow(). As this code is inlined we can't
284 * handle the first case, but if __overflow() is called we can color that
285 * part. As writes to stderr are never buffered, __overflow() is always called
286 * and everything works fine. This is only a problem if stdout is dupped to
287 * stderr (which shouldn't be the case too often). */
288 #if defined(HAVE_STRUCT__IO_FILE__FILENO) && defined(HAVE___OVERFLOW)
289 /* _IO_FILE is glibc's representation of FILE. */
290 HOOK_FILE2(int, __overflow, f, _IO_FILE *, f, int, ch)
292 /* Same for FreeBSD's libc. However it's more aggressive: The inline writing
293 * and __swbuf() are also used for normal output (e.g. putc()). Writing to
294 * stderr is still fine; it always calls __swbuf() as stderr is always
297 HOOK_FILE2(int, __swbuf, f, int, c, FILE *, f)
301 HOOK_VOID1(void, perror, STDERR_FILENO,
304 /* err(3), non standard BSD extension */
306 HOOK_VAR_VOID2(void, err, STDERR_FILENO, verr,
307 int, eval, char const *, fmt)
308 HOOK_VAR_VOID2(void, errx, STDERR_FILENO, verrx,
309 int, eval, char const *, fmt)
310 HOOK_VAR_VOID1(void, warn, STDERR_FILENO, vwarn,
312 HOOK_VAR_VOID1(void, warnx, STDERR_FILENO, vwarnx,
314 HOOK_FUNC_SIMPLE3(void, verr, int, eval, const char *, fmt, va_list, args) {
315 /* Can't use verr() directly as it terminates the process which prevents
316 * the post string from being printed. */
320 HOOK_FUNC_SIMPLE3(void, verrx, int, eval, const char *, fmt, va_list, args) {
325 HOOK_VOID2(void, vwarn, STDERR_FILENO,
326 char const *, fmt, va_list, args)
327 HOOK_VOID2(void, vwarnx, STDERR_FILENO,
328 char const *, fmt, va_list, args)
331 /* error(3), non-standard GNU extension */
333 static void error_vararg(int status, int errnum,
334 char const *filename, unsigned int linenum,
335 char const *format, va_list ap) {
336 static char const *last_filename;
337 static unsigned int last_linenum;
339 /* Skip this error message if requested and if there was already an error
340 * in the same file/line. */
341 if (error_one_per_line
342 && filename != NULL && linenum != 0
343 && filename == last_filename && linenum == last_linenum) {
346 last_filename = filename;
347 last_linenum = linenum;
349 error_message_count++;
353 if (error_print_progname) {
354 error_print_progname();
356 fprintf(stderr, "%s:", program_invocation_name);
358 if (filename != NULL && linenum != 0) {
359 fprintf(stderr, "%s:%u:", filename, linenum);
360 if (error_print_progname) {
361 fprintf(stderr, " ");
364 if (!error_print_progname) {
365 fprintf(stderr, " ");
369 vfprintf(stderr, format, ap);
372 fprintf(stderr, ": %s", strerror(errnum));
375 fprintf(stderr, "\n");
381 void error_at_line(int status, int errnum,
382 char const *filename, unsigned int linenum,
383 char const *format, ...) {
386 va_start(ap, format);
387 error_vararg(status, errnum, filename, linenum, format, ap);
390 void error(int status, int errnum, char const *format, ...) {
393 va_start(ap, format);
394 error_vararg(status, errnum, NULL, 0, format, ap);
400 /* Hook functions which duplicate file descriptors to track them. */
403 HOOK_FUNC_DEF1(int, dup, int, oldfd) {
406 DLSYM_FUNCTION(real_dup, "dup");
408 newfd = real_dup(oldfd);
410 dup_fd(oldfd, newfd);
415 /* int dup2(int, int) */
416 HOOK_FUNC_DEF2(int, dup2, int, oldfd, int, newfd) {
417 DLSYM_FUNCTION(real_dup2, "dup2");
419 newfd = real_dup2(oldfd, newfd);
421 dup_fd(oldfd, newfd);
426 /* int dup3(int, int, int) */
427 HOOK_FUNC_DEF3(int, dup3, int, oldfd, int, newfd, int, flags) {
428 DLSYM_FUNCTION(real_dup3, "dup3");
430 newfd = real_dup3(oldfd, newfd, flags);
432 dup_fd(oldfd, newfd);
438 /* int fcntl(int, int, ...) */
439 HOOK_FUNC_VAR_DEF2(int, fcntl, int, fd, int, cmd /*, ... */) {
443 DLSYM_FUNCTION(real_fcntl, "fcntl");
445 /* fcntl() takes different types of arguments depending on the cmd type
446 * (int, void and pointers are used at the moment). Handling these
447 * arguments for different systems and with possible changes in the future
450 * Therefore always retrieve a void-pointer from our arguments (even if it
451 * wasn't there) and pass it to real_fcntl(). This shouldn't cause any
452 * problems because a void-pointer is most-likely bigger than an int
453 * (something which is not true in reverse) and shouldn't cause
454 * truncation. For register based calling conventions an invalid register
455 * content is passed, but ignored by real_fcntl(). Not perfect, but should
459 result = real_fcntl(fd, cmd, va_arg(ap, void *));
462 /* We only care about duping fds. */
463 if (cmd == F_DUPFD && result > -1) {
471 HOOK_FUNC_DEF1(int, close, int, fd) {
472 DLSYM_FUNCTION(real_close, "close");
477 return real_close(fd);
479 /* int fclose(FILE *) */
480 HOOK_FUNC_DEF1(int, fclose, FILE *, fp) {
483 DLSYM_FUNCTION(real_fclose, "fclose");
485 if (fp != NULL && (fd = fileno(fp)) >= 0) {
488 return real_fclose(fp);
492 /* Hook functions which are necessary for correct tracking. */
494 #if defined(HAVE_VFORK) && defined(HAVE_FORK)
496 /* vfork() is similar to fork() but the address space is shared between
497 * father and child. It's designed for fork()/exec() usage because it's
498 * faster than fork(). However according to the POSIX standard the "child"
499 * isn't allowed to perform any memory-modifications before the exec()
500 * (except the pid_t result variable of vfork()).
502 * As some programs don't adhere to the standard (e.g. the "child" closes
503 * or dups a descriptor before the exec()) and this breaks our tracking of
504 * file descriptors (e.g. it gets closed in the parent as well), we just
505 * fork() instead. This is in compliance with the POSIX standard and as
506 * most systems use copy-on-write anyway not a performance issue. */
512 /* Hook execve() and the other exec*() functions. Some shells use exec*() with
513 * a custom environment which doesn't necessarily contain our updates to
514 * ENV_NAME_PRIVATE_FDS. It's also faster to update the environment only when
515 * necessary, right before the exec(), to pass it to the new program. */
517 /* int execve(char const *, char * const [], char * const []) */
518 HOOK_FUNC_DEF3(int, execve, char const *, filename, char * const *, argv, char * const *, env) {
519 DLSYM_FUNCTION(real_execve, "execve");
521 /* Count environment variables. */
523 char * const *x = env;
527 /* Terminating NULL. */
530 char *env_copy[count + 1 /* space for our new entry if necessary */];
532 /* Make sure the information from the environment is loaded. We can't just
533 * do nothing (like update_environment()) because the caller might pass a
534 * different environment which doesn't include any of our settings. */
536 init_from_environment();
539 char fds_env[strlen(ENV_NAME_PRIVATE_FDS)
540 + 1 + update_environment_buffer_size()];
541 strcpy(fds_env, ENV_NAME_PRIVATE_FDS "=");
542 update_environment_buffer(fds_env + strlen(ENV_NAME_PRIVATE_FDS) + 1);
545 char **x_copy = env_copy;
547 /* Copy the environment manually; allows skipping elements. */
549 while ((*x_copy = *x)) {
550 /* Remove ENV_NAME_FDS if we've already used its value. The new
551 * program must use the updated list from ENV_NAME_PRIVATE_FDS. */
552 if (used_fds_set_by_user
553 && !strncmp(*x, ENV_NAME_FDS "=", strlen(ENV_NAME_FDS) + 1)) {
556 /* Update ENV_NAME_PRIVATE_FDS. */
557 } else if (!strncmp(*x, ENV_NAME_PRIVATE_FDS "=",
558 strlen(ENV_NAME_PRIVATE_FDS) + 1)) {
566 /* The loop "condition" NULL-terminates env_copy. */
569 /* If the process removed ENV_NAME_PRIVATE_FDS from the environment,
575 return real_execve(filename, argv, env_copy);
578 #define EXECL_COPY_VARARGS_START(args) \
582 /* Count arguments. */ \
583 size_t count = 1; /* arg */ \
585 while (va_arg(ap, char *)) { \
590 /* Copy varargs. */ \
591 char *args[count + 1 /* terminating NULL */]; \
592 args[0] = (char *)arg; /* there's no other way around the cast */ \
596 while ((x = va_arg(ap, char *))) { \
600 #define EXECL_COPY_VARARGS_END(args) \
602 #define EXECL_COPY_VARARGS(args) \
603 EXECL_COPY_VARARGS_START(args); \
604 EXECL_COPY_VARARGS_END(args);
606 int execl(char const *path, char const *arg, ...) {
607 EXECL_COPY_VARARGS(args);
609 /* execv() updates the environment. */
610 return execv(path, args);
612 int execlp(char const *file, char const *arg, ...) {
613 EXECL_COPY_VARARGS(args);
615 /* execvp() updates the environment. */
616 return execvp(file, args);
618 int execle(char const *path, char const *arg, ... /*, char * const envp[] */) {
621 EXECL_COPY_VARARGS_START(args);
622 /* Get envp[] located after arguments. */
623 envp = va_arg(ap, char * const *);
624 EXECL_COPY_VARARGS_END(args);
626 /* execve() updates the environment. */
627 return execve(path, args, envp);
630 /* int execv(char const *, char * const []) */
631 HOOK_FUNC_DEF2(int, execv, char const *, path, char * const *, argv) {
632 DLSYM_FUNCTION(real_execv, "execv");
634 update_environment();
635 return real_execv(path, argv);
638 /* int execvp(char const *, char * const []) */
639 HOOK_FUNC_DEF2(int, execvp, char const *, file, char * const *, argv) {
640 DLSYM_FUNCTION(real_execvp, "execvp");
642 update_environment();
643 return real_execvp(file, argv);
647 extern char **environ;
648 int execvpe(char const *file, char * const argv[], char * const envp[]) {
650 char **old_environ = environ;
652 /* Fake the environment so we can reuse execvp(). */
653 environ = (char **)envp;
655 /* execvp() updates the environment. */
656 result = execvp(file, argv);
658 environ = old_environ;