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 /* very unlikely due to vfprintf buffering */
595 if (current_tcp->outf != stderr)
596 perror_msg("%s", outfname);
598 current_tcp->curcol += n;
603 tprintf(const char *fmt, ...)
611 #ifndef HAVE_FPUTS_UNLOCKED
612 # define fputs_unlocked fputs
616 tprints(const char *str)
619 int n = fputs_unlocked(str, current_tcp->outf);
621 current_tcp->curcol += strlen(str);
624 /* very unlikely due to fputs_unlocked buffering */
625 if (current_tcp->outf != stderr)
626 perror_msg("%s", outfname);
631 tprints_comment(const char *const str)
634 tprintf(" /* %s */", str);
638 tprintf_comment(const char *fmt, ...)
652 flush_tcp_output(const struct tcb *const tcp)
654 if (fflush(tcp->outf) && tcp->outf != stderr)
655 perror_msg("%s", outfname);
662 current_tcp->curcol = 0;
663 flush_tcp_output(current_tcp);
666 printing_tcp->curcol = 0;
672 printleader(struct tcb *tcp)
674 /* If -ff, "previous tcb we printed" is always the same as current,
675 * because we have per-tcb output files.
681 current_tcp = printing_tcp;
682 if (printing_tcp->curcol != 0 && (followfork < 2 || printing_tcp == tcp)) {
684 * case 1: we have a shared log (i.e. not -ff), and last line
685 * wasn't finished (same or different tcb, doesn't matter).
686 * case 2: split log, we are the same tcb, but our last line
687 * didn't finish ("SIGKILL nuked us after syscall entry" etc).
689 tprints(" <unfinished ...>\n");
690 printing_tcp->curcol = 0;
696 current_tcp->curcol = 0;
699 tprintf("%-5d ", tcp->pid);
700 else if (nprocs > 1 && !outfname)
701 tprintf("[pid %5u] ", tcp->pid);
704 char str[sizeof("HH:MM:SS")];
705 struct timeval tv, dtv;
706 static struct timeval otv;
708 gettimeofday(&tv, NULL);
712 tv_sub(&dtv, &tv, &otv);
713 tprintf("%6ld.%06ld ",
714 (long) dtv.tv_sec, (long) dtv.tv_usec);
716 } else if (tflag > 2) {
717 tprintf("%ld.%06ld ",
718 (long) tv.tv_sec, (long) tv.tv_usec);
720 time_t local = tv.tv_sec;
721 strftime(str, sizeof(str), "%T", localtime(&local));
723 tprintf("%s.%06ld ", str, (long) tv.tv_usec);
735 if (current_tcp->curcol < acolumn)
736 tprints(acolumn_spaces + current_tcp->curcol);
739 /* Should be only called directly *after successful attach* to a tracee.
740 * Otherwise, "strace -oFILE -ff -p<nonexistant_pid>"
741 * may create bogus empty FILE.<nonexistant_pid>, and then die.
744 newoutf(struct tcb *tcp)
746 tcp->outf = shared_log; /* if not -ff mode, the same file is for all */
747 if (followfork >= 2) {
748 char name[520 + sizeof(int) * 3];
749 sprintf(name, "%.512s.%u", outfname, tcp->pid);
750 tcp->outf = strace_fopen(name);
757 /* Allocate some (more) TCBs (and expand the table).
758 We don't want to relocate the TCBs because our
759 callers have pointers and it would be a pain.
760 So tcbtab is a table of pointers. Since we never
761 free the TCBs, we allocate a single chunk of many. */
762 unsigned int new_tcbtabsize, alloc_tcbtabsize;
766 alloc_tcbtabsize = tcbtabsize;
767 new_tcbtabsize = tcbtabsize * 2;
769 new_tcbtabsize = alloc_tcbtabsize = 1;
772 newtcbs = xcalloc(alloc_tcbtabsize, sizeof(newtcbs[0]));
773 tcbtab = xreallocarray(tcbtab, new_tcbtabsize, sizeof(tcbtab[0]));
774 while (tcbtabsize < new_tcbtabsize)
775 tcbtab[tcbtabsize++] = newtcbs++;
784 if (nprocs == tcbtabsize)
787 for (i = 0; i < tcbtabsize; i++) {
790 memset(tcp, 0, sizeof(*tcp));
792 #if SUPPORTED_PERSONALITIES > 1
793 tcp->currpers = current_personality;
797 if (stack_trace_enabled)
798 unwind_tcb_init(tcp);
803 error_msg("new tcb for pid %d, active tcbs:%d",
808 error_msg_and_die("bug in alloctcb");
812 get_tcb_priv_data(const struct tcb *tcp)
814 return tcp->_priv_data;
818 set_tcb_priv_data(struct tcb *tcp, void *const priv_data,
819 void (*const free_priv_data)(void *))
824 tcp->_free_priv_data = free_priv_data;
825 tcp->_priv_data = priv_data;
831 free_tcb_priv_data(struct tcb *tcp)
833 if (tcp->_priv_data) {
834 if (tcp->_free_priv_data) {
835 tcp->_free_priv_data(tcp->_priv_data);
836 tcp->_free_priv_data = NULL;
838 tcp->_priv_data = NULL;
843 droptcb(struct tcb *tcp)
849 for (p = 0; p < SUPPORTED_PERSONALITIES; ++p)
850 free(tcp->inject_vec[p]);
852 free_tcb_priv_data(tcp);
855 if (stack_trace_enabled) {
862 error_msg("dropped tcb for pid %d, %d remain",
866 if (followfork >= 2) {
867 if (tcp->curcol != 0)
868 fprintf(tcp->outf, " <detached ...>\n");
871 if (printing_tcp == tcp && tcp->curcol != 0)
872 fprintf(tcp->outf, " <detached ...>\n");
873 flush_tcp_output(tcp);
877 if (current_tcp == tcp)
879 if (printing_tcp == tcp)
882 memset(tcp, 0, sizeof(*tcp));
885 /* Detach traced process.
886 * Never call DETACH twice on the same process as both unattached and
887 * attached-unstopped processes give the same ESRCH. For unattached process we
888 * would SIGSTOP it and wait for its SIGSTOP notification forever.
891 detach(struct tcb *tcp)
897 * Linux wrongly insists the child be stopped
898 * before detaching. Arghh. We go through hoops
899 * to make a clean break of things.
902 if (!(tcp->flags & TCB_ATTACHED))
905 /* We attached but possibly didn't see the expected SIGSTOP.
906 * We must catch exactly one as otherwise the detached process
907 * would be left stopped (process state T).
909 if (tcp->flags & TCB_IGNORE_ONE_SIGSTOP)
912 error = ptrace(PTRACE_DETACH, tcp->pid, 0, 0);
914 /* On a clear day, you can see forever. */
917 if (errno != ESRCH) {
918 /* Shouldn't happen. */
919 perror_msg("detach: ptrace(PTRACE_DETACH,%u)", tcp->pid);
922 /* ESRCH: process is either not stopped or doesn't exist. */
923 if (my_tkill(tcp->pid, 0) < 0) {
925 /* Shouldn't happen. */
926 perror_msg("detach: tkill(%u,0)", tcp->pid);
927 /* else: process doesn't exist. */
930 /* Process is not stopped, need to stop it. */
933 * With SEIZE, tracee can be in group-stop already.
934 * In this state sending it another SIGSTOP does nothing.
935 * Need to use INTERRUPT.
936 * Testcase: trying to ^C a "strace -p <stopped_process>".
938 error = ptrace(PTRACE_INTERRUPT, tcp->pid, 0, 0);
942 perror_msg("detach: ptrace(PTRACE_INTERRUPT,%u)", tcp->pid);
944 error = my_tkill(tcp->pid, SIGSTOP);
948 perror_msg("detach: tkill(%u,SIGSTOP)", tcp->pid);
950 /* Either process doesn't exist, or some weird error. */
954 /* We end up here in three cases:
955 * 1. We sent PTRACE_INTERRUPT (use_seize case)
956 * 2. We sent SIGSTOP (!use_seize)
957 * 3. Attach SIGSTOP was already pending (TCB_IGNORE_ONE_SIGSTOP set)
961 if (waitpid(tcp->pid, &status, __WALL) < 0) {
965 * if (errno == ECHILD) break;
966 * ^^^ WRONG! We expect this PID to exist,
967 * and want to emit a message otherwise:
969 perror_msg("detach: waitpid(%u)", tcp->pid);
972 if (!WIFSTOPPED(status)) {
974 * Tracee exited or was killed by signal.
975 * We shouldn't normally reach this place:
976 * we don't want to consume exit status.
977 * Consider "strace -p PID" being ^C-ed:
978 * we want merely to detach from PID.
980 * However, we _can_ end up here if tracee
985 sig = WSTOPSIG(status);
987 error_msg("detach wait: event:%d sig:%d",
988 (unsigned)status >> 16, sig);
990 unsigned event = (unsigned)status >> 16;
991 if (event == PTRACE_EVENT_STOP /*&& sig == SIGTRAP*/) {
993 * sig == SIGTRAP: PTRACE_INTERRUPT stop.
994 * sig == other: process was already stopped
995 * with this stopping sig (see tests/detach-stopped).
996 * Looks like re-injecting this sig is not necessary
997 * in DETACH for the tracee to remain stopped.
1002 * PTRACE_INTERRUPT is not guaranteed to produce
1003 * the above event if other ptrace-stop is pending.
1004 * See tests/detach-sleeping testcase:
1005 * strace got SIGINT while tracee is sleeping.
1006 * We sent PTRACE_INTERRUPT.
1007 * We see syscall exit, not PTRACE_INTERRUPT stop.
1008 * We won't get PTRACE_INTERRUPT stop
1009 * if we would CONT now. Need to DETACH.
1011 if (sig == syscall_trap_sig)
1013 /* else: not sure in which case we can be here.
1014 * Signal stop? Inject it while detaching.
1016 ptrace_restart(PTRACE_DETACH, tcp, sig);
1019 /* Note: this check has to be after use_seize check */
1020 /* (else, in use_seize case SIGSTOP will be mistreated) */
1021 if (sig == SIGSTOP) {
1022 /* Detach, suppressing SIGSTOP */
1023 ptrace_restart(PTRACE_DETACH, tcp, 0);
1026 if (sig == syscall_trap_sig)
1028 /* Can't detach just yet, may need to wait for SIGSTOP */
1029 error = ptrace_restart(PTRACE_CONT, tcp, sig);
1031 /* Should not happen.
1032 * Note: ptrace_restart returns 0 on ESRCH, so it's not it.
1033 * ptrace_restart already emitted error message.
1040 if (!qflag && (tcp->flags & TCB_ATTACHED))
1041 error_msg("Process %u detached", tcp->pid);
1047 process_opt_p_list(char *opt)
1051 * We accept -p PID,PID; -p "`pidof PROG`"; -p "`pgrep PROG`".
1052 * pidof uses space as delim, pgrep uses newline. :(
1055 char *delim = opt + strcspn(opt, "\n\t ,");
1059 pid = string_to_uint(opt);
1061 error_msg_and_die("Invalid process id: '%s'", opt);
1063 if (pid == strace_tracer_pid) {
1064 error_msg_and_die("I'm sorry, I can't let you do that, Dave.");
1075 attach_tcb(struct tcb *const tcp)
1077 if (ptrace_attach_or_seize(tcp->pid) < 0) {
1078 perror_msg("attach: ptrace(%s, %d)",
1079 ptrace_attach_cmd, tcp->pid);
1084 tcp->flags |= TCB_ATTACHED | TCB_STARTUP | post_attach_sigstop;
1087 error_msg("attach to pid %d (main) succeeded", tcp->pid);
1089 char procdir[sizeof("/proc/%d/task") + sizeof(int) * 3];
1091 unsigned int ntid = 0, nerr = 0;
1093 if (followfork && tcp->pid != strace_child &&
1094 sprintf(procdir, "/proc/%d/task", tcp->pid) > 0 &&
1095 (dir = opendir(procdir)) != NULL) {
1098 while ((de = read_dir(dir)) != NULL) {
1099 if (de->d_fileno == 0)
1102 int tid = string_to_uint(de->d_name);
1103 if (tid <= 0 || tid == tcp->pid)
1107 if (ptrace_attach_or_seize(tid) < 0) {
1110 perror_msg("attach: ptrace(%s, %d)",
1111 ptrace_attach_cmd, tid);
1115 error_msg("attach to pid %d succeeded", tid);
1117 struct tcb *tid_tcp = alloctcb(tid);
1118 tid_tcp->flags |= TCB_ATTACHED | TCB_STARTUP |
1119 post_attach_sigstop;
1128 error_msg("Process %u attached"
1130 tcp->pid, ntid - nerr + 1);
1132 error_msg("Process %u attached",
1138 startup_attach(void)
1140 pid_t parent_pid = strace_tracer_pid;
1145 * Block user interruptions as we would leave the traced
1146 * process stopped (process state T) if we would terminate in
1147 * between PTRACE_ATTACH and wait4() on SIGSTOP.
1148 * We rely on cleanup() from this point on.
1151 sigprocmask(SIG_SETMASK, &blocked_set, NULL);
1153 if (daemonized_tracer) {
1156 perror_msg_and_die("fork");
1158 if (pid) { /* parent */
1160 * Wait for grandchild to attach to straced process
1161 * (grandparent). Grandchild SIGKILLs us after it attached.
1162 * Grandparent's wait() is unblocked by our death,
1163 * it proceeds to exec the straced program.
1166 _exit(0); /* paranoia */
1169 /* We will be the tracer process. Remember our new pid: */
1170 strace_tracer_pid = getpid();
1173 for (tcbi = 0; tcbi < tcbtabsize; tcbi++) {
1179 /* Is this a process we should attach to, but not yet attached? */
1180 if (tcp->flags & TCB_ATTACHED)
1181 continue; /* no, we already attached it */
1183 if (tcp->pid == parent_pid || tcp->pid == strace_tracer_pid) {
1185 perror_msg("attach: pid %d", tcp->pid);
1193 sigprocmask(SIG_SETMASK, &start_set, NULL);
1196 sigprocmask(SIG_SETMASK, &blocked_set, NULL);
1198 } /* for each tcbtab[] */
1200 if (daemonized_tracer) {
1202 * Make parent go away.
1203 * Also makes grandparent's wait() unblock.
1205 kill(parent_pid, SIGKILL);
1211 sigprocmask(SIG_SETMASK, &start_set, NULL);
1214 /* Stack-o-phobic exec helper, in the hope to work around
1215 * NOMMU + "daemonized tracer" difficulty.
1217 struct exec_params {
1223 struct sigaction child_sa;
1225 static struct exec_params params_for_tracee;
1227 static void ATTRIBUTE_NOINLINE ATTRIBUTE_NORETURN
1230 struct exec_params *params = ¶ms_for_tracee;
1232 if (params->fd_to_close >= 0)
1233 close(params->fd_to_close);
1234 if (!daemonized_tracer && !use_seize) {
1235 if (ptrace(PTRACE_TRACEME, 0L, 0L, 0L) < 0) {
1236 perror_msg_and_die("ptrace(PTRACE_TRACEME, ...)");
1240 if (username != NULL) {
1242 * It is important to set groups before we
1243 * lose privileges on setuid.
1245 if (initgroups(username, run_gid) < 0) {
1246 perror_msg_and_die("initgroups");
1248 if (setregid(run_gid, params->run_egid) < 0) {
1249 perror_msg_and_die("setregid");
1251 if (setreuid(run_uid, params->run_euid) < 0) {
1252 perror_msg_and_die("setreuid");
1254 } else if (geteuid() != 0)
1255 if (setreuid(run_uid, run_uid) < 0) {
1256 perror_msg_and_die("setreuid");
1259 if (!daemonized_tracer) {
1261 * Induce a ptrace stop. Tracer (our parent)
1262 * will resume us with PTRACE_SYSCALL and display
1263 * the immediately following execve syscall.
1264 * Can't do this on NOMMU systems, we are after
1265 * vfork: parent is blocked, stopping would deadlock.
1268 kill(getpid(), SIGSTOP);
1271 /* we depend on SIGCHLD set to SIG_DFL by init code */
1272 /* if it happens to be SIG_IGN'ed, wait won't block */
1277 if (params_for_tracee.child_sa.sa_handler != SIG_DFL)
1278 sigaction(SIGCHLD, ¶ms_for_tracee.child_sa, NULL);
1280 execv(params->pathname, params->argv);
1281 perror_msg_and_die("exec");
1285 * Open a dummy descriptor for use as a placeholder.
1286 * The descriptor is O_RDONLY with FD_CLOEXEC flag set.
1287 * A read attempt from such descriptor ends with EOF,
1288 * a write attempt is rejected with EBADF.
1291 open_dummy_desc(void)
1296 perror_msg_and_die("pipe");
1298 set_cloexec_flag(fds[0]);
1302 /* placeholder fds status for stdin and stdout */
1303 static bool fd_is_placeholder[2];
1306 * Ensure that all standard file descriptors are open by opening placeholder
1307 * file descriptors for those standard file descriptors that are not open.
1309 * The information which descriptors have been made open is saved
1310 * in fd_is_placeholder for later use.
1313 ensure_standard_fds_opened(void)
1317 while ((fd = open_dummy_desc()) <= 2) {
1320 fd_is_placeholder[fd] = true;
1328 * Redirect stdin and stdout unless they have been opened earlier
1329 * by ensure_standard_fds_opened as placeholders.
1332 redirect_standard_fds(void)
1337 * It might be a good idea to redirect stderr as well,
1338 * but we sometimes need to print error messages.
1340 for (i = 0; i <= 1; ++i) {
1341 if (!fd_is_placeholder[i]) {
1349 startup_child(char **argv)
1351 struct_stat statbuf;
1352 const char *filename;
1353 size_t filename_len;
1354 char pathname[PATH_MAX];
1359 filename_len = strlen(filename);
1361 if (filename_len > sizeof(pathname) - 1) {
1362 errno = ENAMETOOLONG;
1363 perror_msg_and_die("exec");
1365 if (strchr(filename, '/')) {
1366 strcpy(pathname, filename);
1368 #ifdef USE_DEBUGGING_EXEC
1370 * Debuggers customarily check the current directory
1371 * first regardless of the path but doing that gives
1372 * security geeks a panic attack.
1374 else if (stat_file(filename, &statbuf) == 0)
1375 strcpy(pathname, filename);
1376 #endif /* USE_DEBUGGING_EXEC */
1381 for (path = getenv("PATH"); path && *path; path += m) {
1382 const char *colon = strchr(path, ':');
1387 m = n = strlen(path);
1389 if (!getcwd(pathname, PATH_MAX))
1391 len = strlen(pathname);
1392 } else if (n > sizeof(pathname) - 1)
1395 strncpy(pathname, path, n);
1398 if (len && pathname[len - 1] != '/')
1399 pathname[len++] = '/';
1400 if (filename_len + len > sizeof(pathname) - 1)
1402 strcpy(pathname + len, filename);
1403 if (stat_file(pathname, &statbuf) == 0 &&
1404 /* Accept only regular files
1405 with some execute bits set.
1406 XXX not perfect, might still fail */
1407 S_ISREG(statbuf.st_mode) &&
1408 (statbuf.st_mode & 0111))
1411 if (!path || !*path)
1414 if (stat_file(pathname, &statbuf) < 0) {
1415 perror_msg_and_die("Can't stat '%s'", filename);
1418 params_for_tracee.fd_to_close = (shared_log != stderr) ? fileno(shared_log) : -1;
1419 params_for_tracee.run_euid = (statbuf.st_mode & S_ISUID) ? statbuf.st_uid : run_uid;
1420 params_for_tracee.run_egid = (statbuf.st_mode & S_ISGID) ? statbuf.st_gid : run_gid;
1421 params_for_tracee.argv = argv;
1423 * On NOMMU, can be safely freed only after execve in tracee.
1424 * It's hard to know when that happens, so we just leak it.
1426 params_for_tracee.pathname = NOMMU_SYSTEM ? xstrdup(pathname) : pathname;
1428 #if defined HAVE_PRCTL && defined PR_SET_PTRACER && defined PR_SET_PTRACER_ANY
1429 if (daemonized_tracer)
1430 prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY);
1435 perror_msg_and_die("fork");
1437 if ((pid != 0 && daemonized_tracer)
1438 || (pid == 0 && !daemonized_tracer)
1440 /* We are to become the tracee. Two cases:
1442 * not -D: we are child
1447 /* We are the tracer */
1449 if (!daemonized_tracer) {
1452 /* child did PTRACE_TRACEME, nothing to do in parent */
1454 if (!NOMMU_SYSTEM) {
1455 /* Wait until child stopped itself */
1457 while (waitpid(pid, &status, WSTOPPED) < 0) {
1460 perror_msg_and_die("waitpid");
1462 if (!WIFSTOPPED(status) || WSTOPSIG(status) != SIGSTOP) {
1463 kill_save_errno(pid, SIGKILL);
1464 perror_msg_and_die("Unexpected wait status %#x",
1468 /* Else: NOMMU case, we have no way to sync.
1469 * Just attach to it as soon as possible.
1470 * This means that we may miss a few first syscalls...
1473 if (ptrace_attach_or_seize(pid)) {
1474 kill_save_errno(pid, SIGKILL);
1475 perror_msg_and_die("attach: ptrace(%s, %d)",
1476 ptrace_attach_cmd, pid);
1481 tcp = alloctcb(pid);
1482 tcp->flags |= TCB_ATTACHED | TCB_STARTUP
1483 | TCB_SKIP_DETACH_ON_FIRST_EXEC
1484 | (NOMMU_SYSTEM ? 0 : (TCB_HIDE_LOG | post_attach_sigstop));
1487 /* With -D, we are *child* here, the tracee is our parent. */
1488 strace_child = strace_tracer_pid;
1489 strace_tracer_pid = getpid();
1490 tcp = alloctcb(strace_child);
1491 tcp->flags |= TCB_SKIP_DETACH_ON_FIRST_EXEC | TCB_HIDE_LOG;
1492 /* attaching will be done later, by startup_attach */
1493 /* note: we don't do newoutf(tcp) here either! */
1495 /* NOMMU BUG! -D mode is active, we (child) return,
1496 * and we will scribble over parent's stack!
1497 * When parent later unpauses, it segfaults.
1500 * (1) by declaring exec_or_die() NORETURN,
1501 * hopefully compiler will just jump to it
1502 * instead of call (won't push anything to stack),
1503 * (2) by trying very hard in exec_or_die()
1504 * to not use any stack,
1505 * (3) having a really big (PATH_MAX) stack object
1506 * in this function, which creates a "buffer" between
1507 * child's and parent's stack pointers.
1508 * This may save us if (1) and (2) failed
1509 * and compiler decided to use stack in exec_or_die() anyway
1510 * (happens on i386 because of stack parameter passing).
1512 * A cleaner solution is to use makecontext + setcontext
1513 * to create a genuine separate stack and execute on it.
1517 * A case where straced process is part of a pipe:
1518 * { sleep 1; yes | head -n99999; } | strace -o/dev/null sh -c 'exec <&-; sleep 9'
1519 * If strace won't close its fd#0, closing it in tracee is not enough:
1520 * the pipe is still open, it has a reader. Thus, "head" will not get its
1521 * SIGPIPE at once, on the first write.
1523 * Preventing it by redirecting strace's stdin/out.
1524 * (Don't leave fds 0 and 1 closed, this is bad practice: future opens
1525 * will reuse them, unexpectedly making a newly opened object "stdin").
1527 redirect_standard_fds();
1532 test_ptrace_seize(void)
1536 /* Need fork for test. NOMMU has no forks */
1538 post_attach_sigstop = 0; /* this sets use_seize to 1 */
1544 perror_msg_and_die("fork");
1551 /* PTRACE_SEIZE, unlike ATTACH, doesn't force tracee to trap. After
1552 * attaching tracee continues to run unless a trap condition occurs.
1553 * PTRACE_SEIZE doesn't affect signal or group stop state.
1555 if (ptrace(PTRACE_SEIZE, pid, 0, 0) == 0) {
1556 post_attach_sigstop = 0; /* this sets use_seize to 1 */
1557 } else if (debug_flag) {
1558 error_msg("PTRACE_SEIZE doesn't work");
1564 int status, tracee_pid;
1567 tracee_pid = waitpid(pid, &status, 0);
1568 if (tracee_pid <= 0) {
1571 perror_msg_and_die("%s: unexpected wait result %d",
1572 __func__, tracee_pid);
1574 if (WIFSIGNALED(status)) {
1577 error_msg_and_die("%s: unexpected wait status %#x",
1581 #else /* !USE_SEIZE */
1582 # define test_ptrace_seize() ((void)0)
1586 get_os_release(void)
1592 perror_msg_and_die("uname");
1593 /* u.release has this form: "3.2.9[-some-garbage]" */
1597 if (!(*p >= '0' && *p <= '9'))
1598 error_msg_and_die("Bad OS release string: '%s'", u.release);
1599 /* Note: this open-codes KERNEL_VERSION(): */
1600 rel = (rel << 8) | atoi(p);
1601 if (rel >= KERNEL_VERSION(1, 0, 0))
1603 while (*p >= '0' && *p <= '9')
1606 if (rel >= KERNEL_VERSION(0, 1, 0)) {
1607 /* "X.Y-something" means "X.Y.0" */
1611 error_msg_and_die("Bad OS release string: '%s'", u.release);
1619 set_sigaction(int signo, void (*sighandler)(int), struct sigaction *oldact)
1621 /* if signal handler is a function, add the signal to blocked_set */
1622 if (sighandler != SIG_IGN && sighandler != SIG_DFL)
1623 sigaddset(&blocked_set, signo);
1625 const struct sigaction sa = { .sa_handler = sighandler };
1626 sigaction(signo, &sa, oldact);
1630 * Initialization part of main() was eating much stack (~0.5k),
1631 * which was unused after init.
1632 * We can reuse it if we move init code into a separate function.
1634 * Don't want main() to inline us and defeat the reason
1635 * we have a separate function.
1637 static void ATTRIBUTE_NOINLINE
1638 init(int argc, char *argv[])
1643 if (!program_invocation_name || !*program_invocation_name) {
1644 static char name[] = "strace";
1645 program_invocation_name =
1646 (argv[0] && *argv[0]) ? argv[0] : name;
1649 strace_tracer_pid = getpid();
1651 os_release = get_os_release();
1653 shared_log = stderr;
1654 set_sortby(DEFAULT_SORTBY);
1655 set_personality(DEFAULT_PERSONALITY);
1656 qualify("trace=all");
1657 qualify("abbrev=all");
1658 qualify("verbose=all");
1659 #if DEFAULT_QUAL_FLAGS != (QUAL_TRACE | QUAL_ABBREV | QUAL_VERBOSE)
1660 # error Bug in DEFAULT_QUAL_FLAGS
1662 qualify("signal=all");
1663 while ((c = getopt(argc, argv,
1664 "+b:cCdfFhiqrtTvVwxyz"
1665 #ifdef USE_LIBUNWIND
1669 "a:e:o:O:p:s:S:u:E:P:I:")) != EOF) {
1672 if (strcmp(optarg, "execve") != 0)
1673 error_msg_and_die("Syscall '%s' for -b isn't supported",
1675 detach_on_execve = 1;
1678 if (cflag == CFLAG_BOTH) {
1679 error_msg_and_help("-c and -C are mutually exclusive");
1681 cflag = CFLAG_ONLY_STATS;
1684 if (cflag == CFLAG_ONLY_STATS) {
1685 error_msg_and_help("-c and -C are mutually exclusive");
1693 daemonized_tracer = 1;
1720 count_wallclock = 1;
1729 qualify("abbrev=none");
1736 not_failing_only = 1;
1739 acolumn = string_to_uint(optarg);
1741 error_opt_arg(c, optarg);
1750 i = string_to_uint(optarg);
1752 error_opt_arg(c, optarg);
1756 process_opt_p_list(optarg);
1759 pathtrace_select(optarg);
1762 i = string_to_uint(optarg);
1763 if (i < 0 || (unsigned int) i > -1U / 4)
1764 error_opt_arg(c, optarg);
1773 #ifdef USE_LIBUNWIND
1775 stack_trace_enabled = true;
1779 if (putenv(optarg) < 0)
1780 perror_msg_and_die("putenv");
1783 opt_intr = string_to_uint_upto(optarg, NUM_INTR_OPTS - 1);
1785 error_opt_arg(c, optarg);
1788 error_msg_and_help(NULL);
1796 if (argc < 0 || (!argv[0] && !nprocs)) {
1797 error_msg_and_help("must have PROG [ARGS] or -p PID");
1800 if (!argv[0] && daemonized_tracer) {
1801 error_msg_and_help("PROG [ARGS] must be specified with -D");
1807 if (followfork >= 2 && cflag) {
1808 error_msg_and_help("(-c or -C) and -ff are mutually exclusive");
1811 if (count_wallclock && !cflag) {
1812 error_msg_and_help("-w must be given with (-c or -C)");
1815 if (cflag == CFLAG_ONLY_STATS) {
1817 error_msg("-%c has no effect with -c", 'i');
1818 #ifdef USE_LIBUNWIND
1819 if (stack_trace_enabled)
1820 error_msg("-%c has no effect with -c", 'k');
1823 error_msg("-%c has no effect with -c", 'r');
1825 error_msg("-%c has no effect with -c", 't');
1827 error_msg("-%c has no effect with -c", 'T');
1829 error_msg("-%c has no effect with -c", 'y');
1834 error_msg("-tt has no effect with -r");
1838 acolumn_spaces = xmalloc(acolumn + 1);
1839 memset(acolumn_spaces, ' ', acolumn);
1840 acolumn_spaces[acolumn] = '\0';
1842 sigprocmask(SIG_SETMASK, NULL, &start_set);
1843 memcpy(&blocked_set, &start_set, sizeof(blocked_set));
1845 set_sigaction(SIGCHLD, SIG_DFL, ¶ms_for_tracee.child_sa);
1847 #ifdef USE_LIBUNWIND
1848 if (stack_trace_enabled) {
1852 for (tcbi = 0; tcbi < tcbtabsize; ++tcbi) {
1853 unwind_tcb_init(tcbtab[tcbi]);
1858 /* See if they want to run as another user. */
1859 if (username != NULL) {
1860 struct passwd *pent;
1862 if (getuid() != 0 || geteuid() != 0) {
1863 error_msg_and_die("You must be root to use the -u option");
1865 pent = getpwnam(username);
1867 error_msg_and_die("Cannot find user '%s'", username);
1869 run_uid = pent->pw_uid;
1870 run_gid = pent->pw_gid;
1877 ptrace_setoptions |= PTRACE_O_TRACECLONE |
1878 PTRACE_O_TRACEFORK |
1879 PTRACE_O_TRACEVFORK;
1881 error_msg("ptrace_setoptions = %#x", ptrace_setoptions);
1882 test_ptrace_seize();
1885 * Is something weird with our stdin and/or stdout -
1886 * for example, may they be not open? In this case,
1887 * ensure that none of the future opens uses them.
1889 * This was seen in the wild when /proc/sys/kernel/core_pattern
1890 * was set to "|/bin/strace -o/tmp/LOG PROG":
1891 * kernel runs coredump helper with fd#0 open but fd#1 closed (!),
1892 * therefore LOG gets opened to fd#1, and fd#1 is closed by
1893 * "don't hold up stdin/out open" code soon after.
1895 ensure_standard_fds_opened();
1897 /* Check if they want to redirect the output. */
1899 /* See if they want to pipe the output. */
1900 if (outfname[0] == '|' || outfname[0] == '!') {
1902 * We can't do the <outfname>.PID funny business
1903 * when using popen, so prohibit it.
1905 if (followfork >= 2)
1906 error_msg_and_help("piping the output and -ff are mutually exclusive");
1907 shared_log = strace_popen(outfname + 1);
1908 } else if (followfork < 2)
1909 shared_log = strace_fopen(outfname);
1911 /* -ff without -o FILE is the same as single -f */
1912 if (followfork >= 2)
1916 if (!outfname || outfname[0] == '|' || outfname[0] == '!') {
1917 setvbuf(shared_log, NULL, _IOLBF, 0);
1921 * argv[0] -pPID -oFILE Default interactive setting
1922 * yes * 0 INTR_WHILE_WAIT
1923 * no 1 0 INTR_WHILE_WAIT
1924 * yes * 1 INTR_NEVER
1925 * no 1 1 INTR_WHILE_WAIT
1928 if (outfname && argv[0]) {
1930 opt_intr = INTR_NEVER;
1935 opt_intr = INTR_WHILE_WAIT;
1938 * startup_child() must be called before the signal handlers get
1939 * installed below as they are inherited into the spawned process.
1940 * Also we do not need to be protected by them as during interruption
1941 * in the startup_child() mode we kill the spawned process anyway.
1944 startup_child(argv);
1947 set_sigaction(SIGTTOU, SIG_IGN, NULL);
1948 set_sigaction(SIGTTIN, SIG_IGN, NULL);
1949 if (opt_intr != INTR_ANYWHERE) {
1950 if (opt_intr == INTR_BLOCK_TSTP_TOO)
1951 set_sigaction(SIGTSTP, SIG_IGN, NULL);
1953 * In interactive mode (if no -o OUTFILE, or -p PID is used),
1954 * fatal signals are blocked while syscall stop is processed,
1955 * and acted on in between, when waiting for new syscall stops.
1956 * In non-interactive mode, signals are ignored.
1958 set_sigaction(SIGHUP, interactive ? interrupt : SIG_IGN, NULL);
1959 set_sigaction(SIGINT, interactive ? interrupt : SIG_IGN, NULL);
1960 set_sigaction(SIGQUIT, interactive ? interrupt : SIG_IGN, NULL);
1961 set_sigaction(SIGPIPE, interactive ? interrupt : SIG_IGN, NULL);
1962 set_sigaction(SIGTERM, interactive ? interrupt : SIG_IGN, NULL);
1965 if (nprocs != 0 || daemonized_tracer)
1968 /* Do we want pids printed in our -o OUTFILE?
1969 * -ff: no (every pid has its own file); or
1970 * -f: yes (there can be more pids in the future); or
1971 * -p PID1,PID2: yes (there are already more than one pid)
1973 print_pid_pfx = (outfname && followfork < 2 && (followfork == 1 || nprocs > 1));
1984 for (i = 0; i < tcbtabsize; i++) {
1985 struct tcb *tcp = tcbtab[i];
1986 if (tcp->pid == pid)
2000 /* 'interrupted' is a volatile object, fetch it only once */
2001 fatal_sig = interrupted;
2003 fatal_sig = SIGTERM;
2005 for (i = 0; i < tcbtabsize; i++) {
2010 error_msg("cleanup: looking at pid %u", tcp->pid);
2011 if (tcp->pid == strace_child) {
2012 kill(tcp->pid, SIGCONT);
2013 kill(tcp->pid, fatal_sig);
2018 call_summary(shared_log);
2028 print_debug_info(const int pid, int status)
2030 const unsigned int event = (unsigned int) status >> 16;
2031 char buf[sizeof("WIFEXITED,exitcode=%u") + sizeof(int)*3 /*paranoia:*/ + 16];
2032 char evbuf[sizeof(",EVENT_VFORK_DONE (%u)") + sizeof(int)*3 /*paranoia:*/ + 16];
2035 if (WIFSIGNALED(status))
2037 sprintf(buf, "WIFSIGNALED,%ssig=%s",
2038 WCOREDUMP(status) ? "core," : "",
2039 signame(WTERMSIG(status)));
2041 sprintf(buf, "WIFSIGNALED,sig=%s",
2042 signame(WTERMSIG(status)));
2044 if (WIFEXITED(status))
2045 sprintf(buf, "WIFEXITED,exitcode=%u", WEXITSTATUS(status));
2046 if (WIFSTOPPED(status))
2047 sprintf(buf, "WIFSTOPPED,sig=%s", signame(WSTOPSIG(status)));
2050 static const char *const event_names[] = {
2051 [PTRACE_EVENT_CLONE] = "CLONE",
2052 [PTRACE_EVENT_FORK] = "FORK",
2053 [PTRACE_EVENT_VFORK] = "VFORK",
2054 [PTRACE_EVENT_VFORK_DONE] = "VFORK_DONE",
2055 [PTRACE_EVENT_EXEC] = "EXEC",
2056 [PTRACE_EVENT_EXIT] = "EXIT",
2057 /* [PTRACE_EVENT_STOP (=128)] would make biggish array */
2059 const char *e = "??";
2060 if (event < ARRAY_SIZE(event_names))
2061 e = event_names[event];
2062 else if (event == PTRACE_EVENT_STOP)
2064 sprintf(evbuf, ",EVENT_%s (%u)", e, event);
2066 error_msg("[wait(0x%06x) = %u] %s%s", status, pid, buf, evbuf);
2070 maybe_allocate_tcb(const int pid, int status)
2072 if (!WIFSTOPPED(status)) {
2073 if (detach_on_execve && pid == strace_child) {
2074 /* example: strace -bexecve sh -c 'exec true' */
2079 * This can happen if we inherited an unknown child.
2080 * Example: (sleep 1 & exec strace true)
2082 error_msg("Exit of unknown pid %u ignored", pid);
2086 /* We assume it's a fork/vfork/clone child */
2087 struct tcb *tcp = alloctcb(pid);
2088 tcp->flags |= TCB_ATTACHED | TCB_STARTUP | post_attach_sigstop;
2091 error_msg("Process %d attached", pid);
2095 * This can happen if a clone call misused CLONE_PTRACE itself.
2097 unsigned int sig = WSTOPSIG(status);
2100 unsigned int event = (unsigned int) status >> 16;
2101 if (event == PTRACE_EVENT_STOP)
2108 ptrace(PTRACE_DETACH, pid, NULL, (unsigned long) sig);
2109 error_msg("Detached unknown pid %d%s%s", pid,
2110 sig ? " with signal " : "",
2111 sig ? signame(sig) : "");
2117 maybe_switch_tcbs(struct tcb *tcp, const int pid)
2120 struct tcb *execve_thread;
2123 if (ptrace(PTRACE_GETEVENTMSG, pid, NULL, &old_pid) < 0)
2125 /* Avoid truncation in pid2tcb() param passing */
2126 if (old_pid <= 0 || old_pid == pid)
2128 if ((unsigned long) old_pid > UINT_MAX)
2130 execve_thread = pid2tcb(old_pid);
2131 /* It should be !NULL, but I feel paranoid */
2135 if (execve_thread->curcol != 0) {
2137 * One case we are here is -ff:
2138 * try "strace -oLOG -ff test/threaded_execve"
2140 fprintf(execve_thread->outf, " <pid changed to %d ...>\n", pid);
2141 /*execve_thread->curcol = 0; - no need, see code below */
2143 /* Swap output FILEs (needed for -ff) */
2144 fp = execve_thread->outf;
2145 execve_thread->outf = tcp->outf;
2147 /* And their column positions */
2148 execve_thread->curcol = tcp->curcol;
2150 /* Drop leader, but close execve'd thread outfile (if -ff) */
2152 /* Switch to the thread, reusing leader's outfile and pid */
2153 tcp = execve_thread;
2155 if (cflag != CFLAG_ONLY_STATS) {
2157 tprintf("+++ superseded by execve in pid %lu +++\n", old_pid);
2159 tcp->flags |= TCB_REPRINT;
2166 print_signalled(struct tcb *tcp, const int pid, int status)
2168 if (pid == strace_child) {
2169 exit_code = 0x100 | WTERMSIG(status);
2173 if (cflag != CFLAG_ONLY_STATS
2174 && is_number_in_set(WTERMSIG(status), &signal_set)) {
2177 tprintf("+++ killed by %s %s+++\n",
2178 signame(WTERMSIG(status)),
2179 WCOREDUMP(status) ? "(core dumped) " : "");
2181 tprintf("+++ killed by %s +++\n",
2182 signame(WTERMSIG(status)));
2189 print_exited(struct tcb *tcp, const int pid, int status)
2191 if (pid == strace_child) {
2192 exit_code = WEXITSTATUS(status);
2196 if (cflag != CFLAG_ONLY_STATS &&
2199 tprintf("+++ exited with %d +++\n", WEXITSTATUS(status));
2205 print_stopped(struct tcb *tcp, const siginfo_t *si, const unsigned int sig)
2207 if (cflag != CFLAG_ONLY_STATS
2209 && is_number_in_set(sig, &signal_set)) {
2212 tprintf("--- %s ", signame(sig));
2216 tprintf("--- stopped by %s ---\n", signame(sig));
2222 startup_tcb(struct tcb *tcp)
2225 error_msg("pid %d has TCB_STARTUP, initializing it", tcp->pid);
2227 tcp->flags &= ~TCB_STARTUP;
2231 error_msg("setting opts 0x%x on pid %d",
2232 ptrace_setoptions, tcp->pid);
2233 if (ptrace(PTRACE_SETOPTIONS, tcp->pid, NULL, ptrace_setoptions) < 0) {
2234 if (errno != ESRCH) {
2235 /* Should never happen, really */
2236 perror_msg_and_die("PTRACE_SETOPTIONS");
2241 if (get_scno(tcp) == 1)
2242 tcp->s_prev_ent = tcp->s_ent;
2246 print_event_exit(struct tcb *tcp)
2248 if (entering(tcp) || filtered(tcp) || hide_log(tcp)
2249 || cflag == CFLAG_ONLY_STATS) {
2253 if (followfork < 2 && printing_tcp && printing_tcp != tcp
2254 && printing_tcp->curcol != 0) {
2255 current_tcp = printing_tcp;
2256 tprints(" <unfinished ...>\n");
2257 flush_tcp_output(printing_tcp);
2258 printing_tcp->curcol = 0;
2262 if ((followfork < 2 && printing_tcp != tcp)
2263 || (tcp->flags & TCB_REPRINT)) {
2264 tcp->flags &= ~TCB_REPRINT;
2266 tprintf("<... %s resumed>", tcp->s_ent->sys_name);
2269 if (!(tcp->sys_func_rval & RVAL_DECODED)) {
2271 * The decoder has probably decided to print something
2272 * on exiting syscall which is not going to happen.
2274 tprints(" <unfinished ...>");
2283 /* Break the main loop. */
2286 /* Call next_event() again. */
2289 /* Restart the tracee with signal 0 and call next_event() again. */
2293 * For all the events below, current_tcp is set to current tracee's
2294 * tcb. All the suggested actions imply that you want to continue
2295 * tracing of the current tracee; alternatively, you can detach it.
2299 * Syscall entry or exit.
2300 * Restart the tracee with signal 0, or with an injected signal number.
2305 * Tracee received signal with number WSTOPSIG(*pstatus); signal info
2306 * is written to *si. Restart the tracee (with that signal number
2307 * if you want to deliver it).
2309 TE_SIGNAL_DELIVERY_STOP,
2312 * Tracee was killed by a signal with number WTERMSIG(*pstatus).
2317 * Tracee was stopped by a signal with number WSTOPSIG(*pstatus).
2318 * Restart the tracee with that signal number.
2323 * Tracee exited with status WEXITSTATUS(*pstatus).
2328 * Tracee is going to perform execve().
2329 * Restart the tracee with signal 0.
2331 TE_STOP_BEFORE_EXECVE,
2334 * Tracee is going to terminate.
2335 * Restart the tracee with signal 0.
2337 TE_STOP_BEFORE_EXIT,
2340 static enum trace_event
2341 next_event(int *pstatus, siginfo_t *si)
2353 * Used to exit simply when nprocs hits zero, but in this testcase:
2354 * int main(void) { _exit(!!fork()); }
2355 * under strace -f, parent sometimes (rarely) manages
2356 * to exit before we see the first stop of the child,
2357 * and we are losing track of it:
2358 * 19923 clone(...) = 19924
2359 * 19923 exit_group(1) = ?
2360 * 19923 +++ exited with 1 +++
2361 * Exiting only when wait() returns ECHILD works better.
2363 if (popen_pid != 0) {
2364 /* However, if -o|logger is in use, we can't do that.
2365 * Can work around that by double-forking the logger,
2366 * but that loses the ability to wait for its completion
2367 * on exit. Oh well...
2374 sigprocmask(SIG_SETMASK, &start_set, NULL);
2375 pid = wait4(-1, pstatus, __WALL, (cflag ? &ru : NULL));
2378 sigprocmask(SIG_SETMASK, &blocked_set, NULL);
2381 if (wait_errno == EINTR)
2383 if (nprocs == 0 && wait_errno == ECHILD)
2386 * If nprocs > 0, ECHILD is not expected,
2387 * treat it as any other error here:
2390 perror_msg_and_die("wait4(__WALL)");
2395 if (pid == popen_pid) {
2396 if (!WIFSTOPPED(status))
2402 print_debug_info(pid, status);
2404 /* Look up 'pid' in our table. */
2408 tcp = maybe_allocate_tcb(pid, status);
2415 /* Set current output file */
2419 tv_sub(&tcp->dtime, &ru.ru_stime, &tcp->stime);
2420 tcp->stime = ru.ru_stime;
2423 if (WIFSIGNALED(status))
2424 return TE_SIGNALLED;
2426 if (WIFEXITED(status))
2430 * As WCONTINUED flag has not been specified to wait4,
2431 * it cannot be WIFCONTINUED(status), so the only case
2432 * that remains is WIFSTOPPED(status).
2435 /* Is this the very first time we see this tracee stopped? */
2436 if (tcp->flags & TCB_STARTUP)
2439 const unsigned int sig = WSTOPSIG(status);
2440 const unsigned int event = (unsigned int) status >> 16;
2445 * Is this post-attach SIGSTOP?
2446 * Interestingly, the process may stop
2447 * with STOPSIG equal to some other signal
2448 * than SIGSTOP if we happened to attach
2449 * just before the process takes a signal.
2451 if (sig == SIGSTOP && (tcp->flags & TCB_IGNORE_ONE_SIGSTOP)) {
2453 error_msg("ignored SIGSTOP on pid %d", tcp->pid);
2454 tcp->flags &= ~TCB_IGNORE_ONE_SIGSTOP;
2456 } else if (sig == syscall_trap_sig) {
2457 return TE_SYSCALL_STOP;
2459 *si = (siginfo_t) {};
2461 * True if tracee is stopped by signal
2462 * (as opposed to "tracee received signal").
2463 * TODO: shouldn't we check for errno == EINVAL too?
2464 * We can get ESRCH instead, you know...
2466 bool stopped = ptrace(PTRACE_GETSIGINFO, pid, 0, si) < 0;
2467 return stopped ? TE_GROUP_STOP : TE_SIGNAL_DELIVERY_STOP;
2471 case PTRACE_EVENT_STOP:
2473 * PTRACE_INTERRUPT-stop or group-stop.
2474 * PTRACE_INTERRUPT-stop has sig == SIGTRAP here.
2481 return TE_GROUP_STOP;
2485 case PTRACE_EVENT_EXEC:
2486 return TE_STOP_BEFORE_EXECVE;
2487 case PTRACE_EVENT_EXIT:
2488 return TE_STOP_BEFORE_EXIT;
2495 trace_syscall(struct tcb *tcp, unsigned int *sig)
2497 if (entering(tcp)) {
2498 int res = syscall_entering_decode(tcp);
2503 res = syscall_entering_trace(tcp, sig);
2505 syscall_entering_finish(tcp, res);
2508 struct timeval tv = {};
2509 int res = syscall_exiting_decode(tcp, &tv);
2511 res = syscall_exiting_trace(tcp, tv, res);
2513 syscall_exiting_finish(tcp);
2518 /* Returns true iff the main trace loop has to continue. */
2520 dispatch_event(enum trace_event ret, int *pstatus, siginfo_t *si)
2522 unsigned int restart_op = PTRACE_SYSCALL;
2523 unsigned int restart_sig = 0;
2535 case TE_SYSCALL_STOP:
2536 if (trace_syscall(current_tcp, &restart_sig) < 0) {
2538 * ptrace() failed in trace_syscall().
2539 * Likely a result of process disappearing mid-flight.
2540 * Observed case: exit_group() or SIGKILL terminating
2541 * all processes in thread group.
2542 * We assume that ptrace error was caused by process death.
2543 * We used to detach(current_tcp) here, but since we no
2544 * longer implement "detach before death" policy/hack,
2545 * we can let this process to report its death to us
2546 * normally, via WIFEXITED or WIFSIGNALED wait status.
2552 case TE_SIGNAL_DELIVERY_STOP:
2553 restart_sig = WSTOPSIG(*pstatus);
2554 print_stopped(current_tcp, si, restart_sig);
2558 print_signalled(current_tcp, current_tcp->pid, *pstatus);
2559 droptcb(current_tcp);
2563 restart_sig = WSTOPSIG(*pstatus);
2564 print_stopped(current_tcp, NULL, restart_sig);
2567 * This ends ptrace-stop, but does *not* end group-stop.
2568 * This makes stopping signals work properly on straced
2569 * process (that is, process really stops. It used to
2572 restart_op = PTRACE_LISTEN;
2578 print_exited(current_tcp, current_tcp->pid, *pstatus);
2579 droptcb(current_tcp);
2582 case TE_STOP_BEFORE_EXECVE:
2584 * Under Linux, execve changes pid to thread leader's pid,
2585 * and we see this changed pid on EVENT_EXEC and later,
2586 * execve sysexit. Leader "disappears" without exit
2587 * notification. Let user know that, drop leader's tcb,
2588 * and fix up pid in execve thread's tcb.
2589 * Effectively, execve thread's tcb replaces leader's tcb.
2591 * BTW, leader is 'stuck undead' (doesn't report WIFEXITED
2592 * on exit syscall) in multithreaded programs exactly
2593 * in order to handle this case.
2595 * PTRACE_GETEVENTMSG returns old pid starting from Linux 3.0.
2596 * On 2.6 and earlier, it can return garbage.
2598 if (os_release >= KERNEL_VERSION(3, 0, 0))
2599 current_tcp = maybe_switch_tcbs(current_tcp, current_tcp->pid);
2601 if (detach_on_execve) {
2602 if (current_tcp->flags & TCB_SKIP_DETACH_ON_FIRST_EXEC) {
2603 current_tcp->flags &= ~TCB_SKIP_DETACH_ON_FIRST_EXEC;
2605 detach(current_tcp); /* do "-b execve" thingy */
2611 case TE_STOP_BEFORE_EXIT:
2612 print_event_exit(current_tcp);
2616 /* We handled quick cases, we are permitted to interrupt now. */
2620 if (ptrace_restart(restart_op, current_tcp, restart_sig) < 0) {
2621 /* Note: ptrace_restart emitted error message */
2628 #ifdef ENABLE_COVERAGE_GCOV
2629 extern void __gcov_flush(void);
2632 static void ATTRIBUTE_NORETURN
2637 if (shared_log != stderr)
2640 while (waitpid(popen_pid, NULL, 0) < 0 && errno == EINTR)
2643 if (exit_code > 0xff) {
2644 /* Avoid potential core file clobbering. */
2645 struct_rlimit rlim = {0, 0};
2646 set_rlimit(RLIMIT_CORE, &rlim);
2648 /* Child was killed by a signal, mimic that. */
2650 signal(exit_code, SIG_DFL);
2651 #ifdef ENABLE_COVERAGE_GCOV
2656 /* Unblock the signal. */
2659 sigaddset(&mask, exit_code);
2660 #ifdef ENABLE_COVERAGE_GCOV
2663 sigprocmask(SIG_UNBLOCK, &mask, NULL);
2665 /* Paranoia - what if this signal is not fatal?
2666 Exit with 128 + signo then. */
2673 main(int argc, char *argv[])
2677 exit_code = !nprocs;
2681 while (dispatch_event(next_event(&status, &si), &status, &si))