2 * Copyright (c) 1991, 1992 Paul Kranenburg <pk@cs.few.eur.nl>
3 * Copyright (c) 1993 Branko Lankester <branko@hacktic.nl>
4 * Copyright (c) 1993, 1994, 1995, 1996 Rick Sladkey <jrs@world.std.com>
5 * Copyright (c) 1996-1999 Wichert Akkerman <wichert@cistron.nl>
6 * Copyright (c) 1999-2018 The strace developers.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. The name of the author may not be used to endorse or promote products
18 * derived from this software without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
21 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
22 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
23 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
24 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
25 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
29 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38 #include <sys/resource.h>
48 #include <sys/utsname.h>
50 # include <sys/prctl.h>
52 #include <asm/unistd.h>
54 #include "largefile_wrappers.h"
55 #include "mmap_cache.h"
56 #include "number_set.h"
58 #include "printsiginfo.h"
59 #include "trace_event.h"
63 /* In some libc, these aren't declared. Do it ourself: */
64 extern char **environ;
68 #ifdef ENABLE_STACKTRACE
69 /* if this is true do the stack trace for every system call */
70 bool stack_trace_enabled;
73 #define my_tkill(tid, sig) syscall(__NR_tkill, (tid), (sig))
75 /* Glue for systems without a MMU that cannot provide fork() */
76 #if !defined(HAVE_FORK)
78 # define NOMMU_SYSTEM 1
81 # define fork() vfork()
84 const unsigned int syscall_trap_sig = SIGTRAP | 0x80;
86 cflag_t cflag = CFLAG_NONE;
87 unsigned int followfork;
88 unsigned int ptrace_setoptions = PTRACE_O_TRACESYSGOOD | PTRACE_O_TRACEEXEC
96 static unsigned int tflag;
98 static bool print_pid_pfx;
103 INTR_ANYWHERE = 1, /* don't block/ignore any signals */
104 INTR_WHILE_WAIT = 2, /* block fatal signals while decoding syscall. default */
105 INTR_NEVER = 3, /* block fatal signals. default if '-o FILE PROG' */
106 INTR_BLOCK_TSTP_TOO = 4, /* block fatal signals and SIGTSTP (^Z) */
110 /* We play with signal mask only if this mode is active: */
111 #define interactive (opt_intr == INTR_WHILE_WAIT)
114 * daemonized_tracer supports -D option.
115 * With this option, strace forks twice.
116 * Unlike normal case, with -D *grandparent* process exec's,
117 * becoming a traced process. Child exits (this prevents traced process
118 * from having children it doesn't expect to have), and grandchild
119 * attaches to grandparent similarly to strace -p PID.
120 * This allows for more transparent interaction in cases
121 * when process and its parent are communicating via signals,
122 * wait() etc. Without -D, strace process gets lodged in between,
123 * disrupting parent<->child link.
125 static bool daemonized_tracer;
127 static int post_attach_sigstop = TCB_IGNORE_ONE_SIGSTOP;
128 #define use_seize (post_attach_sigstop == 0)
130 /* Sometimes we want to print only succeeding syscalls. */
131 bool not_failing_only;
133 /* Show path associated with fd arguments */
134 unsigned int show_fd_path;
136 static bool detach_on_execve;
138 static int exit_code;
139 static int strace_child;
140 static int strace_tracer_pid;
142 static const char *username;
143 static uid_t run_uid;
144 static gid_t run_gid;
146 unsigned int max_strlen = DEFAULT_STRLEN;
147 static int acolumn = DEFAULT_ACOLUMN;
148 static char *acolumn_spaces;
150 /* Default output style for xlat entities */
151 enum xlat_style xlat_verbosity = XLAT_STYLE_ABBREV;
153 static const char *outfname;
154 /* If -ff, points to stderr. Else, it's our common output log */
155 static FILE *shared_log;
156 static bool open_append;
158 struct tcb *printing_tcp;
159 static struct tcb *current_tcp;
161 struct tcb_wait_data {
162 enum trace_event te; /**< Event passed to dispatch_event() */
163 int status; /**< status, returned by wait4() */
164 siginfo_t si; /**< siginfo, returned by PTRACE_GETSIGINFO */
167 static struct tcb **tcbtab;
168 static unsigned int nprocs;
169 static size_t tcbtabsize;
171 #ifndef HAVE_PROGRAM_INVOCATION_NAME
172 char *program_invocation_name;
175 unsigned os_release; /* generated from uname()'s u.release */
177 static void detach(struct tcb *tcp);
178 static void cleanup(void);
179 static void interrupt(int sig);
181 #ifdef HAVE_SIG_ATOMIC_T
182 static volatile sig_atomic_t interrupted, restart_failed;
184 static volatile int interrupted, restart_failed;
187 static sigset_t timer_set;
188 static void timer_sighandler(int);
190 #ifndef HAVE_STRERROR
192 #if !HAVE_DECL_SYS_ERRLIST
194 extern char *sys_errlist[];
200 static char buf[sizeof("Unknown error %d") + sizeof(int)*3];
202 if (err_no < 1 || err_no >= sys_nerr) {
203 xsprintf(buf, "Unknown error %d", err_no);
206 return sys_errlist[err_no];
209 #endif /* HAVE_STERRROR */
214 static const char features[] =
215 #ifdef ENABLE_STACKTRACE
216 " stack-trace=" USE_UNWINDER
221 #if SUPPORTED_PERSONALITIES > 1
222 # if defined HAVE_M32_MPERS
227 #endif /* SUPPORTED_PERSONALITIES > 1 */
228 #if SUPPORTED_PERSONALITIES > 2
229 # if defined HAVE_MX32_MPERS
234 #endif /* SUPPORTED_PERSONALITIES > 2 */
237 printf("%s -- version %s\n"
238 "Copyright (c) 1991-%s The strace developers <%s>.\n"
239 "This is free software; see the source for copying conditions. There is NO\n"
240 "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n",
241 PACKAGE_NAME, PACKAGE_VERSION, COPYRIGHT_YEAR, PACKAGE_URL);
242 printf("\nOptional features enabled:%s\n",
243 features[0] ? features : " (none)");
250 usage: strace [-CdffhiqrtttTvVwxxy] [-I n] [-e expr]...\n\
251 [-a column] [-o file] [-s strsize] [-P path]...\n\
252 -p pid... / [-D] [-E var=val]... [-u username] PROG [ARGS]\n\
253 or: strace -c[dfw] [-I n] [-e expr]... [-O overhead] [-S sortby]\n\
254 -p pid... / [-D] [-E var=val]... [-u username] PROG [ARGS]\n\
257 -a column alignment COLUMN for printing syscall results (default %d)\n\
258 -i print instruction pointer at time of syscall\n\
260 #ifdef ENABLE_STACKTRACE
262 -k obtain stack trace between each syscall\n\
266 -o file send trace output to FILE instead of stderr\n\
267 -q suppress messages about attaching, detaching, etc.\n\
268 -r print relative timestamp\n\
269 -s strsize limit length of print strings to STRSIZE chars (default %d)\n\
270 -t print absolute timestamp\n\
271 -tt print absolute timestamp with usecs\n\
272 -T print time spent in each syscall\n\
273 -x print non-ascii strings in hex\n\
274 -xx print all strings in hex\n\
275 -y print paths associated with file descriptor arguments\n\
276 -yy print protocol specific information associated with socket file descriptors\n\
279 -c count time, calls, and errors for each syscall and report summary\n\
280 -C like -c but also print regular output\n\
281 -O overhead set overhead for tracing syscalls to OVERHEAD usecs\n\
282 -S sortby sort syscall counts by: time, calls, name, nothing (default %s)\n\
283 -w summarise syscall latency (default is system time)\n\
286 -e expr a qualifying expression: option=[!]all or option=[!]val1[,val2]...\n\
287 options: trace, abbrev, verbose, raw, signal, read, write, fault, inject, kvm"
289 -P path trace accesses to path\n\
292 -b execve detach on execve syscall\n\
293 -D run tracer process as a detached grandchild, not as parent\n\
295 -ff follow forks with output into separate files\n\
297 1: no signals are blocked\n\
298 2: fatal signals are blocked while decoding syscall (default)\n\
299 3: fatal signals are always blocked (default if '-o FILE PROG')\n\
300 4: fatal signals and SIGTSTP (^Z) are always blocked\n\
301 (useful to make 'strace -o FILE PROG' not stop on ^Z)\n\
304 -E var remove var from the environment for command\n\
305 -E var=val put var=val in the environment for command\n\
306 -p pid trace process with process id PID, may be repeated\n\
307 -u username run command as username handling setuid and/or setgid\n\
310 -d enable debug output to stderr\n\
311 -v verbose mode: print unabbreviated argv, stat, termios, etc. args\n\
312 -h print help message\n\
315 /* ancient, no one should use it
316 -F -- attempt to follow vforks (deprecated, use -f)\n\
318 /* this is broken, so don't document it
319 -z -- print only succeeding syscalls\n\
321 , DEFAULT_ACOLUMN, DEFAULT_STRLEN, DEFAULT_SORTBY);
325 void ATTRIBUTE_NORETURN
328 if (strace_tracer_pid == getpid()) {
338 error_opt_arg(int opt, const char *arg)
340 error_msg_and_help("invalid -%c argument: '%s'", opt, arg);
343 static const char *ptrace_attach_cmd;
346 ptrace_attach_or_seize(int pid)
350 return ptrace_attach_cmd = "PTRACE_ATTACH",
351 ptrace(PTRACE_ATTACH, pid, 0L, 0L);
352 r = ptrace(PTRACE_SEIZE, pid, 0L, (unsigned long) ptrace_setoptions);
354 return ptrace_attach_cmd = "PTRACE_SEIZE", r;
355 r = ptrace(PTRACE_INTERRUPT, pid, 0L, 0L);
356 return ptrace_attach_cmd = "PTRACE_INTERRUPT", r;
360 * Used when we want to unblock stopped traced process.
361 * Should be only used with PTRACE_CONT, PTRACE_DETACH and PTRACE_SYSCALL.
362 * Returns 0 on success or if error was ESRCH
363 * (presumably process was killed while we talk to it).
364 * Otherwise prints error message and returns -1.
367 ptrace_restart(const unsigned int op, struct tcb *const tcp, unsigned int sig)
373 ptrace(op, tcp->pid, 0L, (unsigned long) sig);
393 * Why curcol != 0? Otherwise sometimes we get this:
395 * 10252 kill(10253, SIGKILL) = 0
396 * <ptrace(SYSCALL,10252):No such process>10253 ...next decode...
398 * 10252 died after we retrieved syscall exit data,
399 * but before we tried to restart it. Log looks ugly.
401 if (current_tcp && current_tcp->curcol != 0) {
402 tprintf(" <ptrace(%s):%s>\n", msg, strerror(err));
408 perror_msg("ptrace(PTRACE_%s,pid:%d,sig:%u)", msg, tcp->pid, sig);
413 set_cloexec_flag(int fd)
417 flags = fcntl(fd, F_GETFD);
419 /* Can happen only if fd is bad.
420 * Should never happen: if it does, we have a bug
421 * in the caller. Therefore we just abort
422 * instead of propagating the error.
424 perror_msg_and_die("fcntl(%d, F_GETFD)", fd);
427 newflags = flags | FD_CLOEXEC;
428 if (flags == newflags)
431 if (fcntl(fd, F_SETFD, newflags)) /* never fails */
432 perror_msg_and_die("fcntl(%d, F_SETFD, %#x)", fd, newflags);
436 kill_save_errno(pid_t pid, int sig)
438 int saved_errno = errno;
440 (void) kill(pid, sig);
445 * When strace is setuid executable, we have to swap uids
446 * before and after filesystem and process management operations.
451 int euid = geteuid(), uid = getuid();
453 if (euid != uid && setreuid(euid, uid) < 0) {
454 perror_msg_and_die("setreuid");
459 strace_fopen(const char *path)
464 fp = fopen_stream(path, open_append ? "a" : "w");
466 perror_msg_and_die("Can't fopen '%s'", path);
468 set_cloexec_flag(fileno(fp));
472 static int popen_pid;
475 # define _PATH_BSHELL "/bin/sh"
479 * We cannot use standard popen(3) here because we have to distinguish
480 * popen child process from other processes we trace, and standard popen(3)
481 * does not export its child's pid.
484 strace_popen(const char *command)
492 perror_msg_and_die("pipe");
494 set_cloexec_flag(fds[1]); /* never fails */
498 perror_msg_and_die("vfork");
505 perror_msg_and_die("dup2");
508 execl(_PATH_BSHELL, "sh", "-c", command, NULL);
509 perror_msg_and_die("Can't execute '%s'", _PATH_BSHELL);
516 fp = fdopen(fds[1], "w");
518 perror_msg_and_die("fdopen");
523 outf_perror(const struct tcb * const tcp)
525 if (tcp->outf == stderr)
528 /* This is ugly, but we don't store separate file names */
530 perror_msg("%s.%u", outfname, tcp->pid);
532 perror_msg("%s", outfname);
535 ATTRIBUTE_FORMAT((printf, 1, 0))
537 tvprintf(const char *const fmt, va_list args)
540 int n = vfprintf(current_tcp->outf, fmt, args);
542 /* very unlikely due to vfprintf buffering */
543 outf_perror(current_tcp);
545 current_tcp->curcol += n;
550 tprintf(const char *fmt, ...)
558 #ifndef HAVE_FPUTS_UNLOCKED
559 # define fputs_unlocked fputs
563 tprints(const char *str)
566 int n = fputs_unlocked(str, current_tcp->outf);
568 current_tcp->curcol += strlen(str);
571 /* very unlikely due to fputs_unlocked buffering */
572 outf_perror(current_tcp);
577 tprints_comment(const char *const str)
580 tprintf(" /* %s */", str);
584 tprintf_comment(const char *fmt, ...)
598 flush_tcp_output(const struct tcb *const tcp)
600 if (fflush(tcp->outf))
608 current_tcp->curcol = 0;
609 flush_tcp_output(current_tcp);
612 printing_tcp->curcol = 0;
618 set_current_tcp(const struct tcb *tcp)
620 current_tcp = (struct tcb *) tcp;
622 /* Sync current_personality and stuff */
624 set_personality(current_tcp->currpers);
628 printleader(struct tcb *tcp)
630 /* If -ff, "previous tcb we printed" is always the same as current,
631 * because we have per-tcb output files.
637 set_current_tcp(printing_tcp);
638 if (printing_tcp->curcol != 0 && (followfork < 2 || printing_tcp == tcp)) {
640 * case 1: we have a shared log (i.e. not -ff), and last line
641 * wasn't finished (same or different tcb, doesn't matter).
642 * case 2: split log, we are the same tcb, but our last line
643 * didn't finish ("SIGKILL nuked us after syscall entry" etc).
645 tprints(" <unfinished ...>\n");
646 printing_tcp->curcol = 0;
651 set_current_tcp(tcp);
652 current_tcp->curcol = 0;
655 tprintf("%-5d ", tcp->pid);
656 else if (nprocs > 1 && !outfname)
657 tprintf("[pid %5u] ", tcp->pid);
661 clock_gettime(CLOCK_REALTIME, &ts);
664 tprintf("%lld.%06ld ",
665 (long long) ts.tv_sec, (long) ts.tv_nsec / 1000);
667 time_t local = ts.tv_sec;
668 char str[MAX(sizeof("HH:MM:SS"), sizeof(ts.tv_sec) * 3)];
669 struct tm *tm = localtime(&local);
672 strftime(str, sizeof(str), "%T", tm);
674 xsprintf(str, "%lld", (long long) local);
677 str, (long) ts.tv_nsec / 1000);
685 clock_gettime(CLOCK_MONOTONIC, &ts);
687 static struct timespec ots;
692 ts_sub(&dts, &ts, &ots);
695 tprintf("%s%6ld.%06ld%s ",
697 (long) dts.tv_sec, (long) dts.tv_nsec / 1000,
708 if (current_tcp->curcol < acolumn)
709 tprints(acolumn_spaces + current_tcp->curcol);
712 /* Should be only called directly *after successful attach* to a tracee.
713 * Otherwise, "strace -oFILE -ff -p<nonexistant_pid>"
714 * may create bogus empty FILE.<nonexistant_pid>, and then die.
717 after_successful_attach(struct tcb *tcp, const unsigned int flags)
719 tcp->flags |= TCB_ATTACHED | TCB_STARTUP | flags;
720 tcp->outf = shared_log; /* if not -ff mode, the same file is for all */
721 if (followfork >= 2) {
723 xsprintf(name, "%s.%u", outfname, tcp->pid);
724 tcp->outf = strace_fopen(name);
727 #ifdef ENABLE_STACKTRACE
728 if (stack_trace_enabled)
729 unwind_tcb_init(tcp);
736 /* Allocate some (more) TCBs (and expand the table).
737 We don't want to relocate the TCBs because our
738 callers have pointers and it would be a pain.
739 So tcbtab is a table of pointers. Since we never
740 free the TCBs, we allocate a single chunk of many. */
741 size_t old_tcbtabsize;
743 struct tcb **tcb_ptr;
745 old_tcbtabsize = tcbtabsize;
747 tcbtab = xgrowarray(tcbtab, &tcbtabsize, sizeof(tcbtab[0]));
748 newtcbs = xcalloc(tcbtabsize - old_tcbtabsize, sizeof(newtcbs[0]));
750 for (tcb_ptr = tcbtab + old_tcbtabsize;
751 tcb_ptr < tcbtab + tcbtabsize; tcb_ptr++, newtcbs++)
761 if (nprocs == tcbtabsize)
764 for (i = 0; i < tcbtabsize; i++) {
767 memset(tcp, 0, sizeof(*tcp));
769 #if SUPPORTED_PERSONALITIES > 1
770 tcp->currpers = current_personality;
773 debug_msg("new tcb for pid %d, active tcbs:%d",
778 error_msg_and_die("bug in alloctcb");
782 get_tcb_priv_data(const struct tcb *tcp)
784 return tcp->_priv_data;
788 set_tcb_priv_data(struct tcb *tcp, void *const priv_data,
789 void (*const free_priv_data)(void *))
794 tcp->_free_priv_data = free_priv_data;
795 tcp->_priv_data = priv_data;
801 free_tcb_priv_data(struct tcb *tcp)
803 if (tcp->_priv_data) {
804 if (tcp->_free_priv_data) {
805 tcp->_free_priv_data(tcp->_priv_data);
806 tcp->_free_priv_data = NULL;
808 tcp->_priv_data = NULL;
813 droptcb(struct tcb *tcp)
819 for (p = 0; p < SUPPORTED_PERSONALITIES; ++p)
820 free(tcp->inject_vec[p]);
822 free_tcb_priv_data(tcp);
824 #ifdef ENABLE_STACKTRACE
825 if (stack_trace_enabled)
829 #ifdef HAVE_LINUX_KVM_H
830 kvm_vcpu_info_free(tcp);
834 tcp->mmap_cache->free_fn(tcp, __func__);
837 debug_msg("dropped tcb for pid %d, %d remain", tcp->pid, nprocs);
840 if (followfork >= 2) {
841 if (tcp->curcol != 0)
842 fprintf(tcp->outf, " <detached ...>\n");
845 if (printing_tcp == tcp && tcp->curcol != 0)
846 fprintf(tcp->outf, " <detached ...>\n");
847 flush_tcp_output(tcp);
851 if (current_tcp == tcp)
852 set_current_tcp(NULL);
853 if (printing_tcp == tcp)
856 memset(tcp, 0, sizeof(*tcp));
859 /* Detach traced process.
860 * Never call DETACH twice on the same process as both unattached and
861 * attached-unstopped processes give the same ESRCH. For unattached process we
862 * would SIGSTOP it and wait for its SIGSTOP notification forever.
865 detach(struct tcb *tcp)
871 * Linux wrongly insists the child be stopped
872 * before detaching. Arghh. We go through hoops
873 * to make a clean break of things.
876 if (!(tcp->flags & TCB_ATTACHED))
879 /* We attached but possibly didn't see the expected SIGSTOP.
880 * We must catch exactly one as otherwise the detached process
881 * would be left stopped (process state T).
883 if (tcp->flags & TCB_IGNORE_ONE_SIGSTOP)
886 error = ptrace(PTRACE_DETACH, tcp->pid, 0, 0);
888 /* On a clear day, you can see forever. */
891 if (errno != ESRCH) {
892 /* Shouldn't happen. */
893 perror_func_msg("ptrace(PTRACE_DETACH,%u)", tcp->pid);
896 /* ESRCH: process is either not stopped or doesn't exist. */
897 if (my_tkill(tcp->pid, 0) < 0) {
899 /* Shouldn't happen. */
900 perror_func_msg("tkill(%u,0)", tcp->pid);
901 /* else: process doesn't exist. */
904 /* Process is not stopped, need to stop it. */
907 * With SEIZE, tracee can be in group-stop already.
908 * In this state sending it another SIGSTOP does nothing.
909 * Need to use INTERRUPT.
910 * Testcase: trying to ^C a "strace -p <stopped_process>".
912 error = ptrace(PTRACE_INTERRUPT, tcp->pid, 0, 0);
916 perror_func_msg("ptrace(PTRACE_INTERRUPT,%u)", tcp->pid);
918 error = my_tkill(tcp->pid, SIGSTOP);
922 perror_func_msg("tkill(%u,SIGSTOP)", tcp->pid);
924 /* Either process doesn't exist, or some weird error. */
928 /* We end up here in three cases:
929 * 1. We sent PTRACE_INTERRUPT (use_seize case)
930 * 2. We sent SIGSTOP (!use_seize)
931 * 3. Attach SIGSTOP was already pending (TCB_IGNORE_ONE_SIGSTOP set)
935 if (waitpid(tcp->pid, &status, __WALL) < 0) {
939 * if (errno == ECHILD) break;
940 * ^^^ WRONG! We expect this PID to exist,
941 * and want to emit a message otherwise:
943 perror_func_msg("waitpid(%u)", tcp->pid);
946 if (!WIFSTOPPED(status)) {
948 * Tracee exited or was killed by signal.
949 * We shouldn't normally reach this place:
950 * we don't want to consume exit status.
951 * Consider "strace -p PID" being ^C-ed:
952 * we want merely to detach from PID.
954 * However, we _can_ end up here if tracee
959 sig = WSTOPSIG(status);
960 debug_msg("detach wait: event:%d sig:%d",
961 (unsigned) status >> 16, sig);
963 unsigned event = (unsigned)status >> 16;
964 if (event == PTRACE_EVENT_STOP /*&& sig == SIGTRAP*/) {
966 * sig == SIGTRAP: PTRACE_INTERRUPT stop.
967 * sig == other: process was already stopped
968 * with this stopping sig (see tests/detach-stopped).
969 * Looks like re-injecting this sig is not necessary
970 * in DETACH for the tracee to remain stopped.
975 * PTRACE_INTERRUPT is not guaranteed to produce
976 * the above event if other ptrace-stop is pending.
977 * See tests/detach-sleeping testcase:
978 * strace got SIGINT while tracee is sleeping.
979 * We sent PTRACE_INTERRUPT.
980 * We see syscall exit, not PTRACE_INTERRUPT stop.
981 * We won't get PTRACE_INTERRUPT stop
982 * if we would CONT now. Need to DETACH.
984 if (sig == syscall_trap_sig)
986 /* else: not sure in which case we can be here.
987 * Signal stop? Inject it while detaching.
989 ptrace_restart(PTRACE_DETACH, tcp, sig);
992 /* Note: this check has to be after use_seize check */
993 /* (else, in use_seize case SIGSTOP will be mistreated) */
994 if (sig == SIGSTOP) {
995 /* Detach, suppressing SIGSTOP */
996 ptrace_restart(PTRACE_DETACH, tcp, 0);
999 if (sig == syscall_trap_sig)
1001 /* Can't detach just yet, may need to wait for SIGSTOP */
1002 error = ptrace_restart(PTRACE_CONT, tcp, sig);
1004 /* Should not happen.
1005 * Note: ptrace_restart returns 0 on ESRCH, so it's not it.
1006 * ptrace_restart already emitted error message.
1013 if (!qflag && (tcp->flags & TCB_ATTACHED))
1014 error_msg("Process %u detached", tcp->pid);
1020 process_opt_p_list(char *opt)
1024 * We accept -p PID,PID; -p "`pidof PROG`"; -p "`pgrep PROG`".
1025 * pidof uses space as delim, pgrep uses newline. :(
1028 char *delim = opt + strcspn(opt, "\n\t ,");
1032 pid = string_to_uint(opt);
1034 error_msg_and_die("Invalid process id: '%s'", opt);
1036 if (pid == strace_tracer_pid) {
1037 error_msg_and_die("I'm sorry, I can't let you do that, Dave.");
1048 attach_tcb(struct tcb *const tcp)
1050 if (ptrace_attach_or_seize(tcp->pid) < 0) {
1051 perror_msg("attach: ptrace(%s, %d)",
1052 ptrace_attach_cmd, tcp->pid);
1057 after_successful_attach(tcp, TCB_GRABBED | post_attach_sigstop);
1058 debug_msg("attach to pid %d (main) succeeded", tcp->pid);
1060 static const char task_path[] = "/proc/%d/task";
1061 char procdir[sizeof(task_path) + sizeof(int) * 3];
1063 unsigned int ntid = 0, nerr = 0;
1065 if (followfork && tcp->pid != strace_child &&
1066 xsprintf(procdir, task_path, tcp->pid) > 0 &&
1067 (dir = opendir(procdir)) != NULL) {
1070 while ((de = read_dir(dir)) != NULL) {
1071 if (de->d_fileno == 0)
1074 int tid = string_to_uint(de->d_name);
1075 if (tid <= 0 || tid == tcp->pid)
1079 if (ptrace_attach_or_seize(tid) < 0) {
1081 debug_perror_msg("attach: ptrace(%s, %d)",
1082 ptrace_attach_cmd, tid);
1086 after_successful_attach(alloctcb(tid),
1087 TCB_GRABBED | post_attach_sigstop);
1088 debug_msg("attach to pid %d succeeded", tid);
1096 error_msg("Process %u attached"
1098 tcp->pid, ntid - nerr + 1);
1100 error_msg("Process %u attached",
1106 startup_attach(void)
1108 pid_t parent_pid = strace_tracer_pid;
1112 if (daemonized_tracer) {
1115 perror_func_msg_and_die("fork");
1117 if (pid) { /* parent */
1119 * Wait for grandchild to attach to straced process
1120 * (grandparent). Grandchild SIGKILLs us after it attached.
1121 * Grandparent's wait() is unblocked by our death,
1122 * it proceeds to exec the straced program.
1125 _exit(0); /* paranoia */
1128 /* We will be the tracer process. Remember our new pid: */
1129 strace_tracer_pid = getpid();
1132 for (tcbi = 0; tcbi < tcbtabsize; tcbi++) {
1138 /* Is this a process we should attach to, but not yet attached? */
1139 if (tcp->flags & TCB_ATTACHED)
1140 continue; /* no, we already attached it */
1142 if (tcp->pid == parent_pid || tcp->pid == strace_tracer_pid) {
1144 perror_msg("attach: pid %d", tcp->pid);
1153 } /* for each tcbtab[] */
1155 if (daemonized_tracer) {
1157 * Make parent go away.
1158 * Also makes grandparent's wait() unblock.
1160 kill(parent_pid, SIGKILL);
1165 /* Stack-o-phobic exec helper, in the hope to work around
1166 * NOMMU + "daemonized tracer" difficulty.
1168 struct exec_params {
1174 struct sigaction child_sa;
1176 static struct exec_params params_for_tracee;
1178 static void ATTRIBUTE_NOINLINE ATTRIBUTE_NORETURN
1181 struct exec_params *params = ¶ms_for_tracee;
1183 if (params->fd_to_close >= 0)
1184 close(params->fd_to_close);
1185 if (!daemonized_tracer && !use_seize) {
1186 if (ptrace(PTRACE_TRACEME, 0L, 0L, 0L) < 0) {
1187 perror_msg_and_die("ptrace(PTRACE_TRACEME, ...)");
1191 if (username != NULL) {
1193 * It is important to set groups before we
1194 * lose privileges on setuid.
1196 if (initgroups(username, run_gid) < 0) {
1197 perror_msg_and_die("initgroups");
1199 if (setregid(run_gid, params->run_egid) < 0) {
1200 perror_msg_and_die("setregid");
1202 if (setreuid(run_uid, params->run_euid) < 0) {
1203 perror_msg_and_die("setreuid");
1205 } else if (geteuid() != 0)
1206 if (setreuid(run_uid, run_uid) < 0) {
1207 perror_msg_and_die("setreuid");
1210 if (!daemonized_tracer) {
1212 * Induce a ptrace stop. Tracer (our parent)
1213 * will resume us with PTRACE_SYSCALL and display
1214 * the immediately following execve syscall.
1215 * Can't do this on NOMMU systems, we are after
1216 * vfork: parent is blocked, stopping would deadlock.
1219 kill(getpid(), SIGSTOP);
1222 /* we depend on SIGCHLD set to SIG_DFL by init code */
1223 /* if it happens to be SIG_IGN'ed, wait won't block */
1228 if (params_for_tracee.child_sa.sa_handler != SIG_DFL)
1229 sigaction(SIGCHLD, ¶ms_for_tracee.child_sa, NULL);
1231 execv(params->pathname, params->argv);
1232 perror_msg_and_die("exec");
1236 * Open a dummy descriptor for use as a placeholder.
1237 * The descriptor is O_RDONLY with FD_CLOEXEC flag set.
1238 * A read attempt from such descriptor ends with EOF,
1239 * a write attempt is rejected with EBADF.
1242 open_dummy_desc(void)
1247 perror_func_msg_and_die("pipe");
1249 set_cloexec_flag(fds[0]);
1253 /* placeholder fds status for stdin and stdout */
1254 static bool fd_is_placeholder[2];
1257 * Ensure that all standard file descriptors are open by opening placeholder
1258 * file descriptors for those standard file descriptors that are not open.
1260 * The information which descriptors have been made open is saved
1261 * in fd_is_placeholder for later use.
1264 ensure_standard_fds_opened(void)
1268 while ((fd = open_dummy_desc()) <= 2) {
1271 fd_is_placeholder[fd] = true;
1279 * Redirect stdin and stdout unless they have been opened earlier
1280 * by ensure_standard_fds_opened as placeholders.
1283 redirect_standard_fds(void)
1288 * It might be a good idea to redirect stderr as well,
1289 * but we sometimes need to print error messages.
1291 for (i = 0; i <= 1; ++i) {
1292 if (!fd_is_placeholder[i]) {
1300 startup_child(char **argv)
1302 struct_stat statbuf;
1303 const char *filename;
1304 size_t filename_len;
1305 char pathname[PATH_MAX];
1310 filename_len = strlen(filename);
1312 if (filename_len > sizeof(pathname) - 1) {
1313 errno = ENAMETOOLONG;
1314 perror_msg_and_die("exec");
1316 if (strchr(filename, '/')) {
1317 strcpy(pathname, filename);
1319 #ifdef USE_DEBUGGING_EXEC
1321 * Debuggers customarily check the current directory
1322 * first regardless of the path but doing that gives
1323 * security geeks a panic attack.
1325 else if (stat_file(filename, &statbuf) == 0)
1326 strcpy(pathname, filename);
1327 #endif /* USE_DEBUGGING_EXEC */
1332 for (path = getenv("PATH"); path && *path; path += m) {
1333 const char *colon = strchr(path, ':');
1338 m = n = strlen(path);
1340 if (!getcwd(pathname, PATH_MAX))
1342 len = strlen(pathname);
1343 } else if (n > sizeof(pathname) - 1)
1346 strncpy(pathname, path, n);
1349 if (len && pathname[len - 1] != '/')
1350 pathname[len++] = '/';
1351 if (filename_len + len > sizeof(pathname) - 1)
1353 strcpy(pathname + len, filename);
1354 if (stat_file(pathname, &statbuf) == 0 &&
1355 /* Accept only regular files
1356 with some execute bits set.
1357 XXX not perfect, might still fail */
1358 S_ISREG(statbuf.st_mode) &&
1359 (statbuf.st_mode & 0111))
1362 if (!path || !*path)
1365 if (stat_file(pathname, &statbuf) < 0) {
1366 perror_msg_and_die("Can't stat '%s'", filename);
1369 params_for_tracee.fd_to_close = (shared_log != stderr) ? fileno(shared_log) : -1;
1370 params_for_tracee.run_euid = (statbuf.st_mode & S_ISUID) ? statbuf.st_uid : run_uid;
1371 params_for_tracee.run_egid = (statbuf.st_mode & S_ISGID) ? statbuf.st_gid : run_gid;
1372 params_for_tracee.argv = argv;
1374 * On NOMMU, can be safely freed only after execve in tracee.
1375 * It's hard to know when that happens, so we just leak it.
1377 params_for_tracee.pathname = NOMMU_SYSTEM ? xstrdup(pathname) : pathname;
1379 #if defined HAVE_PRCTL && defined PR_SET_PTRACER && defined PR_SET_PTRACER_ANY
1380 if (daemonized_tracer)
1381 prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY);
1386 perror_func_msg_and_die("fork");
1388 if ((pid != 0 && daemonized_tracer)
1389 || (pid == 0 && !daemonized_tracer)
1391 /* We are to become the tracee. Two cases:
1393 * not -D: we are child
1398 /* We are the tracer */
1400 if (!daemonized_tracer) {
1403 /* child did PTRACE_TRACEME, nothing to do in parent */
1405 if (!NOMMU_SYSTEM) {
1406 /* Wait until child stopped itself */
1408 while (waitpid(pid, &status, WSTOPPED) < 0) {
1411 perror_msg_and_die("waitpid");
1413 if (!WIFSTOPPED(status) || WSTOPSIG(status) != SIGSTOP) {
1414 kill_save_errno(pid, SIGKILL);
1415 perror_msg_and_die("Unexpected wait status %#x",
1419 /* Else: NOMMU case, we have no way to sync.
1420 * Just attach to it as soon as possible.
1421 * This means that we may miss a few first syscalls...
1424 if (ptrace_attach_or_seize(pid)) {
1425 kill_save_errno(pid, SIGKILL);
1426 perror_msg_and_die("attach: ptrace(%s, %d)",
1427 ptrace_attach_cmd, pid);
1432 tcp = alloctcb(pid);
1433 after_successful_attach(tcp, TCB_SKIP_DETACH_ON_FIRST_EXEC
1436 | post_attach_sigstop)));
1438 /* With -D, we are *child* here, the tracee is our parent. */
1439 strace_child = strace_tracer_pid;
1440 strace_tracer_pid = getpid();
1441 tcp = alloctcb(strace_child);
1442 tcp->flags |= TCB_SKIP_DETACH_ON_FIRST_EXEC | TCB_HIDE_LOG;
1444 * Attaching will be done later, by startup_attach.
1445 * Note: we don't do after_successful_attach() here either!
1448 /* NOMMU BUG! -D mode is active, we (child) return,
1449 * and we will scribble over parent's stack!
1450 * When parent later unpauses, it segfaults.
1453 * (1) by declaring exec_or_die() NORETURN,
1454 * hopefully compiler will just jump to it
1455 * instead of call (won't push anything to stack),
1456 * (2) by trying very hard in exec_or_die()
1457 * to not use any stack,
1458 * (3) having a really big (PATH_MAX) stack object
1459 * in this function, which creates a "buffer" between
1460 * child's and parent's stack pointers.
1461 * This may save us if (1) and (2) failed
1462 * and compiler decided to use stack in exec_or_die() anyway
1463 * (happens on i386 because of stack parameter passing).
1465 * A cleaner solution is to use makecontext + setcontext
1466 * to create a genuine separate stack and execute on it.
1470 * A case where straced process is part of a pipe:
1471 * { sleep 1; yes | head -n99999; } | strace -o/dev/null sh -c 'exec <&-; sleep 9'
1472 * If strace won't close its fd#0, closing it in tracee is not enough:
1473 * the pipe is still open, it has a reader. Thus, "head" will not get its
1474 * SIGPIPE at once, on the first write.
1476 * Preventing it by redirecting strace's stdin/out.
1477 * (Don't leave fds 0 and 1 closed, this is bad practice: future opens
1478 * will reuse them, unexpectedly making a newly opened object "stdin").
1480 redirect_standard_fds();
1484 test_ptrace_seize(void)
1488 /* Need fork for test. NOMMU has no forks */
1490 post_attach_sigstop = 0; /* this sets use_seize to 1 */
1496 perror_func_msg_and_die("fork");
1503 /* PTRACE_SEIZE, unlike ATTACH, doesn't force tracee to trap. After
1504 * attaching tracee continues to run unless a trap condition occurs.
1505 * PTRACE_SEIZE doesn't affect signal or group stop state.
1507 if (ptrace(PTRACE_SEIZE, pid, 0, 0) == 0) {
1508 post_attach_sigstop = 0; /* this sets use_seize to 1 */
1510 debug_msg("PTRACE_SEIZE doesn't work");
1516 int status, tracee_pid;
1519 tracee_pid = waitpid(pid, &status, 0);
1520 if (tracee_pid <= 0) {
1523 perror_func_msg_and_die("unexpected wait result %d",
1526 if (WIFSIGNALED(status))
1529 error_func_msg_and_die("unexpected wait status %#x", status);
1534 get_os_release(void)
1540 perror_msg_and_die("uname");
1541 /* u.release has this form: "3.2.9[-some-garbage]" */
1545 if (!(*p >= '0' && *p <= '9'))
1546 error_msg_and_die("Bad OS release string: '%s'", u.release);
1547 /* Note: this open-codes KERNEL_VERSION(): */
1548 rel = (rel << 8) | atoi(p);
1549 if (rel >= KERNEL_VERSION(1, 0, 0))
1551 while (*p >= '0' && *p <= '9')
1554 if (rel >= KERNEL_VERSION(0, 1, 0)) {
1555 /* "X.Y-something" means "X.Y.0" */
1559 error_msg_and_die("Bad OS release string: '%s'", u.release);
1567 set_sighandler(int signo, void (*sighandler)(int), struct sigaction *oldact)
1569 const struct sigaction sa = { .sa_handler = sighandler };
1570 sigaction(signo, &sa, oldact);
1574 * Initialization part of main() was eating much stack (~0.5k),
1575 * which was unused after init.
1576 * We can reuse it if we move init code into a separate function.
1578 * Don't want main() to inline us and defeat the reason
1579 * we have a separate function.
1581 static void ATTRIBUTE_NOINLINE
1582 init(int argc, char *argv[])
1587 if (!program_invocation_name || !*program_invocation_name) {
1588 static char name[] = "strace";
1589 program_invocation_name =
1590 (argc > 0 && argv[0] && *argv[0]) ? argv[0] : name;
1593 strace_tracer_pid = getpid();
1595 os_release = get_os_release();
1597 shared_log = stderr;
1598 set_sortby(DEFAULT_SORTBY);
1599 set_personality(DEFAULT_PERSONALITY);
1600 qualify("trace=all");
1601 qualify("abbrev=all");
1602 qualify("verbose=all");
1603 #if DEFAULT_QUAL_FLAGS != (QUAL_TRACE | QUAL_ABBREV | QUAL_VERBOSE)
1604 # error Bug in DEFAULT_QUAL_FLAGS
1606 qualify("signal=all");
1607 while ((c = getopt(argc, argv, "+"
1608 #ifdef ENABLE_STACKTRACE
1611 "a:Ab:cCdDe:E:fFhiI:o:O:p:P:qrs:S:tTu:vVwxX:yz")) != EOF) {
1614 acolumn = string_to_uint(optarg);
1616 error_opt_arg(c, optarg);
1622 if (strcmp(optarg, "execve") != 0)
1623 error_msg_and_die("Syscall '%s' for -b isn't supported",
1625 detach_on_execve = 1;
1628 if (cflag == CFLAG_BOTH) {
1629 error_msg_and_help("-c and -C are mutually exclusive");
1631 cflag = CFLAG_ONLY_STATS;
1634 if (cflag == CFLAG_ONLY_STATS) {
1635 error_msg_and_help("-c and -C are mutually exclusive");
1643 daemonized_tracer = 1;
1649 if (putenv(optarg) < 0)
1650 perror_msg_and_die("putenv");
1665 opt_intr = string_to_uint_upto(optarg, NUM_INTR_OPTS - 1);
1667 error_opt_arg(c, optarg);
1669 #ifdef ENABLE_STACKTRACE
1671 stack_trace_enabled = true;
1678 i = string_to_uint(optarg);
1680 error_opt_arg(c, optarg);
1684 process_opt_p_list(optarg);
1687 pathtrace_select(optarg);
1696 i = string_to_uint(optarg);
1697 if (i < 0 || (unsigned int) i > -1U / 4)
1698 error_opt_arg(c, optarg);
1714 qualify("abbrev=none");
1721 count_wallclock = 1;
1727 if (!strcmp(optarg, "raw"))
1728 xlat_verbosity = XLAT_STYLE_RAW;
1729 else if (!strcmp(optarg, "abbrev"))
1730 xlat_verbosity = XLAT_STYLE_ABBREV;
1731 else if (!strcmp(optarg, "verbose"))
1732 xlat_verbosity = XLAT_STYLE_VERBOSE;
1734 error_opt_arg(c, optarg);
1740 not_failing_only = 1;
1743 error_msg_and_help(NULL);
1751 if (argc < 0 || (!nprocs && !argc)) {
1752 error_msg_and_help("must have PROG [ARGS] or -p PID");
1755 if (!argc && daemonized_tracer) {
1756 error_msg_and_help("PROG [ARGS] must be specified with -D");
1761 error_msg("deprecated option -F ignored");
1763 error_msg("option -F is deprecated, "
1764 "please use -f instead");
1769 if (followfork >= 2 && cflag) {
1770 error_msg_and_help("(-c or -C) and -ff are mutually exclusive");
1773 if (count_wallclock && !cflag) {
1774 error_msg_and_help("-w must be given with (-c or -C)");
1777 if (cflag == CFLAG_ONLY_STATS) {
1779 error_msg("-%c has no effect with -c", 'i');
1780 #ifdef ENABLE_STACKTRACE
1781 if (stack_trace_enabled)
1782 error_msg("-%c has no effect with -c", 'k');
1785 error_msg("-%c has no effect with -c", 'r');
1787 error_msg("-%c has no effect with -c", 't');
1789 error_msg("-%c has no effect with -c", 'T');
1791 error_msg("-%c has no effect with -c", 'y');
1794 acolumn_spaces = xmalloc(acolumn + 1);
1795 memset(acolumn_spaces, ' ', acolumn);
1796 acolumn_spaces[acolumn] = '\0';
1798 set_sighandler(SIGCHLD, SIG_DFL, ¶ms_for_tracee.child_sa);
1800 #ifdef ENABLE_STACKTRACE
1801 if (stack_trace_enabled)
1805 /* See if they want to run as another user. */
1806 if (username != NULL) {
1807 struct passwd *pent;
1809 if (getuid() != 0 || geteuid() != 0) {
1810 error_msg_and_die("You must be root to use the -u option");
1812 pent = getpwnam(username);
1814 error_msg_and_die("Cannot find user '%s'", username);
1816 run_uid = pent->pw_uid;
1817 run_gid = pent->pw_gid;
1824 ptrace_setoptions |= PTRACE_O_TRACECLONE |
1825 PTRACE_O_TRACEFORK |
1826 PTRACE_O_TRACEVFORK;
1827 debug_msg("ptrace_setoptions = %#x", ptrace_setoptions);
1828 test_ptrace_seize();
1831 * Is something weird with our stdin and/or stdout -
1832 * for example, may they be not open? In this case,
1833 * ensure that none of the future opens uses them.
1835 * This was seen in the wild when /proc/sys/kernel/core_pattern
1836 * was set to "|/bin/strace -o/tmp/LOG PROG":
1837 * kernel runs coredump helper with fd#0 open but fd#1 closed (!),
1838 * therefore LOG gets opened to fd#1, and fd#1 is closed by
1839 * "don't hold up stdin/out open" code soon after.
1841 ensure_standard_fds_opened();
1843 /* Check if they want to redirect the output. */
1845 /* See if they want to pipe the output. */
1846 if (outfname[0] == '|' || outfname[0] == '!') {
1848 * We can't do the <outfname>.PID funny business
1849 * when using popen, so prohibit it.
1851 if (followfork >= 2)
1852 error_msg_and_help("piping the output and -ff "
1853 "are mutually exclusive");
1854 shared_log = strace_popen(outfname + 1);
1855 } else if (followfork < 2) {
1856 shared_log = strace_fopen(outfname);
1857 } else if (strlen(outfname) >= PATH_MAX - sizeof(int) * 3) {
1858 errno = ENAMETOOLONG;
1859 perror_msg_and_die("%s", outfname);
1862 /* -ff without -o FILE is the same as single -f */
1863 if (followfork >= 2)
1867 if (!outfname || outfname[0] == '|' || outfname[0] == '!') {
1868 setvbuf(shared_log, NULL, _IOLBF, 0);
1872 * argv[0] -pPID -oFILE Default interactive setting
1873 * yes * 0 INTR_WHILE_WAIT
1874 * no 1 0 INTR_WHILE_WAIT
1875 * yes * 1 INTR_NEVER
1876 * no 1 1 INTR_WHILE_WAIT
1879 if (outfname && argc) {
1881 opt_intr = INTR_NEVER;
1886 opt_intr = INTR_WHILE_WAIT;
1889 * startup_child() must be called before the signal handlers get
1890 * installed below as they are inherited into the spawned process.
1891 * Also we do not need to be protected by them as during interruption
1892 * in the startup_child() mode we kill the spawned process anyway.
1895 startup_child(argv);
1898 set_sighandler(SIGTTOU, SIG_IGN, NULL);
1899 set_sighandler(SIGTTIN, SIG_IGN, NULL);
1900 if (opt_intr != INTR_ANYWHERE) {
1901 if (opt_intr == INTR_BLOCK_TSTP_TOO)
1902 set_sighandler(SIGTSTP, SIG_IGN, NULL);
1904 * In interactive mode (if no -o OUTFILE, or -p PID is used),
1905 * fatal signals are handled asynchronously and acted
1906 * when waiting for process state changes.
1907 * In non-interactive mode these signals are ignored.
1909 set_sighandler(SIGHUP, interactive ? interrupt : SIG_IGN, NULL);
1910 set_sighandler(SIGINT, interactive ? interrupt : SIG_IGN, NULL);
1911 set_sighandler(SIGQUIT, interactive ? interrupt : SIG_IGN, NULL);
1912 set_sighandler(SIGPIPE, interactive ? interrupt : SIG_IGN, NULL);
1913 set_sighandler(SIGTERM, interactive ? interrupt : SIG_IGN, NULL);
1916 sigemptyset(&timer_set);
1917 sigaddset(&timer_set, SIGALRM);
1918 sigprocmask(SIG_BLOCK, &timer_set, NULL);
1919 set_sighandler(SIGALRM, timer_sighandler, NULL);
1921 if (nprocs != 0 || daemonized_tracer)
1924 /* Do we want pids printed in our -o OUTFILE?
1925 * -ff: no (every pid has its own file); or
1926 * -f: yes (there can be more pids in the future); or
1927 * -p PID1,PID2: yes (there are already more than one pid)
1929 print_pid_pfx = (outfname && followfork < 2 && (followfork == 1 || nprocs > 1));
1933 pid2tcb(const int pid)
1938 #define PID2TCB_CACHE_SIZE 1024U
1939 #define PID2TCB_CACHE_MASK (PID2TCB_CACHE_SIZE - 1)
1941 static struct tcb *pid2tcb_cache[PID2TCB_CACHE_SIZE];
1942 struct tcb **const ptcp = &pid2tcb_cache[pid & PID2TCB_CACHE_MASK];
1943 struct tcb *tcp = *ptcp;
1945 if (tcp && tcp->pid == pid)
1948 for (unsigned int i = 0; i < tcbtabsize; ++i) {
1950 if (tcp->pid == pid)
1964 /* 'interrupted' is a volatile object, fetch it only once */
1965 fatal_sig = interrupted;
1967 fatal_sig = SIGTERM;
1969 for (i = 0; i < tcbtabsize; i++) {
1973 debug_func_msg("looking at pid %u", tcp->pid);
1974 if (tcp->pid == strace_child) {
1975 kill(tcp->pid, SIGCONT);
1976 kill(tcp->pid, fatal_sig);
1981 call_summary(shared_log);
1991 print_debug_info(const int pid, int status)
1993 const unsigned int event = (unsigned int) status >> 16;
1994 char buf[sizeof("WIFEXITED,exitcode=%u") + sizeof(int)*3 /*paranoia:*/ + 16];
1995 char evbuf[sizeof(",EVENT_VFORK_DONE (%u)") + sizeof(int)*3 /*paranoia:*/ + 16];
1998 if (WIFSIGNALED(status))
2000 xsprintf(buf, "WIFSIGNALED,%ssig=%s",
2001 WCOREDUMP(status) ? "core," : "",
2002 signame(WTERMSIG(status)));
2004 xsprintf(buf, "WIFSIGNALED,sig=%s",
2005 signame(WTERMSIG(status)));
2007 if (WIFEXITED(status))
2008 xsprintf(buf, "WIFEXITED,exitcode=%u", WEXITSTATUS(status));
2009 if (WIFSTOPPED(status))
2010 xsprintf(buf, "WIFSTOPPED,sig=%s", signame(WSTOPSIG(status)));
2013 static const char *const event_names[] = {
2014 [PTRACE_EVENT_CLONE] = "CLONE",
2015 [PTRACE_EVENT_FORK] = "FORK",
2016 [PTRACE_EVENT_VFORK] = "VFORK",
2017 [PTRACE_EVENT_VFORK_DONE] = "VFORK_DONE",
2018 [PTRACE_EVENT_EXEC] = "EXEC",
2019 [PTRACE_EVENT_EXIT] = "EXIT",
2020 /* [PTRACE_EVENT_STOP (=128)] would make biggish array */
2022 const char *e = "??";
2023 if (event < ARRAY_SIZE(event_names))
2024 e = event_names[event];
2025 else if (event == PTRACE_EVENT_STOP)
2027 xsprintf(evbuf, ",EVENT_%s (%u)", e, event);
2029 error_msg("[wait(0x%06x) = %u] %s%s", status, pid, buf, evbuf);
2033 maybe_allocate_tcb(const int pid, int status)
2035 if (!WIFSTOPPED(status)) {
2036 if (detach_on_execve && pid == strace_child) {
2037 /* example: strace -bexecve sh -c 'exec true' */
2042 * This can happen if we inherited an unknown child.
2043 * Example: (sleep 1 & exec strace true)
2045 error_msg("Exit of unknown pid %u ignored", pid);
2049 /* We assume it's a fork/vfork/clone child */
2050 struct tcb *tcp = alloctcb(pid);
2051 after_successful_attach(tcp, post_attach_sigstop);
2053 error_msg("Process %d attached", pid);
2057 * This can happen if a clone call misused CLONE_PTRACE itself.
2059 * There used to be a dance around possible re-injection of
2060 * WSTOPSIG(status), but it was later removed as the only
2061 * observable stop here is the initial ptrace-stop.
2063 ptrace(PTRACE_DETACH, pid, NULL, 0L);
2064 error_msg("Detached unknown pid %d", pid);
2070 maybe_switch_tcbs(struct tcb *tcp, const int pid)
2073 struct tcb *execve_thread;
2076 if (ptrace(PTRACE_GETEVENTMSG, pid, NULL, &old_pid) < 0)
2078 /* Avoid truncation in pid2tcb() param passing */
2079 if (old_pid <= 0 || old_pid == pid)
2081 if ((unsigned long) old_pid > UINT_MAX)
2083 execve_thread = pid2tcb(old_pid);
2084 /* It should be !NULL, but I feel paranoid */
2088 if (execve_thread->curcol != 0) {
2090 * One case we are here is -ff:
2091 * try "strace -oLOG -ff test/threaded_execve"
2093 fprintf(execve_thread->outf, " <pid changed to %d ...>\n", pid);
2094 /*execve_thread->curcol = 0; - no need, see code below */
2096 /* Swap output FILEs (needed for -ff) */
2097 fp = execve_thread->outf;
2098 execve_thread->outf = tcp->outf;
2100 /* And their column positions */
2101 execve_thread->curcol = tcp->curcol;
2103 /* Drop leader, but close execve'd thread outfile (if -ff) */
2105 /* Switch to the thread, reusing leader's outfile and pid */
2106 tcp = execve_thread;
2108 if (cflag != CFLAG_ONLY_STATS) {
2110 tprintf("+++ superseded by execve in pid %lu +++\n", old_pid);
2112 tcp->flags |= TCB_REPRINT;
2119 print_signalled(struct tcb *tcp, const int pid, int status)
2121 if (pid == strace_child) {
2122 exit_code = 0x100 | WTERMSIG(status);
2126 if (cflag != CFLAG_ONLY_STATS
2127 && is_number_in_set(WTERMSIG(status), signal_set)) {
2130 tprintf("+++ killed by %s %s+++\n",
2131 signame(WTERMSIG(status)),
2132 WCOREDUMP(status) ? "(core dumped) " : "");
2134 tprintf("+++ killed by %s +++\n",
2135 signame(WTERMSIG(status)));
2142 print_exited(struct tcb *tcp, const int pid, int status)
2144 if (pid == strace_child) {
2145 exit_code = WEXITSTATUS(status);
2149 if (cflag != CFLAG_ONLY_STATS &&
2152 tprintf("+++ exited with %d +++\n", WEXITSTATUS(status));
2158 print_stopped(struct tcb *tcp, const siginfo_t *si, const unsigned int sig)
2160 if (cflag != CFLAG_ONLY_STATS
2162 && is_number_in_set(sig, signal_set)) {
2165 tprintf("--- %s ", signame(sig));
2169 tprintf("--- stopped by %s ---\n", signame(sig));
2175 startup_tcb(struct tcb *tcp)
2177 debug_msg("pid %d has TCB_STARTUP, initializing it", tcp->pid);
2179 tcp->flags &= ~TCB_STARTUP;
2182 debug_msg("setting opts 0x%x on pid %d",
2183 ptrace_setoptions, tcp->pid);
2184 if (ptrace(PTRACE_SETOPTIONS, tcp->pid, NULL, ptrace_setoptions) < 0) {
2185 if (errno != ESRCH) {
2186 /* Should never happen, really */
2187 perror_msg_and_die("PTRACE_SETOPTIONS");
2192 if ((tcp->flags & TCB_GRABBED) && (get_scno(tcp) == 1))
2193 tcp->s_prev_ent = tcp->s_ent;
2197 print_event_exit(struct tcb *tcp)
2199 if (entering(tcp) || filtered(tcp) || hide_log(tcp)
2200 || cflag == CFLAG_ONLY_STATS) {
2204 if (followfork < 2 && printing_tcp && printing_tcp != tcp
2205 && printing_tcp->curcol != 0) {
2206 set_current_tcp(printing_tcp);
2207 tprints(" <unfinished ...>\n");
2208 flush_tcp_output(printing_tcp);
2209 printing_tcp->curcol = 0;
2210 set_current_tcp(tcp);
2213 if ((followfork < 2 && printing_tcp != tcp)
2214 || (tcp->flags & TCB_REPRINT)) {
2215 tcp->flags &= ~TCB_REPRINT;
2217 tprintf("<... %s resumed>", tcp->s_ent->sys_name);
2220 if (!(tcp->sys_func_rval & RVAL_DECODED)) {
2222 * The decoder has probably decided to print something
2223 * on exiting syscall which is not going to happen.
2225 tprints(" <unfinished ...>");
2235 static const struct tcb_wait_data *
2238 static struct tcb_wait_data wait_data;
2243 struct tcb_wait_data *wd = &wait_data;
2250 * Used to exit simply when nprocs hits zero, but in this testcase:
2251 * int main(void) { _exit(!!fork()); }
2252 * under strace -f, parent sometimes (rarely) manages
2253 * to exit before we see the first stop of the child,
2254 * and we are losing track of it:
2255 * 19923 clone(...) = 19924
2256 * 19923 exit_group(1) = ?
2257 * 19923 +++ exited with 1 +++
2258 * Exiting only when wait() returns ECHILD works better.
2260 if (popen_pid != 0) {
2261 /* However, if -o|logger is in use, we can't do that.
2262 * Can work around that by double-forking the logger,
2263 * but that loses the ability to wait for its completion
2264 * on exit. Oh well...
2270 const bool unblock_delay_timer = is_delay_timer_armed();
2273 * The window of opportunity to handle expirations
2274 * of the delay timer opens here.
2276 * Unblock the signal handler for the delay timer
2277 * iff the delay timer is already created.
2279 if (unblock_delay_timer)
2280 sigprocmask(SIG_UNBLOCK, &timer_set, NULL);
2283 * If the delay timer has expired, then its expiration
2284 * has been handled already by the signal handler.
2286 * If the delay timer expires during wait4(),
2287 * then the system call will be interrupted and
2288 * the expiration will be handled by the signal handler.
2290 pid = wait4(-1, &status, __WALL, (cflag ? &ru : NULL));
2291 const int wait_errno = errno;
2294 * The window of opportunity to handle expirations
2295 * of the delay timer closes here.
2297 * Block the signal handler for the delay timer
2298 * iff it was unblocked earlier.
2300 if (unblock_delay_timer) {
2301 sigprocmask(SIG_BLOCK, &timer_set, NULL);
2308 if (wait_errno == EINTR) {
2312 if (nprocs == 0 && wait_errno == ECHILD)
2315 * If nprocs > 0, ECHILD is not expected,
2316 * treat it as any other error here:
2319 perror_msg_and_die("wait4(__WALL)");
2322 wd->status = status;
2324 if (pid == popen_pid) {
2325 if (!WIFSTOPPED(status))
2332 print_debug_info(pid, status);
2334 /* Look up 'pid' in our table. */
2338 tcp = maybe_allocate_tcb(pid, status);
2347 /* Set current output file */
2348 set_current_tcp(tcp);
2351 struct timespec stime = {
2352 .tv_sec = ru.ru_stime.tv_sec,
2353 .tv_nsec = ru.ru_stime.tv_usec * 1000
2355 ts_sub(&tcp->dtime, &stime, &tcp->stime);
2359 if (WIFSIGNALED(status)) {
2360 wd->te = TE_SIGNALLED;
2364 if (WIFEXITED(status)) {
2370 * As WCONTINUED flag has not been specified to wait4,
2371 * it cannot be WIFCONTINUED(status), so the only case
2372 * that remains is WIFSTOPPED(status).
2375 /* Is this the very first time we see this tracee stopped? */
2376 if (tcp->flags & TCB_STARTUP)
2379 const unsigned int sig = WSTOPSIG(status);
2380 const unsigned int event = (unsigned int) status >> 16;
2385 * Is this post-attach SIGSTOP?
2386 * Interestingly, the process may stop
2387 * with STOPSIG equal to some other signal
2388 * than SIGSTOP if we happened to attach
2389 * just before the process takes a signal.
2391 if (sig == SIGSTOP && (tcp->flags & TCB_IGNORE_ONE_SIGSTOP)) {
2392 debug_func_msg("ignored SIGSTOP on pid %d", tcp->pid);
2393 tcp->flags &= ~TCB_IGNORE_ONE_SIGSTOP;
2394 wd->te = TE_RESTART;
2395 } else if (sig == syscall_trap_sig) {
2396 wd->te = TE_SYSCALL_STOP;
2398 memset(&wd->si, 0, sizeof(wd->si));
2400 * True if tracee is stopped by signal
2401 * (as opposed to "tracee received signal").
2402 * TODO: shouldn't we check for errno == EINVAL too?
2403 * We can get ESRCH instead, you know...
2405 bool stopped = ptrace(PTRACE_GETSIGINFO, pid, 0, &wd->si) < 0;
2406 wd->te = stopped ? TE_GROUP_STOP : TE_SIGNAL_DELIVERY_STOP;
2409 case PTRACE_EVENT_STOP:
2411 * PTRACE_INTERRUPT-stop or group-stop.
2412 * PTRACE_INTERRUPT-stop has sig == SIGTRAP here.
2419 wd->te = TE_GROUP_STOP;
2422 wd->te = TE_RESTART;
2425 case PTRACE_EVENT_EXEC:
2426 wd->te = TE_STOP_BEFORE_EXECVE;
2428 case PTRACE_EVENT_EXIT:
2429 wd->te = TE_STOP_BEFORE_EXIT;
2432 wd->te = TE_RESTART;
2439 trace_syscall(struct tcb *tcp, unsigned int *sig)
2441 if (entering(tcp)) {
2442 int res = syscall_entering_decode(tcp);
2447 res = syscall_entering_trace(tcp, sig);
2449 syscall_entering_finish(tcp, res);
2452 struct timespec ts = {};
2453 int res = syscall_exiting_decode(tcp, &ts);
2455 res = syscall_exiting_trace(tcp, &ts, res);
2457 syscall_exiting_finish(tcp);
2462 /* Returns true iff the main trace loop has to continue. */
2464 dispatch_event(const struct tcb_wait_data *wd)
2466 unsigned int restart_op = PTRACE_SYSCALL;
2467 unsigned int restart_sig = 0;
2468 enum trace_event te = wd ? wd->te : TE_BREAK;
2470 * Copy wd->status to a non-const variable to workaround glibc bugs
2471 * around union wait fixed by glibc commit glibc-2.24~391
2473 int status = wd ? wd->status : 0;
2485 case TE_SYSCALL_STOP:
2486 if (trace_syscall(current_tcp, &restart_sig) < 0) {
2488 * ptrace() failed in trace_syscall().
2489 * Likely a result of process disappearing mid-flight.
2490 * Observed case: exit_group() or SIGKILL terminating
2491 * all processes in thread group.
2492 * We assume that ptrace error was caused by process death.
2493 * We used to detach(current_tcp) here, but since we no
2494 * longer implement "detach before death" policy/hack,
2495 * we can let this process to report its death to us
2496 * normally, via WIFEXITED or WIFSIGNALED wait status.
2502 case TE_SIGNAL_DELIVERY_STOP:
2503 restart_sig = WSTOPSIG(status);
2504 print_stopped(current_tcp, &wd->si, restart_sig);
2508 print_signalled(current_tcp, current_tcp->pid, status);
2509 droptcb(current_tcp);
2513 restart_sig = WSTOPSIG(status);
2514 print_stopped(current_tcp, NULL, restart_sig);
2517 * This ends ptrace-stop, but does *not* end group-stop.
2518 * This makes stopping signals work properly on straced
2519 * process (that is, process really stops. It used to
2522 restart_op = PTRACE_LISTEN;
2528 print_exited(current_tcp, current_tcp->pid, status);
2529 droptcb(current_tcp);
2532 case TE_STOP_BEFORE_EXECVE:
2534 * Check that we are inside syscall now (next event after
2535 * PTRACE_EVENT_EXEC should be for syscall exiting). If it is
2536 * not the case, we might have a situation when we attach to a
2537 * process and the first thing we see is a PTRACE_EVENT_EXEC
2538 * and all the following syscall state tracking is screwed up
2541 if (entering(current_tcp)) {
2544 error_msg("Stray PTRACE_EVENT_EXEC from pid %d"
2545 ", trying to recover...",
2548 current_tcp->flags |= TCB_RECOVERING;
2549 ret = trace_syscall(current_tcp, &restart_sig);
2550 current_tcp->flags &= ~TCB_RECOVERING;
2553 /* The reason is described in TE_SYSCALL_STOP */
2559 * Under Linux, execve changes pid to thread leader's pid,
2560 * and we see this changed pid on EVENT_EXEC and later,
2561 * execve sysexit. Leader "disappears" without exit
2562 * notification. Let user know that, drop leader's tcb,
2563 * and fix up pid in execve thread's tcb.
2564 * Effectively, execve thread's tcb replaces leader's tcb.
2566 * BTW, leader is 'stuck undead' (doesn't report WIFEXITED
2567 * on exit syscall) in multithreaded programs exactly
2568 * in order to handle this case.
2570 * PTRACE_GETEVENTMSG returns old pid starting from Linux 3.0.
2571 * On 2.6 and earlier, it can return garbage.
2573 if (os_release >= KERNEL_VERSION(3, 0, 0))
2574 set_current_tcp(maybe_switch_tcbs(current_tcp,
2577 if (detach_on_execve) {
2578 if (current_tcp->flags & TCB_SKIP_DETACH_ON_FIRST_EXEC) {
2579 current_tcp->flags &= ~TCB_SKIP_DETACH_ON_FIRST_EXEC;
2581 detach(current_tcp); /* do "-b execve" thingy */
2587 case TE_STOP_BEFORE_EXIT:
2588 print_event_exit(current_tcp);
2592 /* We handled quick cases, we are permitted to interrupt now. */
2596 /* If the process is being delayed, do not ptrace_restart just yet */
2597 if (syscall_delayed(current_tcp))
2600 if (ptrace_restart(restart_op, current_tcp, restart_sig) < 0) {
2601 /* Note: ptrace_restart emitted error message */
2609 restart_delayed_tcb(struct tcb *const tcp)
2611 const struct tcb_wait_data wd = { .te = TE_RESTART };
2613 debug_func_msg("pid %d", tcp->pid);
2615 tcp->flags &= ~TCB_DELAYED;
2617 struct tcb *const prev_tcp = current_tcp;
2619 bool ret = dispatch_event(&wd);
2620 current_tcp = prev_tcp;
2626 restart_delayed_tcbs(void)
2628 struct tcb *tcp_next = NULL;
2629 struct timespec ts_now;
2631 clock_gettime(CLOCK_MONOTONIC, &ts_now);
2633 for (size_t i = 0; i < tcbtabsize; i++) {
2634 struct tcb *tcp = tcbtab[i];
2636 if (tcp->pid && syscall_delayed(tcp)) {
2637 if (ts_cmp(&ts_now, &tcp->delay_expiration_time) > 0) {
2638 if (!restart_delayed_tcb(tcp))
2641 /* Check whether this tcb is the next. */
2643 ts_cmp(&tcp_next->delay_expiration_time,
2644 &tcp->delay_expiration_time) > 0) {
2652 arm_delay_timer(tcp_next);
2658 * As this signal handler does a lot of work that is not suitable
2659 * for signal handlers, extra care must be taken to ensure that
2660 * it is enabled only in those places where it's safe.
2663 timer_sighandler(int sig)
2665 delay_timer_expired();
2670 int saved_errno = errno;
2672 if (!restart_delayed_tcbs())
2675 errno = saved_errno;
2678 #ifdef ENABLE_COVERAGE_GCOV
2679 extern void __gcov_flush(void);
2682 static void ATTRIBUTE_NORETURN
2687 if (shared_log != stderr)
2690 while (waitpid(popen_pid, NULL, 0) < 0 && errno == EINTR)
2693 if (exit_code > 0xff) {
2694 /* Avoid potential core file clobbering. */
2695 struct_rlimit rlim = {0, 0};
2696 set_rlimit(RLIMIT_CORE, &rlim);
2698 /* Child was killed by a signal, mimic that. */
2700 signal(exit_code, SIG_DFL);
2701 #ifdef ENABLE_COVERAGE_GCOV
2706 /* Unblock the signal. */
2709 sigaddset(&mask, exit_code);
2710 #ifdef ENABLE_COVERAGE_GCOV
2713 sigprocmask(SIG_UNBLOCK, &mask, NULL);
2715 /* Paranoia - what if this signal is not fatal?
2716 Exit with 128 + signo then. */
2723 main(int argc, char *argv[])
2725 setlocale(LC_ALL, "");
2728 exit_code = !nprocs;
2730 while (dispatch_event(next_event()))