]> granicus.if.org Git - strace/blobdiff - strace.c
tests: move F_OFD_SETLK* checks from fcntl64.c to fcntl-common.c
[strace] / strace.c
index 9f2f4c68689b1b02515410b69327fdd34b181285..4b3748571ec69480049d12100bb46413b3f6de30 100644 (file)
--- a/strace.c
+++ b/strace.c
@@ -44,6 +44,7 @@
 #include <pwd.h>
 #include <grp.h>
 #include <dirent.h>
+#include <locale.h>
 #include <sys/utsname.h>
 #ifdef HAVE_PRCTL
 # include <sys/prctl.h>
 #include "printsiginfo.h"
 #include "trace_event.h"
 #include "xstring.h"
+#include "delay.h"
 
 /* In some libc, these aren't declared. Do it ourself: */
 extern char **environ;
 extern int optind;
 extern char *optarg;
 
-#ifdef USE_LIBUNWIND
+#ifdef ENABLE_STACKTRACE
 /* if this is true do the stack trace for every system call */
 bool stack_trace_enabled;
 #endif
@@ -145,9 +147,13 @@ unsigned int max_strlen = DEFAULT_STRLEN;
 static int acolumn = DEFAULT_ACOLUMN;
 static char *acolumn_spaces;
 
+/* Default output style for xlat entities */
+enum xlat_style xlat_verbosity = XLAT_STYLE_ABBREV;
+
 static const char *outfname;
 /* If -ff, points to stderr. Else, it's our common output log */
 static FILE *shared_log;
+static bool open_append;
 
 struct tcb *printing_tcp;
 static struct tcb *current_tcp;
@@ -165,14 +171,16 @@ unsigned os_release; /* generated from uname()'s u.release */
 static void detach(struct tcb *tcp);
 static void cleanup(void);
 static void interrupt(int sig);
-static sigset_t start_set, blocked_set;
 
 #ifdef HAVE_SIG_ATOMIC_T
-static volatile sig_atomic_t interrupted;
+static volatile sig_atomic_t interrupted, restart_failed;
 #else
-static volatile int interrupted;
+static volatile int interrupted, restart_failed;
 #endif
 
+static sigset_t timer_set;
+static void timer_sighandler(int);
+
 #ifndef HAVE_STRERROR
 
 #if !HAVE_DECL_SYS_ERRLIST
@@ -198,12 +206,12 @@ static void
 print_version(void)
 {
        static const char features[] =
-#ifdef USE_LIBUNWIND
-               " stack-unwind"
-#endif /* USE_LIBUNWIND */
+#ifdef ENABLE_STACKTRACE
+               " stack-trace=" USE_UNWINDER
+#endif
 #ifdef USE_DEMANGLE
                " stack-demangle"
-#endif /* USE_DEMANGLE */
+#endif
 #if SUPPORTED_PERSONALITIES > 1
 # if defined HAVE_M32_MPERS
                " m32-mpers"
@@ -243,9 +251,9 @@ Output format:\n\
   -a column      alignment COLUMN for printing syscall results (default %d)\n\
   -i             print instruction pointer at time of syscall\n\
 "
-#ifdef USE_LIBUNWIND
+#ifdef ENABLE_STACKTRACE
 "\
-  -k             obtain stack trace between each syscall (experimental)\n\
+  -k             obtain stack trace between each syscall\n\
 "
 #endif
 "\
@@ -413,7 +421,8 @@ set_cloexec_flag(int fd)
        if (flags == newflags)
                return;
 
-       fcntl(fd, F_SETFD, newflags); /* never fails */
+       if (fcntl(fd, F_SETFD, newflags)) /* never fails */
+               perror_msg_and_die("fcntl(%d, F_SETFD, %#x)", fd, newflags);
 }
 
 static void
@@ -445,7 +454,7 @@ strace_fopen(const char *path)
        FILE *fp;
 
        swap_uid();
-       fp = fopen_stream(path, "w");
+       fp = fopen_stream(path, open_append ? "a" : "w");
        if (!fp)
                perror_msg_and_die("Can't fopen '%s'", path);
        swap_uid();
