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-2017 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.
34 #include <sys/param.h>
37 #include <sys/resource.h>
43 #include <sys/utsname.h>
45 # include <sys/prctl.h>
47 #include <asm/unistd.h>
51 #include "printsiginfo.h"
53 /* In some libc, these aren't declared. Do it ourself: */
54 extern char **environ;
59 /* if this is true do the stack trace for every system call */
60 bool stack_trace_enabled;
63 #define my_tkill(tid, sig) syscall(__NR_tkill, (tid), (sig))
65 /* Glue for systems without a MMU that cannot provide fork() */
66 #if !defined(HAVE_FORK)
68 # define NOMMU_SYSTEM 1
71 # define fork() vfork()
74 const unsigned int syscall_trap_sig = SIGTRAP | 0x80;
76 cflag_t cflag = CFLAG_NONE;
77 unsigned int followfork;
78 unsigned int ptrace_setoptions = PTRACE_O_TRACESYSGOOD | PTRACE_O_TRACEEXEC
86 static unsigned int tflag;
88 static bool print_pid_pfx;
93 INTR_ANYWHERE = 1, /* don't block/ignore any signals */
94 INTR_WHILE_WAIT = 2, /* block fatal signals while decoding syscall. default */
95 INTR_NEVER = 3, /* block fatal signals. default if '-o FILE PROG' */
96 INTR_BLOCK_TSTP_TOO = 4, /* block fatal signals and SIGTSTP (^Z) */
100 /* We play with signal mask only if this mode is active: */
101 #define interactive (opt_intr == INTR_WHILE_WAIT)
104 * daemonized_tracer supports -D option.
105 * With this option, strace forks twice.
106 * Unlike normal case, with -D *grandparent* process exec's,
107 * becoming a traced process. Child exits (this prevents traced process
108 * from having children it doesn't expect to have), and grandchild
109 * attaches to grandparent similarly to strace -p PID.
110 * This allows for more transparent interaction in cases
111 * when process and its parent are communicating via signals,
112 * wait() etc. Without -D, strace process gets lodged in between,
113 * disrupting parent<->child link.
115 static bool daemonized_tracer;
118 static int post_attach_sigstop = TCB_IGNORE_ONE_SIGSTOP;
119 # define use_seize (post_attach_sigstop == 0)
121 # define post_attach_sigstop TCB_IGNORE_ONE_SIGSTOP
125 /* Sometimes we want to print only succeeding syscalls. */
126 bool not_failing_only;
128 /* Show path associated with fd arguments */
129 unsigned int show_fd_path;
131 static bool detach_on_execve;
133 static int exit_code;
134 static int strace_child;
135 static int strace_tracer_pid;
137 static const char *username;
138 static uid_t run_uid;
139 static gid_t run_gid;
141 unsigned int max_strlen = DEFAULT_STRLEN;
142 static int acolumn = DEFAULT_ACOLUMN;
143 static char *acolumn_spaces;
145 static const char *outfname;
146 /* If -ff, points to stderr. Else, it's our common output log */
147 static FILE *shared_log;
149 struct tcb *printing_tcp;
150 static struct tcb *current_tcp;
152 static struct tcb **tcbtab;
153 static unsigned int nprocs, tcbtabsize;
155 #ifndef HAVE_PROGRAM_INVOCATION_NAME
156 char *program_invocation_name;
159 unsigned os_release; /* generated from uname()'s u.release */
161 static void detach(struct tcb *tcp);
162 static void cleanup(void);
163 static void interrupt(int sig);
164 static sigset_t start_set, blocked_set;
166 #ifdef HAVE_SIG_ATOMIC_T
167 static volatile sig_atomic_t interrupted;
169 static volatile int interrupted;
172 #ifndef HAVE_STRERROR
174 #if !HAVE_DECL_SYS_ERRLIST
176 extern char *sys_errlist[];
182 static char buf[sizeof("Unknown error %d") + sizeof(int)*3];
184 if (err_no < 1 || err_no >= sys_nerr) {
185 sprintf(buf, "Unknown error %d", err_no);
188 return sys_errlist[err_no];
191 #endif /* HAVE_STERRROR */
196 static const char features[] =
199 #endif /* USE_LIBUNWIND */
202 printf("%s -- version %s\n"
203 "Copyright (c) 1991-%s The strace developers <%s>.\n"
204 "This is free software; see the source for copying conditions. There is NO\n"
205 "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n",
206 PACKAGE_NAME, PACKAGE_VERSION, COPYRIGHT_YEAR, PACKAGE_URL);
207 printf("\nOptional features enabled:%s\n",
208 features[0] ? features : " (none)");
215 usage: strace [-CdffhiqrtttTvVwxxy] [-I n] [-e expr]...\n\
216 [-a column] [-o file] [-s strsize] [-P path]...\n\
217 -p pid... / [-D] [-E var=val]... [-u username] PROG [ARGS]\n\
218 or: strace -c[dfw] [-I n] [-e expr]... [-O overhead] [-S sortby]\n\
219 -p pid... / [-D] [-E var=val]... [-u username] PROG [ARGS]\n\
222 -a column alignment COLUMN for printing syscall results (default %d)\n\
223 -i print instruction pointer at time of syscall\n\
227 -k obtain stack trace between each syscall (experimental)\n\
231 -o file send trace output to FILE instead of stderr\n\
232 -q suppress messages about attaching, detaching, etc.\n\
233 -r print relative timestamp\n\
234 -s strsize limit length of print strings to STRSIZE chars (default %d)\n\
235 -t print absolute timestamp\n\
236 -tt print absolute timestamp with usecs\n\
237 -T print time spent in each syscall\n\
238 -x print non-ascii strings in hex\n\
239 -xx print all strings in hex\n\
240 -y print paths associated with file descriptor arguments\n\
241 -yy print protocol specific information associated with socket file descriptors\n\
244 -c count time, calls, and errors for each syscall and report summary\n\
245 -C like -c but also print regular output\n\
246 -O overhead set overhead for tracing syscalls to OVERHEAD usecs\n\
247 -S sortby sort syscall counts by: time, calls, name, nothing (default %s)\n\
248 -w summarise syscall latency (default is system time)\n\
251 -e expr a qualifying expression: option=[!]all or option=[!]val1[,val2]...\n\
252 options: trace, abbrev, verbose, raw, signal, read, write, fault\n\
253 -P path trace accesses to path\n\
256 -b execve detach on execve syscall\n\
257 -D run tracer process as a detached grandchild, not as parent\n\
259 -ff follow forks with output into separate files\n\
261 1: no signals are blocked\n\
262 2: fatal signals are blocked while decoding syscall (default)\n\
263 3: fatal signals are always blocked (default if '-o FILE PROG')\n\
264 4: fatal signals and SIGTSTP (^Z) are always blocked\n\
265 (useful to make 'strace -o FILE PROG' not stop on ^Z)\n\
268 -E var remove var from the environment for command\n\
269 -E var=val put var=val in the environment for command\n\
270 -p pid trace process with process id PID, may be repeated\n\
271 -u username run command as username handling setuid and/or setgid\n\
274 -d enable debug output to stderr\n\
275 -v verbose mode: print unabbreviated argv, stat, termios, etc. args\n\
276 -h print help message\n\
279 /* ancient, no one should use it
280 -F -- attempt to follow vforks (deprecated, use -f)\n\
282 /* this is broken, so don't document it
283 -z -- print only succeeding syscalls\n\
285 , DEFAULT_ACOLUMN, DEFAULT_STRLEN, DEFAULT_SORTBY);
289 static void ATTRIBUTE_NORETURN
292 if (strace_tracer_pid == getpid()) {
299 static void verror_msg(int err_no, const char *fmt, va_list p)
305 /* We want to print entire message with single fprintf to ensure
306 * message integrity if stderr is shared with other programs.
307 * Thus we use vasprintf + single fprintf.
310 if (vasprintf(&msg, fmt, p) >= 0) {
312 fprintf(stderr, "%s: %s: %s\n",
313 program_invocation_name, msg, strerror(err_no));
315 fprintf(stderr, "%s: %s\n",
316 program_invocation_name, msg);
319 /* malloc in vasprintf failed, try it without malloc */
320 fprintf(stderr, "%s: ", program_invocation_name);
321 vfprintf(stderr, fmt, p);
323 fprintf(stderr, ": %s\n", strerror(err_no));
327 /* We don't switch stderr to buffered, thus fprintf(stderr)
328 * always flushes its output and this is not necessary: */
329 /* fflush(stderr); */
332 void error_msg(const char *fmt, ...)
336 verror_msg(0, fmt, p);
340 void error_msg_and_die(const char *fmt, ...)
344 verror_msg(0, fmt, p);
348 void error_msg_and_help(const char *fmt, ...)
353 verror_msg(0, fmt, p);
355 fprintf(stderr, "Try '%s -h' for more information.\n",
356 program_invocation_name);
360 void perror_msg(const char *fmt, ...)
364 verror_msg(errno, fmt, p);
368 void perror_msg_and_die(const char *fmt, ...)
372 verror_msg(errno, fmt, p);
377 error_opt_arg(int opt, const char *arg)
379 error_msg_and_help("invalid -%c argument: '%s'", opt, arg);
382 static const char *ptrace_attach_cmd;
385 ptrace_attach_or_seize(int pid)
390 return ptrace_attach_cmd = "PTRACE_ATTACH",
391 ptrace(PTRACE_ATTACH, pid, 0L, 0L);
392 r = ptrace(PTRACE_SEIZE, pid, 0L, (unsigned long) ptrace_setoptions);
394 return ptrace_attach_cmd = "PTRACE_SEIZE", r;
395 r = ptrace(PTRACE_INTERRUPT, pid, 0L, 0L);
396 return ptrace_attach_cmd = "PTRACE_INTERRUPT", r;
398 return ptrace_attach_cmd = "PTRACE_ATTACH",
399 ptrace(PTRACE_ATTACH, pid, 0L, 0L);
404 * Used when we want to unblock stopped traced process.
405 * Should be only used with PTRACE_CONT, PTRACE_DETACH and PTRACE_SYSCALL.
406 * Returns 0 on success or if error was ESRCH
407 * (presumably process was killed while we talk to it).
408 * Otherwise prints error message and returns -1.
411 ptrace_restart(const unsigned int op, struct tcb *const tcp, unsigned int sig)
417 ptrace(op, tcp->pid, 0L, (unsigned long) sig);
437 * Why curcol != 0? Otherwise sometimes we get this:
439 * 10252 kill(10253, SIGKILL) = 0
440 * <ptrace(SYSCALL,10252):No such process>10253 ...next decode...
442 * 10252 died after we retrieved syscall exit data,
443 * but before we tried to restart it. Log looks ugly.
445 if (current_tcp && current_tcp->curcol != 0) {
446 tprintf(" <ptrace(%s):%s>\n", msg, strerror(err));
452 perror_msg("ptrace(PTRACE_%s,pid:%d,sig:%u)", msg, tcp->pid, sig);
457 set_cloexec_flag(int fd)
461 flags = fcntl(fd, F_GETFD);
463 /* Can happen only if fd is bad.
464 * Should never happen: if it does, we have a bug
465 * in the caller. Therefore we just abort
466 * instead of propagating the error.
468 perror_msg_and_die("fcntl(%d, F_GETFD)", fd);
471 newflags = flags | FD_CLOEXEC;
472 if (flags == newflags)
475 fcntl(fd, F_SETFD, newflags); /* never fails */
479 kill_save_errno(pid_t pid, int sig)
481 int saved_errno = errno;
483 (void) kill(pid, sig);
488 * When strace is setuid executable, we have to swap uids
489 * before and after filesystem and process management operations.
494 int euid = geteuid(), uid = getuid();
496 if (euid != uid && setreuid(euid, uid) < 0) {
497 perror_msg_and_die("setreuid");
501 #ifdef _LARGEFILE64_SOURCE
503 # define fopen_for_output fopen64
505 # define fopen_for_output fopen
507 # define struct_stat struct stat64
508 # define stat_file stat64
509 # define struct_dirent struct dirent64
510 # define read_dir readdir64
511 # define struct_rlimit struct rlimit64
512 # define set_rlimit setrlimit64
514 # define fopen_for_output fopen
515 # define struct_stat struct stat
516 # define stat_file stat
517 # define struct_dirent struct dirent
518 # define read_dir readdir
519 # define struct_rlimit struct rlimit
520 # define set_rlimit setrlimit
524 strace_fopen(const char *path)
529 fp = fopen_for_output(path, "w");
531 perror_msg_and_die("Can't fopen '%s'", path);
533 set_cloexec_flag(fileno(fp));
537 static int popen_pid;
540 # define _PATH_BSHELL "/bin/sh"
544 * We cannot use standard popen(3) here because we have to distinguish
545 * popen child process from other processes we trace, and standard popen(3)
546 * does not export its child's pid.
549 strace_popen(const char *command)
557 perror_msg_and_die("pipe");
559 set_cloexec_flag(fds[1]); /* never fails */
563 perror_msg_and_die("vfork");
570 perror_msg_and_die("dup2");
573 execl(_PATH_BSHELL, "sh", "-c", command, NULL);
574 perror_msg_and_die("Can't execute '%s'", _PATH_BSHELL);
581 fp = fdopen(fds[1], "w");
583 perror_msg_and_die("fdopen");
587 ATTRIBUTE_FORMAT((printf, 1, 0))
589 tvprintf(const char *const fmt, va_list args)
592 int n = vfprintf(current_tcp->outf, fmt, args);
594 if (current_tcp->outf != stderr)
595 perror_msg("%s", outfname);
597 current_tcp->curcol += n;
602 tprintf(const char *fmt, ...)
610 #ifndef HAVE_FPUTS_UNLOCKED
611 # define fputs_unlocked fputs
615 tprints(const char *str)
618 int n = fputs_unlocked(str, current_tcp->outf);
620 current_tcp->curcol += strlen(str);
623 if (current_tcp->outf != stderr)
624 perror_msg("%s", outfname);
629 tprints_comment(const char *const str)
632 tprintf(" /* %s */", str);
636 tprintf_comment(const char *fmt, ...)
653 current_tcp->curcol = 0;
654 fflush(current_tcp->outf);
657 printing_tcp->curcol = 0;
663 printleader(struct tcb *tcp)
665 /* If -ff, "previous tcb we printed" is always the same as current,
666 * because we have per-tcb output files.
672 current_tcp = printing_tcp;
673 if (printing_tcp->curcol != 0 && (followfork < 2 || printing_tcp == tcp)) {
675 * case 1: we have a shared log (i.e. not -ff), and last line
676 * wasn't finished (same or different tcb, doesn't matter).
677 * case 2: split log, we are the same tcb, but our last line
678 * didn't finish ("SIGKILL nuked us after syscall entry" etc).
680 tprints(" <unfinished ...>\n");
681 printing_tcp->curcol = 0;
687 current_tcp->curcol = 0;
690 tprintf("%-5d ", tcp->pid);
691 else if (nprocs > 1 && !outfname)
692 tprintf("[pid %5u] ", tcp->pid);
695 char str[sizeof("HH:MM:SS")];
696 struct timeval tv, dtv;
697 static struct timeval otv;
699 gettimeofday(&tv, NULL);
703 tv_sub(&dtv, &tv, &otv);
704 tprintf("%6ld.%06ld ",
705 (long) dtv.tv_sec, (long) dtv.tv_usec);
707 } else if (tflag > 2) {
708 tprintf("%ld.%06ld ",
709 (long) tv.tv_sec, (long) tv.tv_usec);
711 time_t local = tv.tv_sec;
712 strftime(str, sizeof(str), "%T", localtime(&local));
714 tprintf("%s.%06ld ", str, (long) tv.tv_usec);
726 if (current_tcp->curcol < acolumn)
727 tprints(acolumn_spaces + current_tcp->curcol);
730 /* Should be only called directly *after successful attach* to a tracee.
731 * Otherwise, "strace -oFILE -ff -p<nonexistant_pid>"
732 * may create bogus empty FILE.<nonexistant_pid>, and then die.
735 newoutf(struct tcb *tcp)
737 tcp->outf = shared_log; /* if not -ff mode, the same file is for all */
738 if (followfork >= 2) {
739 char name[520 + sizeof(int) * 3];
740 sprintf(name, "%.512s.%u", outfname, tcp->pid);
741 tcp->outf = strace_fopen(name);
748 /* Allocate some (more) TCBs (and expand the table).
749 We don't want to relocate the TCBs because our
750 callers have pointers and it would be a pain.
751 So tcbtab is a table of pointers. Since we never
752 free the TCBs, we allocate a single chunk of many. */
753 unsigned int new_tcbtabsize, alloc_tcbtabsize;
757 alloc_tcbtabsize = tcbtabsize;
758 new_tcbtabsize = tcbtabsize * 2;
760 new_tcbtabsize = alloc_tcbtabsize = 1;
763 newtcbs = xcalloc(alloc_tcbtabsize, sizeof(newtcbs[0]));
764 tcbtab = xreallocarray(tcbtab, new_tcbtabsize, sizeof(tcbtab[0]));
765 while (tcbtabsize < new_tcbtabsize)
766 tcbtab[tcbtabsize++] = newtcbs++;
775 if (nprocs == tcbtabsize)
778 for (i = 0; i < tcbtabsize; i++) {
781 memset(tcp, 0, sizeof(*tcp));
783 #if SUPPORTED_PERSONALITIES > 1
784 tcp->currpers = current_personality;
788 if (stack_trace_enabled)
789 unwind_tcb_init(tcp);
794 error_msg("new tcb for pid %d, active tcbs:%d",
799 error_msg_and_die("bug in alloctcb");
803 get_tcb_priv_data(const struct tcb *tcp)
805 return tcp->_priv_data;
809 set_tcb_priv_data(struct tcb *tcp, void *const priv_data,
810 void (*const free_priv_data)(void *))
815 tcp->_free_priv_data = free_priv_data;
816 tcp->_priv_data = priv_data;
822 free_tcb_priv_data(struct tcb *tcp)
824 if (tcp->_priv_data) {
825 if (tcp->_free_priv_data) {
826 tcp->_free_priv_data(tcp->_priv_data);
827 tcp->_free_priv_data = NULL;
829 tcp->_priv_data = NULL;
834 droptcb(struct tcb *tcp)
840 for (p = 0; p < SUPPORTED_PERSONALITIES; ++p)
841 free(tcp->inject_vec[p]);
843 free_tcb_priv_data(tcp);
846 if (stack_trace_enabled) {
853 error_msg("dropped tcb for pid %d, %d remain",
857 if (followfork >= 2) {
858 if (tcp->curcol != 0)
859 fprintf(tcp->outf, " <detached ...>\n");
862 if (printing_tcp == tcp && tcp->curcol != 0)
863 fprintf(tcp->outf, " <detached ...>\n");
868 if (current_tcp == tcp)
870 if (printing_tcp == tcp)
873 memset(tcp, 0, sizeof(*tcp));
876 /* Detach traced process.
877 * Never call DETACH twice on the same process as both unattached and
878 * attached-unstopped processes give the same ESRCH. For unattached process we
879 * would SIGSTOP it and wait for its SIGSTOP notification forever.
882 detach(struct tcb *tcp)
888 * Linux wrongly insists the child be stopped
889 * before detaching. Arghh. We go through hoops
890 * to make a clean break of things.
893 if (!(tcp->flags & TCB_ATTACHED))
896 /* We attached but possibly didn't see the expected SIGSTOP.
897 * We must catch exactly one as otherwise the detached process
898 * would be left stopped (process state T).
900 if (tcp->flags & TCB_IGNORE_ONE_SIGSTOP)
903 error = ptrace(PTRACE_DETACH, tcp->pid, 0, 0);
905 /* On a clear day, you can see forever. */
908 if (errno != ESRCH) {
909 /* Shouldn't happen. */
910 perror_msg("detach: ptrace(PTRACE_DETACH,%u)", tcp->pid);
913 /* ESRCH: process is either not stopped or doesn't exist. */
914 if (my_tkill(tcp->pid, 0) < 0) {
916 /* Shouldn't happen. */
917 perror_msg("detach: tkill(%u,0)", tcp->pid);
918 /* else: process doesn't exist. */
921 /* Process is not stopped, need to stop it. */
924 * With SEIZE, tracee can be in group-stop already.
925 * In this state sending it another SIGSTOP does nothing.
926 * Need to use INTERRUPT.
927 * Testcase: trying to ^C a "strace -p <stopped_process>".
929 error = ptrace(PTRACE_INTERRUPT, tcp->pid, 0, 0);
933 perror_msg("detach: ptrace(PTRACE_INTERRUPT,%u)", tcp->pid);
935 error = my_tkill(tcp->pid, SIGSTOP);
939 perror_msg("detach: tkill(%u,SIGSTOP)", tcp->pid);
941 /* Either process doesn't exist, or some weird error. */
945 /* We end up here in three cases:
946 * 1. We sent PTRACE_INTERRUPT (use_seize case)
947 * 2. We sent SIGSTOP (!use_seize)
948 * 3. Attach SIGSTOP was already pending (TCB_IGNORE_ONE_SIGSTOP set)
952 if (waitpid(tcp->pid, &status, __WALL) < 0) {
956 * if (errno == ECHILD) break;
957 * ^^^ WRONG! We expect this PID to exist,
958 * and want to emit a message otherwise:
960 perror_msg("detach: waitpid(%u)", tcp->pid);
963 if (!WIFSTOPPED(status)) {
965 * Tracee exited or was killed by signal.
966 * We shouldn't normally reach this place:
967 * we don't want to consume exit status.
968 * Consider "strace -p PID" being ^C-ed:
969 * we want merely to detach from PID.
971 * However, we _can_ end up here if tracee
976 sig = WSTOPSIG(status);
978 error_msg("detach wait: event:%d sig:%d",
979 (unsigned)status >> 16, sig);
981 unsigned event = (unsigned)status >> 16;
982 if (event == PTRACE_EVENT_STOP /*&& sig == SIGTRAP*/) {
984 * sig == SIGTRAP: PTRACE_INTERRUPT stop.
985 * sig == other: process was already stopped
986 * with this stopping sig (see tests/detach-stopped).
987 * Looks like re-injecting this sig is not necessary
988 * in DETACH for the tracee to remain stopped.
993 * PTRACE_INTERRUPT is not guaranteed to produce
994 * the above event if other ptrace-stop is pending.
995 * See tests/detach-sleeping testcase:
996 * strace got SIGINT while tracee is sleeping.
997 * We sent PTRACE_INTERRUPT.
998 * We see syscall exit, not PTRACE_INTERRUPT stop.
999 * We won't get PTRACE_INTERRUPT stop
1000 * if we would CONT now. Need to DETACH.
1002 if (sig == syscall_trap_sig)
1004 /* else: not sure in which case we can be here.
1005 * Signal stop? Inject it while detaching.
1007 ptrace_restart(PTRACE_DETACH, tcp, sig);
1010 /* Note: this check has to be after use_seize check */
1011 /* (else, in use_seize case SIGSTOP will be mistreated) */
1012 if (sig == SIGSTOP) {
1013 /* Detach, suppressing SIGSTOP */
1014 ptrace_restart(PTRACE_DETACH, tcp, 0);
1017 if (sig == syscall_trap_sig)
1019 /* Can't detach just yet, may need to wait for SIGSTOP */
1020 error = ptrace_restart(PTRACE_CONT, tcp, sig);
1022 /* Should not happen.
1023 * Note: ptrace_restart returns 0 on ESRCH, so it's not it.
1024 * ptrace_restart already emitted error message.
1031 if (!qflag && (tcp->flags & TCB_ATTACHED))
1032 error_msg("Process %u detached", tcp->pid);
1038 process_opt_p_list(char *opt)
1042 * We accept -p PID,PID; -p "`pidof PROG`"; -p "`pgrep PROG`".
1043 * pidof uses space as delim, pgrep uses newline. :(
1046 char *delim = opt + strcspn(opt, "\n\t ,");
1050 pid = string_to_uint(opt);
1052 error_msg_and_die("Invalid process id: '%s'", opt);
1054 if (pid == strace_tracer_pid) {
1055 error_msg_and_die("I'm sorry, I can't let you do that, Dave.");
1066 attach_tcb(struct tcb *const tcp)
1068 if (ptrace_attach_or_seize(tcp->pid) < 0) {
1069 perror_msg("attach: ptrace(%s, %d)",
1070 ptrace_attach_cmd, tcp->pid);
1075 tcp->flags |= TCB_ATTACHED | TCB_STARTUP | post_attach_sigstop;
1078 error_msg("attach to pid %d (main) succeeded", tcp->pid);
1080 char procdir[sizeof("/proc/%d/task") + sizeof(int) * 3];
1082 unsigned int ntid = 0, nerr = 0;
1084 if (followfork && tcp->pid != strace_child &&
1085 sprintf(procdir, "/proc/%d/task", tcp->pid) > 0 &&
1086 (dir = opendir(procdir)) != NULL) {
1089 while ((de = read_dir(dir)) != NULL) {
1090 if (de->d_fileno == 0)
1093 int tid = string_to_uint(de->d_name);
1094 if (tid <= 0 || tid == tcp->pid)
1098 if (ptrace_attach_or_seize(tid) < 0) {
1101 perror_msg("attach: ptrace(%s, %d)",
1102 ptrace_attach_cmd, tid);
1106 error_msg("attach to pid %d succeeded", tid);
1108 struct tcb *tid_tcp = alloctcb(tid);
1109 tid_tcp->flags |= TCB_ATTACHED | TCB_STARTUP |
1110 post_attach_sigstop;
1119 error_msg("Process %u attached"
1121 tcp->pid, ntid - nerr + 1);
1123 error_msg("Process %u attached",
1129 startup_attach(void)
1131 pid_t parent_pid = strace_tracer_pid;
1136 * Block user interruptions as we would leave the traced
1137 * process stopped (process state T) if we would terminate in
1138 * between PTRACE_ATTACH and wait4() on SIGSTOP.
1139 * We rely on cleanup() from this point on.
1142 sigprocmask(SIG_SETMASK, &blocked_set, NULL);
1144 if (daemonized_tracer) {
1147 perror_msg_and_die("fork");
1149 if (pid) { /* parent */
1151 * Wait for grandchild to attach to straced process
1152 * (grandparent). Grandchild SIGKILLs us after it attached.
1153 * Grandparent's wait() is unblocked by our death,
1154 * it proceeds to exec the straced program.
1157 _exit(0); /* paranoia */
1160 /* We will be the tracer process. Remember our new pid: */
1161 strace_tracer_pid = getpid();
1164 for (tcbi = 0; tcbi < tcbtabsize; tcbi++) {
1170 /* Is this a process we should attach to, but not yet attached? */
1171 if (tcp->flags & TCB_ATTACHED)
1172 continue; /* no, we already attached it */
1174 if (tcp->pid == parent_pid || tcp->pid == strace_tracer_pid) {
1176 perror_msg("attach: pid %d", tcp->pid);
1184 sigprocmask(SIG_SETMASK, &start_set, NULL);
1187 sigprocmask(SIG_SETMASK, &blocked_set, NULL);
1189 } /* for each tcbtab[] */
1191 if (daemonized_tracer) {
1193 * Make parent go away.
1194 * Also makes grandparent's wait() unblock.
1196 kill(parent_pid, SIGKILL);
1202 sigprocmask(SIG_SETMASK, &start_set, NULL);
1205 /* Stack-o-phobic exec helper, in the hope to work around
1206 * NOMMU + "daemonized tracer" difficulty.
1208 struct exec_params {
1214 struct sigaction child_sa;
1216 static struct exec_params params_for_tracee;
1218 static void ATTRIBUTE_NOINLINE ATTRIBUTE_NORETURN
1221 struct exec_params *params = ¶ms_for_tracee;
1223 if (params->fd_to_close >= 0)
1224 close(params->fd_to_close);
1225 if (!daemonized_tracer && !use_seize) {
1226 if (ptrace(PTRACE_TRACEME, 0L, 0L, 0L) < 0) {
1227 perror_msg_and_die("ptrace(PTRACE_TRACEME, ...)");
1231 if (username != NULL) {
1233 * It is important to set groups before we
1234 * lose privileges on setuid.
1236 if (initgroups(username, run_gid) < 0) {
1237 perror_msg_and_die("initgroups");
1239 if (setregid(run_gid, params->run_egid) < 0) {
1240 perror_msg_and_die("setregid");
1242 if (setreuid(run_uid, params->run_euid) < 0) {
1243 perror_msg_and_die("setreuid");
1245 } else if (geteuid() != 0)
1246 if (setreuid(run_uid, run_uid) < 0) {
1247 perror_msg_and_die("setreuid");
1250 if (!daemonized_tracer) {
1252 * Induce a ptrace stop. Tracer (our parent)
1253 * will resume us with PTRACE_SYSCALL and display
1254 * the immediately following execve syscall.
1255 * Can't do this on NOMMU systems, we are after
1256 * vfork: parent is blocked, stopping would deadlock.
1259 kill(getpid(), SIGSTOP);
1262 /* we depend on SIGCHLD set to SIG_DFL by init code */
1263 /* if it happens to be SIG_IGN'ed, wait won't block */
1268 if (params_for_tracee.child_sa.sa_handler != SIG_DFL)
1269 sigaction(SIGCHLD, ¶ms_for_tracee.child_sa, NULL);
1271 execv(params->pathname, params->argv);
1272 perror_msg_and_die("exec");
1276 * Open a dummy descriptor for use as a placeholder.
1277 * The descriptor is O_RDONLY with FD_CLOEXEC flag set.
1278 * A read attempt from such descriptor ends with EOF,
1279 * a write attempt is rejected with EBADF.
1282 open_dummy_desc(void)
1287 perror_msg_and_die("pipe");
1289 set_cloexec_flag(fds[0]);
1293 /* placeholder fds status for stdin and stdout */
1294 static bool fd_is_placeholder[2];
1297 * Ensure that all standard file descriptors are open by opening placeholder
1298 * file descriptors for those standard file descriptors that are not open.
1300 * The information which descriptors have been made open is saved
1301 * in fd_is_placeholder for later use.
1304 ensure_standard_fds_opened(void)
1308 while ((fd = open_dummy_desc()) <= 2) {
1311 fd_is_placeholder[fd] = true;
1319 * Redirect stdin and stdout unless they have been opened earlier
1320 * by ensure_standard_fds_opened as placeholders.
1323 redirect_standard_fds(void)
1328 * It might be a good idea to redirect stderr as well,
1329 * but we sometimes need to print error messages.
1331 for (i = 0; i <= 1; ++i) {
1332 if (!fd_is_placeholder[i]) {
1340 startup_child(char **argv)
1342 struct_stat statbuf;
1343 const char *filename;
1344 size_t filename_len;
1345 char pathname[PATH_MAX];
1350 filename_len = strlen(filename);
1352 if (filename_len > sizeof(pathname) - 1) {
1353 errno = ENAMETOOLONG;
1354 perror_msg_and_die("exec");
1356 if (strchr(filename, '/')) {
1357 strcpy(pathname, filename);
1359 #ifdef USE_DEBUGGING_EXEC
1361 * Debuggers customarily check the current directory
1362 * first regardless of the path but doing that gives
1363 * security geeks a panic attack.
1365 else if (stat_file(filename, &statbuf) == 0)
1366 strcpy(pathname, filename);
1367 #endif /* USE_DEBUGGING_EXEC */
1372 for (path = getenv("PATH"); path && *path; path += m) {
1373 const char *colon = strchr(path, ':');
1378 m = n = strlen(path);
1380 if (!getcwd(pathname, PATH_MAX))
1382 len = strlen(pathname);
1383 } else if (n > sizeof(pathname) - 1)
1386 strncpy(pathname, path, n);
1389 if (len && pathname[len - 1] != '/')
1390 pathname[len++] = '/';
1391 if (filename_len + len > sizeof(pathname) - 1)
1393 strcpy(pathname + len, filename);
1394 if (stat_file(pathname, &statbuf) == 0 &&
1395 /* Accept only regular files
1396 with some execute bits set.
1397 XXX not perfect, might still fail */
1398 S_ISREG(statbuf.st_mode) &&
1399 (statbuf.st_mode & 0111))
1402 if (!path || !*path)
1405 if (stat_file(pathname, &statbuf) < 0) {
1406 perror_msg_and_die("Can't stat '%s'", filename);
1409 params_for_tracee.fd_to_close = (shared_log != stderr) ? fileno(shared_log) : -1;
1410 params_for_tracee.run_euid = (statbuf.st_mode & S_ISUID) ? statbuf.st_uid : run_uid;
1411 params_for_tracee.run_egid = (statbuf.st_mode & S_ISGID) ? statbuf.st_gid : run_gid;
1412 params_for_tracee.argv = argv;
1414 * On NOMMU, can be safely freed only after execve in tracee.
1415 * It's hard to know when that happens, so we just leak it.
1417 params_for_tracee.pathname = NOMMU_SYSTEM ? xstrdup(pathname) : pathname;
1419 #if defined HAVE_PRCTL && defined PR_SET_PTRACER && defined PR_SET_PTRACER_ANY
1420 if (daemonized_tracer)
1421 prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY);
1426 perror_msg_and_die("fork");
1428 if ((pid != 0 && daemonized_tracer)
1429 || (pid == 0 && !daemonized_tracer)
1431 /* We are to become the tracee. Two cases:
1433 * not -D: we are child
1438 /* We are the tracer */
1440 if (!daemonized_tracer) {
1443 /* child did PTRACE_TRACEME, nothing to do in parent */
1445 if (!NOMMU_SYSTEM) {
1446 /* Wait until child stopped itself */
1448 while (waitpid(pid, &status, WSTOPPED) < 0) {
1451 perror_msg_and_die("waitpid");
1453 if (!WIFSTOPPED(status) || WSTOPSIG(status) != SIGSTOP) {
1454 kill_save_errno(pid, SIGKILL);
1455 perror_msg_and_die("Unexpected wait status %#x",
1459 /* Else: NOMMU case, we have no way to sync.
1460 * Just attach to it as soon as possible.
1461 * This means that we may miss a few first syscalls...
1464 if (ptrace_attach_or_seize(pid)) {
1465 kill_save_errno(pid, SIGKILL);
1466 perror_msg_and_die("attach: ptrace(%s, %d)",
1467 ptrace_attach_cmd, pid);
1472 tcp = alloctcb(pid);
1473 tcp->flags |= TCB_ATTACHED | TCB_STARTUP
1474 | TCB_SKIP_DETACH_ON_FIRST_EXEC
1475 | (NOMMU_SYSTEM ? 0 : (TCB_HIDE_LOG | post_attach_sigstop));
1478 /* With -D, we are *child* here, the tracee is our parent. */
1479 strace_child = strace_tracer_pid;
1480 strace_tracer_pid = getpid();
1481 tcp = alloctcb(strace_child);
1482 tcp->flags |= TCB_SKIP_DETACH_ON_FIRST_EXEC | TCB_HIDE_LOG;
1483 /* attaching will be done later, by startup_attach */
1484 /* note: we don't do newoutf(tcp) here either! */
1486 /* NOMMU BUG! -D mode is active, we (child) return,
1487 * and we will scribble over parent's stack!
1488 * When parent later unpauses, it segfaults.
1491 * (1) by declaring exec_or_die() NORETURN,
1492 * hopefully compiler will just jump to it
1493 * instead of call (won't push anything to stack),
1494 * (2) by trying very hard in exec_or_die()
1495 * to not use any stack,
1496 * (3) having a really big (PATH_MAX) stack object
1497 * in this function, which creates a "buffer" between
1498 * child's and parent's stack pointers.
1499 * This may save us if (1) and (2) failed
1500 * and compiler decided to use stack in exec_or_die() anyway
1501 * (happens on i386 because of stack parameter passing).
1503 * A cleaner solution is to use makecontext + setcontext
1504 * to create a genuine separate stack and execute on it.
1508 * A case where straced process is part of a pipe:
1509 * { sleep 1; yes | head -n99999; } | strace -o/dev/null sh -c 'exec <&-; sleep 9'
1510 * If strace won't close its fd#0, closing it in tracee is not enough:
1511 * the pipe is still open, it has a reader. Thus, "head" will not get its
1512 * SIGPIPE at once, on the first write.
1514 * Preventing it by redirecting strace's stdin/out.
1515 * (Don't leave fds 0 and 1 closed, this is bad practice: future opens
1516 * will reuse them, unexpectedly making a newly opened object "stdin").
1518 redirect_standard_fds();
1523 test_ptrace_seize(void)
1527 /* Need fork for test. NOMMU has no forks */
1529 post_attach_sigstop = 0; /* this sets use_seize to 1 */
1535 perror_msg_and_die("fork");
1542 /* PTRACE_SEIZE, unlike ATTACH, doesn't force tracee to trap. After
1543 * attaching tracee continues to run unless a trap condition occurs.
1544 * PTRACE_SEIZE doesn't affect signal or group stop state.
1546 if (ptrace(PTRACE_SEIZE, pid, 0, 0) == 0) {
1547 post_attach_sigstop = 0; /* this sets use_seize to 1 */
1548 } else if (debug_flag) {
1549 error_msg("PTRACE_SEIZE doesn't work");
1555 int status, tracee_pid;
1558 tracee_pid = waitpid(pid, &status, 0);
1559 if (tracee_pid <= 0) {
1562 perror_msg_and_die("%s: unexpected wait result %d",
1563 __func__, tracee_pid);
1565 if (WIFSIGNALED(status)) {
1568 error_msg_and_die("%s: unexpected wait status %#x",
1572 #else /* !USE_SEIZE */
1573 # define test_ptrace_seize() ((void)0)
1577 get_os_release(void)
1583 perror_msg_and_die("uname");
1584 /* u.release has this form: "3.2.9[-some-garbage]" */
1588 if (!(*p >= '0' && *p <= '9'))
1589 error_msg_and_die("Bad OS release string: '%s'", u.release);
1590 /* Note: this open-codes KERNEL_VERSION(): */
1591 rel = (rel << 8) | atoi(p);
1592 if (rel >= KERNEL_VERSION(1, 0, 0))
1594 while (*p >= '0' && *p <= '9')
1597 if (rel >= KERNEL_VERSION(0, 1, 0)) {
1598 /* "X.Y-something" means "X.Y.0" */
1602 error_msg_and_die("Bad OS release string: '%s'", u.release);
1610 set_sigaction(int signo, void (*sighandler)(int), struct sigaction *oldact)
1612 /* if signal handler is a function, add the signal to blocked_set */
1613 if (sighandler != SIG_IGN && sighandler != SIG_DFL)
1614 sigaddset(&blocked_set, signo);
1616 const struct sigaction sa = { .sa_handler = sighandler };
1617 sigaction(signo, &sa, oldact);
1621 * Initialization part of main() was eating much stack (~0.5k),
1622 * which was unused after init.
1623 * We can reuse it if we move init code into a separate function.
1625 * Don't want main() to inline us and defeat the reason
1626 * we have a separate function.
1628 static void ATTRIBUTE_NOINLINE
1629 init(int argc, char *argv[])
1634 if (!program_invocation_name || !*program_invocation_name) {
1635 static char name[] = "strace";
1636 program_invocation_name =
1637 (argv[0] && *argv[0]) ? argv[0] : name;
1640 strace_tracer_pid = getpid();
1642 os_release = get_os_release();
1644 shared_log = stderr;
1645 set_sortby(DEFAULT_SORTBY);
1646 set_personality(DEFAULT_PERSONALITY);
1647 qualify("trace=all");
1648 qualify("abbrev=all");
1649 qualify("verbose=all");
1650 #if DEFAULT_QUAL_FLAGS != (QUAL_TRACE | QUAL_ABBREV | QUAL_VERBOSE)
1651 # error Bug in DEFAULT_QUAL_FLAGS
1653 qualify("signal=all");
1654 while ((c = getopt(argc, argv,
1655 "+b:cCdfFhiqrtTvVwxyz"
1656 #ifdef USE_LIBUNWIND
1660 "a:e:o:O:p:s:S:u:E:P:I:")) != EOF) {
1663 if (strcmp(optarg, "execve") != 0)
1664 error_msg_and_die("Syscall '%s' for -b isn't supported",
1666 detach_on_execve = 1;
1669 if (cflag == CFLAG_BOTH) {
1670 error_msg_and_help("-c and -C are mutually exclusive");
1672 cflag = CFLAG_ONLY_STATS;
1675 if (cflag == CFLAG_ONLY_STATS) {
1676 error_msg_and_help("-c and -C are mutually exclusive");
1684 daemonized_tracer = 1;
1711 count_wallclock = 1;
1720 qualify("abbrev=none");
1727 not_failing_only = 1;
1730 acolumn = string_to_uint(optarg);
1732 error_opt_arg(c, optarg);
1741 i = string_to_uint(optarg);
1743 error_opt_arg(c, optarg);
1747 process_opt_p_list(optarg);
1750 pathtrace_select(optarg);
1753 i = string_to_uint(optarg);
1754 if (i < 0 || (unsigned int) i > -1U / 4)
1755 error_opt_arg(c, optarg);
1764 #ifdef USE_LIBUNWIND
1766 stack_trace_enabled = true;
1770 if (putenv(optarg) < 0)
1771 perror_msg_and_die("putenv");
1774 opt_intr = string_to_uint_upto(optarg, NUM_INTR_OPTS - 1);
1776 error_opt_arg(c, optarg);
1779 error_msg_and_help(NULL);
1787 if (argc < 0 || (!argv[0] && !nprocs)) {
1788 error_msg_and_help("must have PROG [ARGS] or -p PID");
1791 if (!argv[0] && daemonized_tracer) {
1792 error_msg_and_help("PROG [ARGS] must be specified with -D");
1798 if (followfork >= 2 && cflag) {
1799 error_msg_and_help("(-c or -C) and -ff are mutually exclusive");
1802 if (count_wallclock && !cflag) {
1803 error_msg_and_help("-w must be given with (-c or -C)");
1806 if (cflag == CFLAG_ONLY_STATS) {
1808 error_msg("-%c has no effect with -c", 'i');
1809 #ifdef USE_LIBUNWIND
1810 if (stack_trace_enabled)
1811 error_msg("-%c has no effect with -c", 'k');
1814 error_msg("-%c has no effect with -c", 'r');
1816 error_msg("-%c has no effect with -c", 't');
1818 error_msg("-%c has no effect with -c", 'T');
1820 error_msg("-%c has no effect with -c", 'y');
1825 error_msg("-tt has no effect with -r");
1829 acolumn_spaces = xmalloc(acolumn + 1);
1830 memset(acolumn_spaces, ' ', acolumn);
1831 acolumn_spaces[acolumn] = '\0';
1833 sigprocmask(SIG_SETMASK, NULL, &start_set);
1834 memcpy(&blocked_set, &start_set, sizeof(blocked_set));
1836 set_sigaction(SIGCHLD, SIG_DFL, ¶ms_for_tracee.child_sa);
1838 #ifdef USE_LIBUNWIND
1839 if (stack_trace_enabled) {
1843 for (tcbi = 0; tcbi < tcbtabsize; ++tcbi) {
1844 unwind_tcb_init(tcbtab[tcbi]);
1849 /* See if they want to run as another user. */
1850 if (username != NULL) {
1851 struct passwd *pent;
1853 if (getuid() != 0 || geteuid() != 0) {
1854 error_msg_and_die("You must be root to use the -u option");
1856 pent = getpwnam(username);
1858 error_msg_and_die("Cannot find user '%s'", username);
1860 run_uid = pent->pw_uid;
1861 run_gid = pent->pw_gid;
1868 ptrace_setoptions |= PTRACE_O_TRACECLONE |
1869 PTRACE_O_TRACEFORK |
1870 PTRACE_O_TRACEVFORK;
1872 error_msg("ptrace_setoptions = %#x", ptrace_setoptions);
1873 test_ptrace_seize();
1876 * Is something weird with our stdin and/or stdout -
1877 * for example, may they be not open? In this case,
1878 * ensure that none of the future opens uses them.
1880 * This was seen in the wild when /proc/sys/kernel/core_pattern
1881 * was set to "|/bin/strace -o/tmp/LOG PROG":
1882 * kernel runs coredump helper with fd#0 open but fd#1 closed (!),
1883 * therefore LOG gets opened to fd#1, and fd#1 is closed by
1884 * "don't hold up stdin/out open" code soon after.
1886 ensure_standard_fds_opened();
1888 /* Check if they want to redirect the output. */
1890 /* See if they want to pipe the output. */
1891 if (outfname[0] == '|' || outfname[0] == '!') {
1893 * We can't do the <outfname>.PID funny business
1894 * when using popen, so prohibit it.
1896 if (followfork >= 2)
1897 error_msg_and_help("piping the output and -ff are mutually exclusive");
1898 shared_log = strace_popen(outfname + 1);
1899 } else if (followfork < 2)
1900 shared_log = strace_fopen(outfname);
1902 /* -ff without -o FILE is the same as single -f */
1903 if (followfork >= 2)
1907 if (!outfname || outfname[0] == '|' || outfname[0] == '!') {
1908 setvbuf(shared_log, NULL, _IOLBF, 0);
1912 * argv[0] -pPID -oFILE Default interactive setting
1913 * yes * 0 INTR_WHILE_WAIT
1914 * no 1 0 INTR_WHILE_WAIT
1915 * yes * 1 INTR_NEVER
1916 * no 1 1 INTR_WHILE_WAIT
1919 if (outfname && argv[0]) {
1921 opt_intr = INTR_NEVER;
1926 opt_intr = INTR_WHILE_WAIT;
1929 * startup_child() must be called before the signal handlers get
1930 * installed below as they are inherited into the spawned process.
1931 * Also we do not need to be protected by them as during interruption
1932 * in the startup_child() mode we kill the spawned process anyway.
1935 startup_child(argv);
1938 set_sigaction(SIGTTOU, SIG_IGN, NULL);
1939 set_sigaction(SIGTTIN, SIG_IGN, NULL);
1940 if (opt_intr != INTR_ANYWHERE) {
1941 if (opt_intr == INTR_BLOCK_TSTP_TOO)
1942 set_sigaction(SIGTSTP, SIG_IGN, NULL);
1944 * In interactive mode (if no -o OUTFILE, or -p PID is used),
1945 * fatal signals are blocked while syscall stop is processed,
1946 * and acted on in between, when waiting for new syscall stops.
1947 * In non-interactive mode, signals are ignored.
1949 set_sigaction(SIGHUP, interactive ? interrupt : SIG_IGN, NULL);
1950 set_sigaction(SIGINT, interactive ? interrupt : SIG_IGN, NULL);
1951 set_sigaction(SIGQUIT, interactive ? interrupt : SIG_IGN, NULL);
1952 set_sigaction(SIGPIPE, interactive ? interrupt : SIG_IGN, NULL);
1953 set_sigaction(SIGTERM, interactive ? interrupt : SIG_IGN, NULL);
1956 if (nprocs != 0 || daemonized_tracer)
1959 /* Do we want pids printed in our -o OUTFILE?
1960 * -ff: no (every pid has its own file); or
1961 * -f: yes (there can be more pids in the future); or
1962 * -p PID1,PID2: yes (there are already more than one pid)
1964 print_pid_pfx = (outfname && followfork < 2 && (followfork == 1 || nprocs > 1));
1975 for (i = 0; i < tcbtabsize; i++) {
1976 struct tcb *tcp = tcbtab[i];
1977 if (tcp->pid == pid)
1991 /* 'interrupted' is a volatile object, fetch it only once */
1992 fatal_sig = interrupted;
1994 fatal_sig = SIGTERM;
1996 for (i = 0; i < tcbtabsize; i++) {
2001 error_msg("cleanup: looking at pid %u", tcp->pid);
2002 if (tcp->pid == strace_child) {
2003 kill(tcp->pid, SIGCONT);
2004 kill(tcp->pid, fatal_sig);
2009 call_summary(shared_log);
2019 print_debug_info(const int pid, int status)
2021 const unsigned int event = (unsigned int) status >> 16;
2022 char buf[sizeof("WIFEXITED,exitcode=%u") + sizeof(int)*3 /*paranoia:*/ + 16];
2023 char evbuf[sizeof(",EVENT_VFORK_DONE (%u)") + sizeof(int)*3 /*paranoia:*/ + 16];
2026 if (WIFSIGNALED(status))
2028 sprintf(buf, "WIFSIGNALED,%ssig=%s",
2029 WCOREDUMP(status) ? "core," : "",
2030 signame(WTERMSIG(status)));
2032 sprintf(buf, "WIFSIGNALED,sig=%s",
2033 signame(WTERMSIG(status)));
2035 if (WIFEXITED(status))
2036 sprintf(buf, "WIFEXITED,exitcode=%u", WEXITSTATUS(status));
2037 if (WIFSTOPPED(status))
2038 sprintf(buf, "WIFSTOPPED,sig=%s", signame(WSTOPSIG(status)));
2041 static const char *const event_names[] = {
2042 [PTRACE_EVENT_CLONE] = "CLONE",
2043 [PTRACE_EVENT_FORK] = "FORK",
2044 [PTRACE_EVENT_VFORK] = "VFORK",
2045 [PTRACE_EVENT_VFORK_DONE] = "VFORK_DONE",
2046 [PTRACE_EVENT_EXEC] = "EXEC",
2047 [PTRACE_EVENT_EXIT] = "EXIT",
2048 /* [PTRACE_EVENT_STOP (=128)] would make biggish array */
2050 const char *e = "??";
2051 if (event < ARRAY_SIZE(event_names))
2052 e = event_names[event];
2053 else if (event == PTRACE_EVENT_STOP)
2055 sprintf(evbuf, ",EVENT_%s (%u)", e, event);
2057 error_msg("[wait(0x%06x) = %u] %s%s", status, pid, buf, evbuf);
2061 maybe_allocate_tcb(const int pid, int status)
2063 if (!WIFSTOPPED(status)) {
2064 if (detach_on_execve && pid == strace_child) {
2065 /* example: strace -bexecve sh -c 'exec true' */
2070 * This can happen if we inherited an unknown child.
2071 * Example: (sleep 1 & exec strace true)
2073 error_msg("Exit of unknown pid %u ignored", pid);
2077 /* We assume it's a fork/vfork/clone child */
2078 struct tcb *tcp = alloctcb(pid);
2079 tcp->flags |= TCB_ATTACHED | TCB_STARTUP | post_attach_sigstop;
2082 error_msg("Process %d attached", pid);
2086 * This can happen if a clone call misused CLONE_PTRACE itself.
2088 unsigned int sig = WSTOPSIG(status);
2089 unsigned int event = (unsigned int) status >> 16;
2091 if (event == PTRACE_EVENT_STOP || sig == syscall_trap_sig)
2094 ptrace(PTRACE_DETACH, pid, NULL, (unsigned long) sig);
2095 error_msg("Detached unknown pid %d%s%s", pid,
2096 sig ? " with signal " : "",
2097 sig ? signame(sig) : "");
2103 maybe_switch_tcbs(struct tcb *tcp, const int pid)
2106 struct tcb *execve_thread;
2109 if (ptrace(PTRACE_GETEVENTMSG, pid, NULL, &old_pid) < 0)
2111 /* Avoid truncation in pid2tcb() param passing */
2112 if (old_pid <= 0 || old_pid == pid)
2114 if ((unsigned long) old_pid > UINT_MAX)
2116 execve_thread = pid2tcb(old_pid);
2117 /* It should be !NULL, but I feel paranoid */
2121 if (execve_thread->curcol != 0) {
2123 * One case we are here is -ff:
2124 * try "strace -oLOG -ff test/threaded_execve"
2126 fprintf(execve_thread->outf, " <pid changed to %d ...>\n", pid);
2127 /*execve_thread->curcol = 0; - no need, see code below */
2129 /* Swap output FILEs (needed for -ff) */
2130 fp = execve_thread->outf;
2131 execve_thread->outf = tcp->outf;
2133 /* And their column positions */
2134 execve_thread->curcol = tcp->curcol;
2136 /* Drop leader, but close execve'd thread outfile (if -ff) */
2138 /* Switch to the thread, reusing leader's outfile and pid */
2139 tcp = execve_thread;
2141 if (cflag != CFLAG_ONLY_STATS) {
2143 tprintf("+++ superseded by execve in pid %lu +++\n", old_pid);
2145 tcp->flags |= TCB_REPRINT;
2152 print_signalled(struct tcb *tcp, const int pid, int status)
2154 if (pid == strace_child) {
2155 exit_code = 0x100 | WTERMSIG(status);
2159 if (cflag != CFLAG_ONLY_STATS
2160 && is_number_in_set(WTERMSIG(status), &signal_set)) {
2163 tprintf("+++ killed by %s %s+++\n",
2164 signame(WTERMSIG(status)),
2165 WCOREDUMP(status) ? "(core dumped) " : "");
2167 tprintf("+++ killed by %s +++\n",
2168 signame(WTERMSIG(status)));
2175 print_exited(struct tcb *tcp, const int pid, int status)
2177 if (pid == strace_child) {
2178 exit_code = WEXITSTATUS(status);
2182 if (cflag != CFLAG_ONLY_STATS &&
2185 tprintf("+++ exited with %d +++\n", WEXITSTATUS(status));
2191 print_stopped(struct tcb *tcp, const siginfo_t *si, const unsigned int sig)
2193 if (cflag != CFLAG_ONLY_STATS
2195 && is_number_in_set(sig, &signal_set)) {
2198 tprintf("--- %s ", signame(sig));
2202 tprintf("--- stopped by %s ---\n", signame(sig));
2208 startup_tcb(struct tcb *tcp)
2211 error_msg("pid %d has TCB_STARTUP, initializing it", tcp->pid);
2213 tcp->flags &= ~TCB_STARTUP;
2217 error_msg("setting opts 0x%x on pid %d",
2218 ptrace_setoptions, tcp->pid);
2219 if (ptrace(PTRACE_SETOPTIONS, tcp->pid, NULL, ptrace_setoptions) < 0) {
2220 if (errno != ESRCH) {
2221 /* Should never happen, really */
2222 perror_msg_and_die("PTRACE_SETOPTIONS");
2227 if (get_scno(tcp) == 1)
2228 tcp->s_prev_ent = tcp->s_ent;
2232 print_event_exit(struct tcb *tcp)
2234 if (entering(tcp) || filtered(tcp) || hide_log(tcp)
2235 || cflag == CFLAG_ONLY_STATS) {
2239 if (followfork < 2 && printing_tcp && printing_tcp != tcp
2240 && printing_tcp->curcol != 0) {
2241 current_tcp = printing_tcp;
2242 tprints(" <unfinished ...>\n");
2243 fflush(printing_tcp->outf);
2244 printing_tcp->curcol = 0;
2248 if ((followfork < 2 && printing_tcp != tcp)
2249 || (tcp->flags & TCB_REPRINT)) {
2250 tcp->flags &= ~TCB_REPRINT;
2252 tprintf("<... %s resumed>", tcp->s_ent->sys_name);
2255 if (!(tcp->sys_func_rval & RVAL_DECODED)) {
2257 * The decoder has probably decided to print something
2258 * on exiting syscall which is not going to happen.
2260 tprints(" <unfinished ...>");
2269 /* Break the main loop. */
2272 /* Call next_event() again. */
2275 /* Restart the tracee with signal 0 and call next_event() again. */
2279 * For all the events below, current_tcp is set to current tracee's
2280 * tcb. All the suggested actions imply that you want to continue
2281 * tracing of the current tracee; alternatively, you can detach it.
2285 * Syscall entry or exit.
2286 * Restart the tracee with signal 0, or with an injected signal number.
2291 * Tracee received signal with number WSTOPSIG(*pstatus); signal info
2292 * is written to *si. Restart the tracee (with that signal number
2293 * if you want to deliver it).
2295 TE_SIGNAL_DELIVERY_STOP,
2298 * Tracee was killed by a signal with number WTERMSIG(*pstatus).
2303 * Tracee was stopped by a signal with number WSTOPSIG(*pstatus).
2304 * Restart the tracee with that signal number.
2309 * Tracee exited with status WEXITSTATUS(*pstatus).
2314 * Tracee is going to perform execve().
2315 * Restart the tracee with signal 0.
2317 TE_STOP_BEFORE_EXECVE,
2320 * Tracee is going to terminate.
2321 * Restart the tracee with signal 0.
2323 TE_STOP_BEFORE_EXIT,
2326 static enum trace_event
2327 next_event(int *pstatus, siginfo_t *si)
2339 * Used to exit simply when nprocs hits zero, but in this testcase:
2340 * int main(void) { _exit(!!fork()); }
2341 * under strace -f, parent sometimes (rarely) manages
2342 * to exit before we see the first stop of the child,
2343 * and we are losing track of it:
2344 * 19923 clone(...) = 19924
2345 * 19923 exit_group(1) = ?
2346 * 19923 +++ exited with 1 +++
2347 * Exiting only when wait() returns ECHILD works better.
2349 if (popen_pid != 0) {
2350 /* However, if -o|logger is in use, we can't do that.
2351 * Can work around that by double-forking the logger,
2352 * but that loses the ability to wait for its completion
2353 * on exit. Oh well...
2360 sigprocmask(SIG_SETMASK, &start_set, NULL);
2361 pid = wait4(-1, pstatus, __WALL, (cflag ? &ru : NULL));
2364 sigprocmask(SIG_SETMASK, &blocked_set, NULL);
2367 if (wait_errno == EINTR)
2369 if (nprocs == 0 && wait_errno == ECHILD)
2372 * If nprocs > 0, ECHILD is not expected,
2373 * treat it as any other error here:
2376 perror_msg_and_die("wait4(__WALL)");
2381 if (pid == popen_pid) {
2382 if (!WIFSTOPPED(status))
2388 print_debug_info(pid, status);
2390 /* Look up 'pid' in our table. */
2394 tcp = maybe_allocate_tcb(pid, status);
2401 /* Set current output file */
2405 tv_sub(&tcp->dtime, &ru.ru_stime, &tcp->stime);
2406 tcp->stime = ru.ru_stime;
2409 if (WIFSIGNALED(status))
2410 return TE_SIGNALLED;
2412 if (WIFEXITED(status))
2416 * As WCONTINUED flag has not been specified to wait4,
2417 * it cannot be WIFCONTINUED(status), so the only case
2418 * that remains is WIFSTOPPED(status).
2421 /* Is this the very first time we see this tracee stopped? */
2422 if (tcp->flags & TCB_STARTUP)
2425 const unsigned int sig = WSTOPSIG(status);
2426 const unsigned int event = (unsigned int) status >> 16;
2431 * Is this post-attach SIGSTOP?
2432 * Interestingly, the process may stop
2433 * with STOPSIG equal to some other signal
2434 * than SIGSTOP if we happened to attach
2435 * just before the process takes a signal.
2437 if (sig == SIGSTOP && (tcp->flags & TCB_IGNORE_ONE_SIGSTOP)) {
2439 error_msg("ignored SIGSTOP on pid %d", tcp->pid);
2440 tcp->flags &= ~TCB_IGNORE_ONE_SIGSTOP;
2442 } else if (sig == syscall_trap_sig) {
2443 return TE_SYSCALL_STOP;
2445 *si = (siginfo_t) {};
2447 * True if tracee is stopped by signal
2448 * (as opposed to "tracee received signal").
2449 * TODO: shouldn't we check for errno == EINVAL too?
2450 * We can get ESRCH instead, you know...
2452 bool stopped = ptrace(PTRACE_GETSIGINFO, pid, 0, si) < 0;
2453 return stopped ? TE_GROUP_STOP : TE_SIGNAL_DELIVERY_STOP;
2457 case PTRACE_EVENT_STOP:
2459 * PTRACE_INTERRUPT-stop or group-stop.
2460 * PTRACE_INTERRUPT-stop has sig == SIGTRAP here.
2467 return TE_GROUP_STOP;
2471 case PTRACE_EVENT_EXEC:
2472 return TE_STOP_BEFORE_EXECVE;
2473 case PTRACE_EVENT_EXIT:
2474 return TE_STOP_BEFORE_EXIT;
2481 trace_syscall(struct tcb *tcp, unsigned int *sig)
2483 if (entering(tcp)) {
2484 int res = syscall_entering_decode(tcp);
2489 res = syscall_entering_trace(tcp, sig);
2491 syscall_entering_finish(tcp, res);
2494 struct timeval tv = {};
2495 int res = syscall_exiting_decode(tcp, &tv);
2497 res = syscall_exiting_trace(tcp, tv, res);
2499 syscall_exiting_finish(tcp);
2504 /* Returns true iff the main trace loop has to continue. */
2506 dispatch_event(enum trace_event ret, int *pstatus, siginfo_t *si)
2508 unsigned int restart_op = PTRACE_SYSCALL;
2509 unsigned int restart_sig = 0;
2521 case TE_SYSCALL_STOP:
2522 if (trace_syscall(current_tcp, &restart_sig) < 0) {
2524 * ptrace() failed in trace_syscall().
2525 * Likely a result of process disappearing mid-flight.
2526 * Observed case: exit_group() or SIGKILL terminating
2527 * all processes in thread group.
2528 * We assume that ptrace error was caused by process death.
2529 * We used to detach(current_tcp) here, but since we no
2530 * longer implement "detach before death" policy/hack,
2531 * we can let this process to report its death to us
2532 * normally, via WIFEXITED or WIFSIGNALED wait status.
2538 case TE_SIGNAL_DELIVERY_STOP:
2539 restart_sig = WSTOPSIG(*pstatus);
2540 print_stopped(current_tcp, si, restart_sig);
2544 print_signalled(current_tcp, current_tcp->pid, *pstatus);
2545 droptcb(current_tcp);
2549 restart_sig = WSTOPSIG(*pstatus);
2550 print_stopped(current_tcp, NULL, restart_sig);
2553 * This ends ptrace-stop, but does *not* end group-stop.
2554 * This makes stopping signals work properly on straced
2555 * process (that is, process really stops. It used to
2558 restart_op = PTRACE_LISTEN;
2564 print_exited(current_tcp, current_tcp->pid, *pstatus);
2565 droptcb(current_tcp);
2568 case TE_STOP_BEFORE_EXECVE:
2570 * Under Linux, execve changes pid to thread leader's pid,
2571 * and we see this changed pid on EVENT_EXEC and later,
2572 * execve sysexit. Leader "disappears" without exit
2573 * notification. Let user know that, drop leader's tcb,
2574 * and fix up pid in execve thread's tcb.
2575 * Effectively, execve thread's tcb replaces leader's tcb.
2577 * BTW, leader is 'stuck undead' (doesn't report WIFEXITED
2578 * on exit syscall) in multithreaded programs exactly
2579 * in order to handle this case.
2581 * PTRACE_GETEVENTMSG returns old pid starting from Linux 3.0.
2582 * On 2.6 and earlier, it can return garbage.
2584 if (os_release >= KERNEL_VERSION(3, 0, 0))
2585 current_tcp = maybe_switch_tcbs(current_tcp, current_tcp->pid);
2587 if (detach_on_execve) {
2588 if (current_tcp->flags & TCB_SKIP_DETACH_ON_FIRST_EXEC) {
2589 current_tcp->flags &= ~TCB_SKIP_DETACH_ON_FIRST_EXEC;
2591 detach(current_tcp); /* do "-b execve" thingy */
2597 case TE_STOP_BEFORE_EXIT:
2598 print_event_exit(current_tcp);
2602 /* We handled quick cases, we are permitted to interrupt now. */
2606 if (ptrace_restart(restart_op, current_tcp, restart_sig) < 0) {
2607 /* Note: ptrace_restart emitted error message */
2614 #ifdef ENABLE_COVERAGE_GCOV
2615 extern void __gcov_flush(void);
2618 static void ATTRIBUTE_NORETURN
2623 if (shared_log != stderr)
2626 while (waitpid(popen_pid, NULL, 0) < 0 && errno == EINTR)
2629 if (exit_code > 0xff) {
2630 /* Avoid potential core file clobbering. */
2631 struct_rlimit rlim = {0, 0};
2632 set_rlimit(RLIMIT_CORE, &rlim);
2634 /* Child was killed by a signal, mimic that. */
2636 signal(exit_code, SIG_DFL);
2637 #ifdef ENABLE_COVERAGE_GCOV
2642 /* Unblock the signal. */
2645 sigaddset(&mask, exit_code);
2646 #ifdef ENABLE_COVERAGE_GCOV
2649 sigprocmask(SIG_UNBLOCK, &mask, NULL);
2651 /* Paranoia - what if this signal is not fatal?
2652 Exit with 128 + signo then. */
2659 main(int argc, char *argv[])
2663 exit_code = !nprocs;
2667 while (dispatch_event(next_event(&status, &si), &status, &si))