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/>.
23 /* Must be loaded before the following headers. */
24 #include "ldpreload.h"
37 /* Conflicting declaration in glibc. */
38 #undef fwrite_unlocked
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 *);
46 /* Did we already (try to) parse the environment and setup the necessary
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;
53 #include "constants.h"
59 #include "hookmacros.h"
64 /* See hookmacros.h for the decision if a function call is colored. */
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
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);
80 static void dup_fd(int oldfd, int newfd) {
82 debug("%3d -> %3d\t\t\t[%d]\n", oldfd, newfd, getpid());
85 if (unlikely(!initialized)) {
86 init_from_environment();
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);
95 /* We are not tracking this file descriptor, remove newfd from the list
98 tracked_fds_remove(newfd);
102 static void close_fd(int fd) {
104 debug("%3d -> .\t\t\t[%d]\n", fd, getpid());
107 if (unlikely(!initialized)) {
108 init_from_environment();
111 tracked_fds_remove(fd);
115 /* "Action" handlers called when a file descriptor is matched. */
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;
122 /* Load alternative pre/post strings from the environment if available, fall
123 * back to default values. */
124 static void init_pre_post_string(void) {
125 pre_string = getenv(ENV_NAME_PRE_STRING);
127 pre_string = DEFAULT_PRE_STRING;
129 pre_string_size = strlen(pre_string);
131 post_string = getenv(ENV_NAME_POST_STRING);
133 post_string = DEFAULT_POST_STRING;
135 post_string_size = strlen(post_string);
138 /* Don't inline any of the pre/post functions. Keep the hook function as small
139 * as possible for speed reasons. */
140 static void handle_fd_pre(int fd) __noinline;
141 static void handle_fd_post(int fd) __noinline;
142 static void handle_file_pre(FILE *stream) __noinline;
143 static void handle_file_post(FILE *stream) __noinline;
145 static void handle_fd_pre(int fd) {
146 int saved_errno = errno;
148 if (unlikely(!pre_string || !post_string)) {
149 init_pre_post_string();
152 DLSYM_FUNCTION(real_write, "write");
153 real_write(fd, pre_string, pre_string_size);
157 static void handle_fd_post(int fd) {
158 int saved_errno = errno;
160 /* write() already loaded above in handle_fd_pre(). */
161 real_write(fd, post_string, post_string_size);
166 static void handle_file_pre(FILE *stream) {
167 int saved_errno = errno;
169 if (unlikely(!pre_string || !post_string)) {
170 init_pre_post_string();
173 DLSYM_FUNCTION(real_fwrite, "fwrite");
174 real_fwrite(pre_string, pre_string_size, 1, stream);
178 static void handle_file_post(FILE *stream) {
179 int saved_errno = errno;
181 /* fwrite() already loaded above in handle_file_pre(). */
182 real_fwrite(post_string, post_string_size, 1, stream);
189 /* Hook all important output functions to manipulate their output. */
191 HOOK_FD3(ssize_t, write, fd,
192 int, fd, void const *, buf, size_t, count)
193 HOOK_FILE4(size_t, fwrite, stream,
194 void const *, ptr, size_t, size, size_t, nmemb, FILE *, stream)
197 HOOK_FILE2(int, fputs, stream,
198 char const *, s, FILE *, stream)
199 HOOK_FILE2(int, fputc, stream,
200 int, c, FILE *, stream)
201 HOOK_FILE2(int, putc, stream,
202 int, c, FILE *, stream)
203 HOOK_FILE1(int, putchar, stdout,
205 HOOK_FILE1(int, puts, stdout,
208 /* printf(3), excluding all s*() and vs*() functions (no output) */
209 HOOK_VAR_FILE1(int, printf, stdout, vprintf,
210 char const *, format)
211 HOOK_VAR_FILE2(int, fprintf, stream, vfprintf,
212 FILE *, stream, char const *, format)
213 HOOK_FILE2(int, vprintf, stdout,
214 char const *, format, va_list, ap)
215 HOOK_FILE3(int, vfprintf, stream,
216 FILE *, stream, char const *, format, va_list, ap)
217 /* Hardening functions (-D_FORTIFY_SOURCE=2), only functions from above */
218 HOOK_VAR_FILE2(int, __printf_chk, stdout, __vprintf_chk,
219 int, flag, char const *, format)
220 HOOK_VAR_FILE3(int, __fprintf_chk, fp, __vfprintf_chk,
221 FILE *, fp, int, flag, char const *, format)
222 HOOK_FILE3(int, __vprintf_chk, stdout,
223 int, flag, char const *, format, va_list, ap)
224 HOOK_FILE4(int, __vfprintf_chk, stream,
225 FILE *, stream, int, flag, char const *, format, va_list, ap)
227 /* unlocked_stdio(3), only functions from above are hooked */
228 HOOK_FILE4(size_t, fwrite_unlocked, stream,
229 void const *, ptr, size_t, size, size_t, nmemb, FILE *, stream)
230 HOOK_FILE2(int, fputs_unlocked, stream,
231 char const *, s, FILE *, stream)
232 HOOK_FILE2(int, fputc_unlocked, stream,
233 int, c, FILE *, stream)
234 HOOK_FILE2(int, putc_unlocked, stream,
235 int, c, FILE *, stream)
236 HOOK_FILE1(int, putchar_unlocked, stdout,
240 HOOK_VOID1(void, perror, STDERR_FILENO,
245 static void error_vararg(int status, int errnum,
246 char const *filename, unsigned int linenum,
247 char const *format, va_list ap) {
248 static char const *last_filename;
249 static unsigned int last_linenum;
251 /* Skip this error message if requested and if there was already an error
252 * in the same file/line. */
253 if (error_one_per_line
254 && filename != NULL && linenum != 0
255 && filename == last_filename && linenum == last_linenum) {
258 last_filename = filename;
259 last_linenum = linenum;
261 error_message_count++;
265 if (error_print_progname) {
266 error_print_progname();
268 fprintf(stderr, "%s:", program_invocation_name);
270 if (filename != NULL && linenum != 0) {
271 fprintf(stderr, "%s:%u:", filename, linenum);
272 if (error_print_progname) {
273 fprintf(stderr, " ");
276 if (!error_print_progname) {
277 fprintf(stderr, " ");
281 vfprintf(stderr, format, ap);
284 fprintf(stderr, ": %s", strerror(errnum));
287 fprintf(stderr, "\n");
293 void error_at_line(int status, int errnum,
294 char const *filename, unsigned int linenum,
295 char const *format, ...) {
298 va_start(ap, format);
299 error_vararg(status, errnum, filename, linenum, format, ap);
302 void error(int status, int errnum, char const *format, ...) {
305 va_start(ap, format);
306 error_vararg(status, errnum, NULL, 0, format, ap);
312 /* Hook functions which duplicate file descriptors to track them. */
314 static int (*real_dup)(int);
315 static int (*real_dup2)(int, int);
316 static int (*real_dup3)(int, int, int);
320 DLSYM_FUNCTION(real_dup, "dup");
322 newfd = real_dup(oldfd);
324 dup_fd(oldfd, newfd);
329 int dup2(int oldfd, int newfd) {
330 DLSYM_FUNCTION(real_dup2, "dup2");
332 newfd = real_dup2(oldfd, newfd);
334 dup_fd(oldfd, newfd);
339 int dup3(int oldfd, int newfd, int flags) {
340 DLSYM_FUNCTION(real_dup3, "dup3");
342 newfd = real_dup3(oldfd, newfd, flags);
344 dup_fd(oldfd, newfd);
350 static int (*real_fcntl)(int, int, ...);
351 int fcntl(int fd, int cmd, ...) {
355 DLSYM_FUNCTION(real_fcntl, "fcntl");
357 /* fcntl() takes different types of arguments depending on the cmd type
358 * (int, void and pointers are used at the moment). Handling these
359 * arguments for different systems and with possible changes in the future
362 * Therefore always retrieve a void-pointer from our arguments (even if it
363 * wasn't there) and pass it to real_fcntl(). This shouldn't cause any
364 * problems because a void-pointer is most-likely bigger than an int
365 * (something which is not true in reverse) and shouldn't cause
366 * truncation. For register based calling conventions an invalid register
367 * content is passed, but ignored by real_fcntl(). Not perfect, but should
371 result = real_fcntl(fd, cmd, va_arg(ap, void *));
374 /* We only care about duping fds. */
375 if (cmd == F_DUPFD && result != -1) {
382 static int (*real_close)(int);
384 DLSYM_FUNCTION(real_close, "close");
387 return real_close(fd);
389 static int (*real_fclose)(FILE *);
390 int fclose(FILE *fp) {
391 DLSYM_FUNCTION(real_fclose, "fclose");
393 close_fd(fileno(fp));
394 return real_fclose(fp);
398 /* Hook functions which are necessary for correct tracking. */
400 #if defined(HAVE_VFORK) && defined(HAVE_FORK)
402 /* vfork() is similar to fork() but the address space is shared between
403 * father and child. It's designed for fork()/exec() usage because it's
404 * faster than fork(). However according to the POSIX standard the "child"
405 * isn't allowed to perform any memory-modifications before the exec()
406 * (except the pid_t result variable of vfork()).
408 * As some programs don't adhere to the standard (e.g. the "child" closes
409 * or dups a descriptor before the exec()) and this breaks our tracking of
410 * file descriptors (e.g. it gets closed in the parent as well), we just
411 * fork() instead. This is in compliance with the POSIX standard and as
412 * most systems use copy-on-write anyway not a performance issue. */
418 /* Hook execve() and the other exec*() functions. Some shells use exec*() with
419 * a custom environment which doesn't necessarily contain our updates to
420 * ENV_NAME_FDS. It's also faster to update the environment only when
421 * necessary, right before the exec() to pass it to the new process. */
423 static int (*real_execve)(char const *filename, char * const argv[], char * const env[]);
424 int execve(char const *filename, char * const argv[], char * const env[]) {
425 DLSYM_FUNCTION(real_execve, "execve");
430 /* Count arguments and search for existing ENV_NAME_FDS environment
433 char * const *x = env;
435 if (!strncmp(*x, ENV_NAME_FDS "=", strlen(ENV_NAME_FDS) + 1)) {
443 /* Terminating NULL. */
446 char *env_copy[count + 1 /* space for our new entry if necessary */];
447 memcpy(env_copy, env, count * sizeof(char *));
449 /* Make sure the information from the environment is loaded. We can't just
450 * do nothing (like update_environment()) because the caller might pass a
451 * different environment which doesn't include any of our settings. */
453 init_from_environment();
456 char fds_env[strlen(ENV_NAME_FDS) + 1 + update_environment_buffer_size()];
457 strcpy(fds_env, ENV_NAME_FDS "=");
458 update_environment_buffer(fds_env + strlen(ENV_NAME_FDS) + 1);
461 env_copy[index] = fds_env;
463 /* If the process removed ENV_NAME_FDS from the environment, re-add
465 env_copy[count-1] = fds_env;
466 env_copy[count] = NULL;
469 return real_execve(filename, argv, env_copy);
472 #define EXECL_COPY_VARARGS_START(args) \
476 /* Count arguments. */ \
477 size_t count = 1; /* arg */ \
479 while (va_arg(ap, char const *)) { \
484 /* Copy varargs. */ \
485 char *args[count + 1 /* terminating NULL */]; \
486 args[0] = (char *)arg; \
490 while ((x = va_arg(ap, char *))) { \
494 #define EXECL_COPY_VARARGS_END(args) \
496 #define EXECL_COPY_VARARGS(args) \
497 EXECL_COPY_VARARGS_START(args); \
498 EXECL_COPY_VARARGS_END(args);
500 int execl(char const *path, char const *arg, ...) {
501 EXECL_COPY_VARARGS(args);
503 update_environment();
504 return execv(path, args);
507 int execlp(char const *file, char const *arg, ...) {
508 EXECL_COPY_VARARGS(args);
510 update_environment();
511 return execvp(file, args);
514 int execle(char const *path, char const *arg, ... /*, char * const envp[] */) {
515 EXECL_COPY_VARARGS_START(args);
516 /* Get envp[] located after arguments. */
517 char * const *envp = va_arg(ap, char * const *);
518 EXECL_COPY_VARARGS_END(args);
520 return execve(path, args, envp);
523 static int (*real_execv)(char const *path, char * const argv[]);
524 int execv(char const *path, char * const argv[]) {
525 DLSYM_FUNCTION(real_execv, "execv");
527 update_environment();
528 return real_execv(path, argv);
531 static int (*real_execvp)(char const *path, char * const argv[]);
532 int execvp(char const *path, char * const argv[]) {
533 DLSYM_FUNCTION(real_execvp, "execvp");
535 update_environment();
536 return real_execvp(path, argv);