@@ -642,27 +651,20 @@ printleader(struct tcb *tcp)
 
        if (tflag) {
                struct timespec ts;
-               clock_gettime(rflag ? CLOCK_MONOTONIC : CLOCK_REALTIME, &ts);
-
-               if (rflag) {
-                       static struct timespec ots;
-                       if (ots.tv_sec == 0)
-                               ots = ts;
-
-                       struct timespec dts;
-                       ts_sub(&dts, &ts, &ots);
-                       ots = ts;
+               clock_gettime(CLOCK_REALTIME, &ts);
 
-                       tprintf("%6ld.%06ld ",
-                               (long) dts.tv_sec, (long) dts.tv_nsec / 1000);
-               } else if (tflag > 2) {
+               if (tflag > 2) {
                        tprintf("%lld.%06ld ",
                                (long long) ts.tv_sec, (long) ts.tv_nsec / 1000);
                } else {
                        time_t local = ts.tv_sec;
-                       char str[sizeof("HH:MM:SS")];
+                       char str[MAX(sizeof("HH:MM:SS"), sizeof(ts.tv_sec) * 3)];
+                       struct tm *tm = localtime(&local);
 
-                       strftime(str, sizeof(str), "%T", localtime(&local));
+                       if (tm)
+                               strftime(str, sizeof(str), "%T", tm);
+                       else
+                               xsprintf(str, "%lld", (long long) local);
                        if (tflag > 1)
                                tprintf("%s.%06ld ",
                                        str, (long) ts.tv_nsec / 1000);
@@ -670,6 +672,25 @@ printleader(struct tcb *tcp)
                                tprintf("%s ", str);
                }
        }
+
+       if (rflag) {
+               struct timespec ts;
+               clock_gettime(CLOCK_MONOTONIC, &ts);
+
+               static struct timespec ots;
+               if (ots.tv_sec == 0)
+                       ots = ts;
+
+               struct timespec dts;
+               ts_sub(&dts, &ts, &ots);
+               ots = ts;
+
+               tprintf("%s%6ld.%06ld%s ",
+                       tflag ? "(+" : "",
+                       (long) dts.tv_sec, (long) dts.tv_nsec / 1000,
+                       tflag ? ")" : "");
+       }
+
        if (iflag)
                print_pc(tcp);
 }
@@ -686,14 +707,20 @@ tabto(void)
  * may create bogus empty FILE.<nonexistant_pid>, and then die.
  */
 static void
-newoutf(struct tcb *tcp)
+after_successful_attach(struct tcb *tcp, const unsigned int flags)
 {
+       tcp->flags |= TCB_ATTACHED | TCB_STARTUP | flags;
        tcp->outf = shared_log; /* if not -ff mode, the same file is for all */
        if (followfork >= 2) {
                char name[PATH_MAX];
                xsprintf(name, "%s.%u", outfname, tcp->pid);
                tcp->outf = strace_fopen(name);
        }
+
+#ifdef ENABLE_STACKTRACE
+       if (stack_trace_enabled)
+               unwind_tcb_init(tcp);
+#endif
 }
 
 static void
@@ -735,12 +762,6 @@ alloctcb(int pid)
 #if SUPPORTED_PERSONALITIES > 1
                        tcp->currpers = current_personality;
 #endif
-
-#ifdef USE_LIBUNWIND
-                       if (stack_trace_enabled)
-                               unwind_tcb_init(tcp);
-#endif
-
                        nprocs++;
                        debug_msg("new tcb for pid %d, active tcbs:%d",
                                  tcp->pid, nprocs);
@@ -793,13 +814,13 @@ droptcb(struct tcb *tcp)
 
        free_tcb_priv_data(tcp);
 
-#ifdef USE_LIBUNWIND
-       if (stack_trace_enabled) {
+#ifdef ENABLE_STACKTRACE
+       if (stack_trace_enabled)
                unwind_tcb_fin(tcp);
-       }
 #endif
 
-       mmap_cache_delete(tcp, __func__);
+       if (tcp->mmap_cache)
+               tcp->mmap_cache->free_fn(tcp, __func__);
 
        nprocs--;
        debug_msg("dropped tcb for pid %d, %d remain", tcp->pid, nprocs);
@@ -1022,9 +1043,7 @@ attach_tcb(struct tcb *const tcp)
                return;
        }
 
-       tcp->flags |= TCB_ATTACHED | TCB_GRABBED | TCB_STARTUP |
-                     post_attach_sigstop;
-       newoutf(tcp);
+       after_successful_attach(tcp, TCB_GRABBED | post_attach_sigstop);
        debug_msg("attach to pid %d (main) succeeded", tcp->pid);
 
        static const char task_path[] = "/proc/%d/task";
@@ -1052,12 +1071,10 @@ attach_tcb(struct tcb *const tcp)
                                                 ptrace_attach_cmd, tid);
                                continue;
                        }
-                       debug_msg("attach to pid %d succeeded", tid);
 
-                       struct tcb *tid_tcp = alloctcb(tid);
-                       tid_tcp->flags |= TCB_ATTACHED | TCB_GRABBED |
-                                         TCB_STARTUP | post_attach_sigstop;
-                       newoutf(tid_tcp);
+                       after_successful_attach(alloctcb(tid),
+                                               TCB_GRABBED | post_attach_sigstop);
+                       debug_msg("attach to pid %d succeeded", tid);
                }
 
                closedir(dir);
@@ -1081,15 +1098,6 @@ startup_attach(void)
        unsigned int tcbi;
        struct tcb *tcp;
 
-       /*
-        * Block user interruptions as we would leave the traced
-        * process stopped (process state T) if we would terminate in
-        * between PTRACE_ATTACH and wait4() on SIGSTOP.
-        * We rely on cleanup() from this point on.
-        */
-       if (interactive)
-               sigprocmask(SIG_SETMASK, &blocked_set, NULL);
-
        if (daemonized_tracer) {
                pid_t pid = fork();
                if (pid < 0)
@@ -1129,12 +1137,8 @@ startup_attach(void)
 
                attach_tcb(tcp);
 
-               if (interactive) {
-                       sigprocmask(SIG_SETMASK, &start_set, NULL);
-                       if (interrupted)
-                               goto ret;
-                       sigprocmask(SIG_SETMASK, &blocked_set, NULL);
-               }
+               if (interrupted)
+                       return;
        } /* for each tcbtab[] */
 
        if (daemonized_tracer) {
@@ -1145,10 +1149,6 @@ startup_attach(void)
                kill(parent_pid, SIGKILL);
                strace_child = 0;
        }
-
- ret:
-       if (interactive)
-               sigprocmask(SIG_SETMASK, &start_set, NULL);
 }
 
 /* Stack-o-phobic exec helper, in the hope to work around
@@ -1419,18 +1419,20 @@ startup_child(char **argv)
                                kill(pid, SIGCONT);
                }
                tcp = alloctcb(pid);
-               tcp->flags |= TCB_ATTACHED | TCB_STARTUP
-                           | TCB_SKIP_DETACH_ON_FIRST_EXEC
-                           | (NOMMU_SYSTEM ? 0 : (TCB_HIDE_LOG | post_attach_sigstop));
-               newoutf(tcp);
+               after_successful_attach(tcp, TCB_SKIP_DETACH_ON_FIRST_EXEC
+                                            | (NOMMU_SYSTEM ? 0
+                                               : (TCB_HIDE_LOG
+                                                  | post_attach_sigstop)));
        } else {
                /* With -D, we are *child* here, the tracee is our parent. */
                strace_child = strace_tracer_pid;
                strace_tracer_pid = getpid();
                tcp = alloctcb(strace_child);
                tcp->flags |= TCB_SKIP_DETACH_ON_FIRST_EXEC | TCB_HIDE_LOG;
-               /* attaching will be done later, by startup_attach */
-               /* note: we don't do newoutf(tcp) here either! */
+               /*
+                * Attaching will be done later, by startup_attach.
+                * Note: we don't do after_successful_attach() here either!
+                */
 
                /* NOMMU BUG! -D mode is active, we (child) return,
                 * and we will scribble over parent's stack!
@@ -1553,10 +1555,6 @@ get_os_release(void)
 static void
 set_sighandler(int signo, void (*sighandler)(int), struct sigaction *oldact)
 {
-       /* if signal handler is a function, add the signal to blocked_set */
-       if (sighandler != SIG_IGN && sighandler != SIG_DFL)
-               sigaddset(&blocked_set, signo);
-
        const struct sigaction sa = { .sa_handler = sighandler };
        sigaction(signo, &sa, oldact);
 }
@@ -1596,16 +1594,19 @@ init(int argc, char *argv[])
 #endif
        qualify("signal=all");
        while ((c = getopt(argc, argv, "+"
-#ifdef USE_LIBUNWIND
+#ifdef ENABLE_STACKTRACE
            "k"
 #endif
-           "a:b:cCdDe:E:fFhiI:o:O:p:P:qrs:S:tTu:vVwxyz")) != EOF) {
+           "a:Ab:cCdDe:E:fFhiI:o:O:p:P:qrs:S:tTu:vVwxX:yz")) != EOF) {
                switch (c) {
                case 'a':
                        acolumn = string_to_uint(optarg);
                        if (acolumn < 0)
                                error_opt_arg(c, optarg);
                        break;
+               case 'A':
+                       open_append = true;
+                       break;
                case 'b':
                        if (strcmp(optarg, "execve") != 0)
                                error_msg_and_die("Syscall '%s' for -b isn't supported",
@@ -1654,7 +1655,7 @@ init(int argc, char *argv[])
                        if (opt_intr <= 0)
                                error_opt_arg(c, optarg);
                        break;
-#ifdef USE_LIBUNWIND
+#ifdef ENABLE_STACKTRACE
                case 'k':
                        stack_trace_enabled = true;
                        break;
@@ -1711,6 +1712,16 @@ init(int argc, char *argv[])
                case 'x':
                        xflag++;
                        break;
+               case 'X':
+                       if (!strcmp(optarg, "raw"))
+                               xlat_verbosity = XLAT_STYLE_RAW;
+                       else if (!strcmp(optarg, "abbrev"))
+                               xlat_verbosity = XLAT_STYLE_ABBREV;
+                       else if (!strcmp(optarg, "verbose"))
+                               xlat_verbosity = XLAT_STYLE_VERBOSE;
+                       else
+                               error_opt_arg(c, optarg);
+                       break;
                case 'y':
                        show_fd_path++;
                        break;
@@ -1755,7 +1766,7 @@ init(int argc, char *argv[])
        if (cflag == CFLAG_ONLY_STATS) {
                if (iflag)
                        error_msg("-%c has no effect with -c", 'i');
-#ifdef USE_LIBUNWIND
+#ifdef ENABLE_STACKTRACE
                if (stack_trace_enabled)
                        error_msg("-%c has no effect with -c", 'k');
 #endif
@@ -1769,30 +1780,15 @@ init(int argc, char *argv[])
                        error_msg("-%c has no effect with -c", 'y');
        }
 
-       if (rflag) {
-               if (tflag > 1)
-                       error_msg("-tt has no effect with -r");
-               tflag = 1;
-       }
-
        acolumn_spaces = xmalloc(acolumn + 1);
        memset(acolumn_spaces, ' ', acolumn);
        acolumn_spaces[acolumn] = '\0';
 
-       sigprocmask(SIG_SETMASK, NULL, &start_set);
-       memcpy(&blocked_set, &start_set, sizeof(blocked_set));
-
        set_sighandler(SIGCHLD, SIG_DFL, &params_for_tracee.child_sa);
 
-#ifdef USE_LIBUNWIND
-       if (stack_trace_enabled) {
-               unsigned int tcbi;
-
+#ifdef ENABLE_STACKTRACE
+       if (stack_trace_enabled)
                unwind_init();
-               for (tcbi = 0; tcbi < tcbtabsize; ++tcbi) {
-                       unwind_tcb_init(tcbtab[tcbi]);
-               }
-       }
 #endif
 
        /* See if they want to run as another user. */
@@ -1895,9 +1891,9 @@ init(int argc, char *argv[])
                        set_sighandler(SIGTSTP, SIG_IGN, NULL);
                /*
                 * In interactive mode (if no -o OUTFILE, or -p PID is used),
-                * fatal signals are blocked while syscall stop is processed,
-                * and acted on in between, when waiting for new syscall stops.
-                * In non-interactive mode, signals are ignored.
+                * fatal signals are handled asynchronously and acted
+                * when waiting for process state changes.
+                * In non-interactive mode these signals are ignored.
                 */
                set_sighandler(SIGHUP, interactive ? interrupt : SIG_IGN, NULL);
                set_sighandler(SIGINT, interactive ? interrupt : SIG_IGN, NULL);
@@ -1906,6 +1902,11 @@ init(int argc, char *argv[])
                set_sighandler(SIGTERM, interactive ? interrupt : SIG_IGN, NULL);
        }
 
+       sigemptyset(&timer_set);
+       sigaddset(&timer_set, SIGALRM);
+       sigprocmask(SIG_BLOCK, &timer_set, NULL);
+       set_sighandler(SIGALRM, timer_sighandler, NULL);
+
        if (nprocs != 0 || daemonized_tracer)
                startup_attach();
 
@@ -2036,8 +2037,7 @@ maybe_allocate_tcb(const int pid, int status)
        if (followfork) {
                /* We assume it's a fork/vfork/clone child */
                struct tcb *tcp = alloctcb(pid);
-               tcp->flags |= TCB_ATTACHED | TCB_STARTUP | post_attach_sigstop;
-               newoutf(tcp);
+               after_successful_attach(tcp, post_attach_sigstop);
                if (!qflag)
                        error_msg("Process %d attached", pid);
                return tcp;
@@ -2225,7 +2225,6 @@ static enum trace_event
 next_event(int *pstatus, siginfo_t *si)
 {
        int pid;
-       int wait_errno;
        int status;
        struct tcb *tcp;
        struct rusage ru;
@@ -2254,12 +2253,42 @@ next_event(int *pstatus, siginfo_t *si)
                        return TE_BREAK;
        }
 
-       if (interactive)
-               sigprocmask(SIG_SETMASK, &start_set, NULL);
+       const bool unblock_delay_timer = is_delay_timer_armed();
+
+       /*
+        * The window of opportunity to handle expirations
+        * of the delay timer opens here.
+        *
+        * Unblock the signal handler for the delay timer
+        * iff the delay timer is already created.
+        */
+       if (unblock_delay_timer)
+               sigprocmask(SIG_UNBLOCK, &timer_set, NULL);
+
+       /*
+        * If the delay timer has expired, then its expiration
+        * has been handled already by the signal handler.
+        *
+        * If the delay timer expires during wait4(),
+        * then the system call will be interrupted and
+        * the expiration will be handled by the signal handler.
+        */
        pid = wait4(-1, pstatus, __WALL, (cflag ? &ru : NULL));
-       wait_errno = errno;
-       if (interactive)
-               sigprocmask(SIG_SETMASK, &blocked_set, NULL);
+       const int wait_errno = errno;
+
+       /*
+        * The window of opportunity to handle expirations
+        * of the delay timer closes here.
+        *
+        * Block the signal handler for the delay timer
+        * iff it was unblocked earlier.
+        */
+       if (unblock_delay_timer) {
+               sigprocmask(SIG_BLOCK, &timer_set, NULL);
+
+               if (restart_failed)
+                       return TE_BREAK;
+       }
 
        if (pid < 0) {
                if (wait_errno == EINTR)
@@ -2528,6 +2557,10 @@ dispatch_event(enum trace_event ret, int *pstatus, siginfo_t *si)
        if (interrupted)
                return false;
 
+       /* If the process is being delayed, do not ptrace_restart just yet */
+       if (syscall_delayed(current_tcp))
+               return true;
+
        if (ptrace_restart(restart_op, current_tcp, restart_sig) < 0) {
                /* Note: ptrace_restart emitted error message */
                exit_code = 1;
@@ -2536,6 +2569,74 @@ dispatch_event(enum trace_event ret, int *pstatus, siginfo_t *si)
        return true;
 }
 
+static bool
+restart_delayed_tcb(struct tcb *const tcp)
+{
+       debug_func_msg("pid %d", tcp->pid);
+
+       tcp->flags &= ~TCB_DELAYED;
+
+       struct tcb *const prev_tcp = current_tcp;
+       current_tcp = tcp;
+       bool ret = dispatch_event(TE_RESTART, NULL, NULL);
+       current_tcp = prev_tcp;
+
+       return ret;
+}
+
+static bool
+restart_delayed_tcbs(void)
+{
+       struct tcb *tcp_next = NULL;
+       struct timespec ts_now;
+
+       clock_gettime(CLOCK_MONOTONIC, &ts_now);
+
+       for (size_t i = 0; i < tcbtabsize; i++) {
+               struct tcb *tcp = tcbtab[i];
+
+               if (tcp->pid && syscall_delayed(tcp)) {
+                       if (ts_cmp(&ts_now, &tcp->delay_expiration_time) > 0) {
+                               if (!restart_delayed_tcb(tcp))
+                                       return false;
+                       } else {
+                               /* Check whether this tcb is the next.  */
+                               if (!tcp_next ||
+                                   ts_cmp(&tcp_next->delay_expiration_time,
+                                          &tcp->delay_expiration_time) > 0) {
+                                       tcp_next = tcp;
+                               }
+                       }
+               }
+       }
+
+       if (tcp_next)
+               arm_delay_timer(tcp_next);
+
+       return true;
+}
+
+/*
+ * As this signal handler does a lot of work that is not suitable
+ * for signal handlers, extra care must be taken to ensure that
+ * it is enabled only in those places where it's safe.
+ */
+static void
+timer_sighandler(int sig)
+{
+       delay_timer_expired();
+
+       if (restart_failed)
+               return;
+
+       int saved_errno = errno;
+
+       if (!restart_delayed_tcbs())
+               restart_failed = 1;
+
+       errno = saved_errno;
+}
+
 #ifdef ENABLE_COVERAGE_GCOV
 extern void __gcov_flush(void);
 #endif
@@ -2583,6 +2684,7 @@ terminate(void)
 int
 main(int argc, char *argv[])
 {
+       setlocale(LC_ALL, "");
        init(argc, argv);
 
        exit_code = !nprocs;