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>
49 #include "number_set.h"
52 #include "printsiginfo.h"
54 /* In some libc, these aren't declared. Do it ourself: */
55 extern char **environ;
60 /* if this is true do the stack trace for every system call */
61 bool stack_trace_enabled;
64 #define my_tkill(tid, sig) syscall(__NR_tkill, (tid), (sig))
66 /* Glue for systems without a MMU that cannot provide fork() */
67 #if !defined(HAVE_FORK)
69 # define NOMMU_SYSTEM 1
72 # define fork() vfork()
75 const unsigned int syscall_trap_sig = SIGTRAP | 0x80;
77 cflag_t cflag = CFLAG_NONE;
78 unsigned int followfork;
79 unsigned int ptrace_setoptions = PTRACE_O_TRACESYSGOOD | PTRACE_O_TRACEEXEC
87 static unsigned int tflag;
89 static bool print_pid_pfx;
94 INTR_ANYWHERE = 1, /* don't block/ignore any signals */
95 INTR_WHILE_WAIT = 2, /* block fatal signals while decoding syscall. default */
96 INTR_NEVER = 3, /* block fatal signals. default if '-o FILE PROG' */
97 INTR_BLOCK_TSTP_TOO = 4, /* block fatal signals and SIGTSTP (^Z) */
101 /* We play with signal mask only if this mode is active: */
102 #define interactive (opt_intr == INTR_WHILE_WAIT)
105 * daemonized_tracer supports -D option.
106 * With this option, strace forks twice.
107 * Unlike normal case, with -D *grandparent* process exec's,
108 * becoming a traced process. Child exits (this prevents traced process
109 * from having children it doesn't expect to have), and grandchild
110 * attaches to grandparent similarly to strace -p PID.
111 * This allows for more transparent interaction in cases
112 * when process and its parent are communicating via signals,
113 * wait() etc. Without -D, strace process gets lodged in between,
114 * disrupting parent<->child link.
116 static bool daemonized_tracer;
119 static int post_attach_sigstop = TCB_IGNORE_ONE_SIGSTOP;
120 # define use_seize (post_attach_sigstop == 0)
122 # define post_attach_sigstop TCB_IGNORE_ONE_SIGSTOP
126 /* Sometimes we want to print only succeeding syscalls. */
127 bool not_failing_only;
129 /* Show path associated with fd arguments */
130 unsigned int show_fd_path;
132 static bool detach_on_execve;
134 static int exit_code;
135 static int strace_child;
136 static int strace_tracer_pid;
138 static const char *username;
139 static uid_t run_uid;
140 static gid_t run_gid;
142 unsigned int max_strlen = DEFAULT_STRLEN;
143 static int acolumn = DEFAULT_ACOLUMN;
144 static char *acolumn_spaces;
146 static const char *outfname;
147 /* If -ff, points to stderr. Else, it's our common output log */
148 static FILE *shared_log;
150 struct tcb *printing_tcp;
151 static struct tcb *current_tcp;
153 static struct tcb **tcbtab;
154 static unsigned int nprocs, tcbtabsize;
156 #ifndef HAVE_PROGRAM_INVOCATION_NAME
157 char *program_invocation_name;
160 unsigned os_release; /* generated from uname()'s u.release */
162 static void detach(struct tcb *tcp);
163 static void cleanup(void);
164 static void interrupt(int sig);
165 static sigset_t start_set, blocked_set;
167 #ifdef HAVE_SIG_ATOMIC_T
168 static volatile sig_atomic_t interrupted;
170 static volatile int interrupted;
173 #ifndef HAVE_STRERROR
175 #if !HAVE_DECL_SYS_ERRLIST
177 extern char *sys_errlist[];
183 static char buf[sizeof("Unknown error %d") + sizeof(int)*3];
185 if (err_no < 1 || err_no >= sys_nerr) {
186 sprintf(buf, "Unknown error %d", err_no);
189 return sys_errlist[err_no];
192 #endif /* HAVE_STERRROR */
197 static const char features[] =
200 #endif /* USE_LIBUNWIND */
203 printf("%s -- version %s\n"
204 "Copyright (c) 1991-%s The strace developers <%s>.\n"
205 "This is free software; see the source for copying conditions. There is NO\n"
206 "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n",
207 PACKAGE_NAME, PACKAGE_VERSION, COPYRIGHT_YEAR, PACKAGE_URL);
208 printf("\nOptional features enabled:%s\n",
209 features[0] ? features : " (none)");
216 usage: strace [-CdffhiqrtttTvVwxxy] [-I n] [-e expr]...\n\
217 [-a column] [-o file] [-s strsize] [-P path]...\n\
218 -p pid... / [-D] [-E var=val]... [-u username] PROG [ARGS]\n\
219 or: strace -c[dfw] [-I n] [-e expr]... [-O overhead] [-S sortby]\n\
220 -p pid... / [-D] [-E var=val]... [-u username] PROG [ARGS]\n\
223 -a column alignment COLUMN for printing syscall results (default %d)\n\
224 -i print instruction pointer at time of syscall\n\
228 -k obtain stack trace between each syscall (experimental)\n\
232 -o file send trace output to FILE instead of stderr\n\
233 -q suppress messages about attaching, detaching, etc.\n\
234 -r print relative timestamp\n\
235 -s strsize limit length of print strings to STRSIZE chars (default %d)\n\
236 -t print absolute timestamp\n\
237 -tt print absolute timestamp with usecs\n\
238 -T print time spent in each syscall\n\
239 -x print non-ascii strings in hex\n\
240 -xx print all strings in hex\n\
241 -y print paths associated with file descriptor arguments\n\
242 -yy print protocol specific information associated with socket file descriptors\n\
245 -c count time, calls, and errors for each syscall and report summary\n\
246 -C like -c but also print regular output\n\
247 -O overhead set overhead for tracing syscalls to OVERHEAD usecs\n\
248 -S sortby sort syscall counts by: time, calls, name, nothing (default %s)\n\
249 -w summarise syscall latency (default is system time)\n\
252 -e expr a qualifying expression: option=[!]all or option=[!]val1[,val2]...\n\
253 options: trace, abbrev, verbose, raw, signal, read, write, fault\n\
254 -P path trace accesses to path\n\
257 -b execve detach on execve syscall\n\
258 -D run tracer process as a detached grandchild, not as parent\n\
260 -ff follow forks with output into separate files\n\
262 1: no signals are blocked\n\
263 2: fatal signals are blocked while decoding syscall (default)\n\
264 3: fatal signals are always blocked (default if '-o FILE PROG')\n\
265 4: fatal signals and SIGTSTP (^Z) are always blocked\n\
266 (useful to make 'strace -o FILE PROG' not stop on ^Z)\n\
269 -E var remove var from the environment for command\n\
270 -E var=val put var=val in the environment for command\n\
271 -p pid trace process with process id PID, may be repeated\n\
272 -u username run command as username handling setuid and/or setgid\n\
275 -d enable debug output to stderr\n\
276 -v verbose mode: print unabbreviated argv, stat, termios, etc. args\n\
277 -h print help message\n\
280 /* ancient, no one should use it
281 -F -- attempt to follow vforks (deprecated, use -f)\n\
283 /* this is broken, so don't document it
284 -z -- print only succeeding syscalls\n\
286 , DEFAULT_ACOLUMN, DEFAULT_STRLEN, DEFAULT_SORTBY);
290 void ATTRIBUTE_NORETURN
293 if (strace_tracer_pid == getpid()) {
301 error_opt_arg(int opt, const char *arg)
303 error_msg_and_help("invalid -%c argument: '%s'", opt, arg);
306 static const char *ptrace_attach_cmd;
309 ptrace_attach_or_seize(int pid)
314 return ptrace_attach_cmd = "PTRACE_ATTACH",
315 ptrace(PTRACE_ATTACH, pid, 0L, 0L);
316 r = ptrace(PTRACE_SEIZE, pid, 0L, (unsigned long) ptrace_setoptions);
318 return ptrace_attach_cmd = "PTRACE_SEIZE", r;
319 r = ptrace(PTRACE_INTERRUPT, pid, 0L, 0L);
320 return ptrace_attach_cmd = "PTRACE_INTERRUPT", r;
322 return ptrace_attach_cmd = "PTRACE_ATTACH",
323 ptrace(PTRACE_ATTACH, pid, 0L, 0L);
328 * Used when we want to unblock stopped traced process.
329 * Should be only used with PTRACE_CONT, PTRACE_DETACH and PTRACE_SYSCALL.
330 * Returns 0 on success or if error was ESRCH
331 * (presumably process was killed while we talk to it).
332 * Otherwise prints error message and returns -1.
335 ptrace_restart(const unsigned int op, struct tcb *const tcp, unsigned int sig)
341 ptrace(op, tcp->pid, 0L, (unsigned long) sig);
361 * Why curcol != 0? Otherwise sometimes we get this:
363 * 10252 kill(10253, SIGKILL) = 0
364 * <ptrace(SYSCALL,10252):No such process>10253 ...next decode...
366 * 10252 died after we retrieved syscall exit data,
367 * but before we tried to restart it. Log looks ugly.
369 if (current_tcp && current_tcp->curcol != 0) {
370 tprintf(" <ptrace(%s):%s>\n", msg, strerror(err));
376 perror_msg("ptrace(PTRACE_%s,pid:%d,sig:%u)", msg, tcp->pid, sig);
381 set_cloexec_flag(int fd)
385 flags = fcntl(fd, F_GETFD);
387 /* Can happen only if fd is bad.
388 * Should never happen: if it does, we have a bug
389 * in the caller. Therefore we just abort
390 * instead of propagating the error.
392 perror_msg_and_die("fcntl(%d, F_GETFD)", fd);
395 newflags = flags | FD_CLOEXEC;
396 if (flags == newflags)
399 fcntl(fd, F_SETFD, newflags); /* never fails */
403 kill_save_errno(pid_t pid, int sig)
405 int saved_errno = errno;
407 (void) kill(pid, sig);
412 * When strace is setuid executable, we have to swap uids
413 * before and after filesystem and process management operations.
418 int euid = geteuid(), uid = getuid();
420 if (euid != uid && setreuid(euid, uid) < 0) {
421 perror_msg_and_die("setreuid");
425 #ifdef _LARGEFILE64_SOURCE
427 # define fopen_for_output fopen64
429 # define fopen_for_output fopen
431 # define struct_stat struct stat64
432 # define stat_file stat64
433 # define struct_dirent struct dirent64
434 # define read_dir readdir64
435 # define struct_rlimit struct rlimit64
436 # define set_rlimit setrlimit64
438 # define fopen_for_output fopen
439 # define struct_stat struct stat
440 # define stat_file stat
441 # define struct_dirent struct dirent
442 # define read_dir readdir
443 # define struct_rlimit struct rlimit
444 # define set_rlimit setrlimit
448 strace_fopen(const char *path)
453 fp = fopen_for_output(path, "w");
455 perror_msg_and_die("Can't fopen '%s'", path);
457 set_cloexec_flag(fileno(fp));
461 static int popen_pid;
464 # define _PATH_BSHELL "/bin/sh"
468 * We cannot use standard popen(3) here because we have to distinguish
469 * popen child process from other processes we trace, and standard popen(3)
470 * does not export its child's pid.
473 strace_popen(const char *command)
481 perror_msg_and_die("pipe");
483 set_cloexec_flag(fds[1]); /* never fails */
487 perror_msg_and_die("vfork");
494 perror_msg_and_die("dup2");
497 execl(_PATH_BSHELL, "sh", "-c", command, NULL);
498 perror_msg_and_die("Can't execute '%s'", _PATH_BSHELL);
505 fp = fdopen(fds[1], "w");
507 perror_msg_and_die("fdopen");
511 ATTRIBUTE_FORMAT((printf, 1, 0))
513 tvprintf(const char *const fmt, va_list args)
516 int n = vfprintf(current_tcp->outf, fmt, args);
518 /* very unlikely due to vfprintf buffering */
519 if (current_tcp->outf != stderr)
520 perror_msg("%s", outfname);
522 current_tcp->curcol += n;
527 tprintf(const char *fmt, ...)
535 #ifndef HAVE_FPUTS_UNLOCKED
536 # define fputs_unlocked fputs
540 tprints(const char *str)
543 int n = fputs_unlocked(str, current_tcp->outf);
545 current_tcp->curcol += strlen(str);
548 /* very unlikely due to fputs_unlocked buffering */
549 if (current_tcp->outf != stderr)
550 perror_msg("%s", outfname);
555 tprints_comment(const char *const str)
558 tprintf(" /* %s */", str);
562 tprintf_comment(const char *fmt, ...)
576 flush_tcp_output(const struct tcb *const tcp)
578 if (fflush(tcp->outf) && tcp->outf != stderr)
579 perror_msg("%s", outfname);
586 current_tcp->curcol = 0;
587 flush_tcp_output(current_tcp);
590 printing_tcp->curcol = 0;
596 printleader(struct tcb *tcp)
598 /* If -ff, "previous tcb we printed" is always the same as current,
599 * because we have per-tcb output files.
605 current_tcp = printing_tcp;
606 if (printing_tcp->curcol != 0 && (followfork < 2 || printing_tcp == tcp)) {
608 * case 1: we have a shared log (i.e. not -ff), and last line
609 * wasn't finished (same or different tcb, doesn't matter).
610 * case 2: split log, we are the same tcb, but our last line
611 * didn't finish ("SIGKILL nuked us after syscall entry" etc).
613 tprints(" <unfinished ...>\n");
614 printing_tcp->curcol = 0;
620 current_tcp->curcol = 0;
623 tprintf("%-5d ", tcp->pid);
624 else if (nprocs > 1 && !outfname)
625 tprintf("[pid %5u] ", tcp->pid);
628 char str[sizeof("HH:MM:SS")];
629 struct timeval tv, dtv;
630 static struct timeval otv;
632 gettimeofday(&tv, NULL);
636 tv_sub(&dtv, &tv, &otv);
637 tprintf("%6ld.%06ld ",
638 (long) dtv.tv_sec, (long) dtv.tv_usec);
640 } else if (tflag > 2) {
641 tprintf("%ld.%06ld ",
642 (long) tv.tv_sec, (long) tv.tv_usec);
644 time_t local = tv.tv_sec;
645 strftime(str, sizeof(str), "%T", localtime(&local));
647 tprintf("%s.%06ld ", str, (long) tv.tv_usec);
659 if (current_tcp->curcol < acolumn)
660 tprints(acolumn_spaces + current_tcp->curcol);
663 /* Should be only called directly *after successful attach* to a tracee.
664 * Otherwise, "strace -oFILE -ff -p<nonexistant_pid>"
665 * may create bogus empty FILE.<nonexistant_pid>, and then die.
668 newoutf(struct tcb *tcp)
670 tcp->outf = shared_log; /* if not -ff mode, the same file is for all */
671 if (followfork >= 2) {
672 char name[520 + sizeof(int) * 3];
673 sprintf(name, "%.512s.%u", outfname, tcp->pid);
674 tcp->outf = strace_fopen(name);
681 /* Allocate some (more) TCBs (and expand the table).
682 We don't want to relocate the TCBs because our
683 callers have pointers and it would be a pain.
684 So tcbtab is a table of pointers. Since we never
685 free the TCBs, we allocate a single chunk of many. */
686 unsigned int new_tcbtabsize, alloc_tcbtabsize;
690 alloc_tcbtabsize = tcbtabsize;
691 new_tcbtabsize = tcbtabsize * 2;
693 new_tcbtabsize = alloc_tcbtabsize = 1;
696 newtcbs = xcalloc(alloc_tcbtabsize, sizeof(newtcbs[0]));
697 tcbtab = xreallocarray(tcbtab, new_tcbtabsize, sizeof(tcbtab[0]));
698 while (tcbtabsize < new_tcbtabsize)
699 tcbtab[tcbtabsize++] = newtcbs++;
708 if (nprocs == tcbtabsize)
711 for (i = 0; i < tcbtabsize; i++) {
714 memset(tcp, 0, sizeof(*tcp));
716 #if SUPPORTED_PERSONALITIES > 1
717 tcp->currpers = current_personality;
721 if (stack_trace_enabled)
722 unwind_tcb_init(tcp);
727 error_msg("new tcb for pid %d, active tcbs:%d",
732 error_msg_and_die("bug in alloctcb");
736 get_tcb_priv_data(const struct tcb *tcp)
738 return tcp->_priv_data;
742 set_tcb_priv_data(struct tcb *tcp, void *const priv_data,
743 void (*const free_priv_data)(void *))
748 tcp->_free_priv_data = free_priv_data;
749 tcp->_priv_data = priv_data;
755 free_tcb_priv_data(struct tcb *tcp)
757 if (tcp->_priv_data) {
758 if (tcp->_free_priv_data) {
759 tcp->_free_priv_data(tcp->_priv_data);
760 tcp->_free_priv_data = NULL;
762 tcp->_priv_data = NULL;
767 droptcb(struct tcb *tcp)
773 for (p = 0; p < SUPPORTED_PERSONALITIES; ++p)
774 free(tcp->inject_vec[p]);
776 free_tcb_priv_data(tcp);
779 if (stack_trace_enabled) {
786 error_msg("dropped tcb for pid %d, %d remain",
790 if (followfork >= 2) {
791 if (tcp->curcol != 0)
792 fprintf(tcp->outf, " <detached ...>\n");
795 if (printing_tcp == tcp && tcp->curcol != 0)
796 fprintf(tcp->outf, " <detached ...>\n");
797 flush_tcp_output(tcp);
801 if (current_tcp == tcp)
803 if (printing_tcp == tcp)
806 memset(tcp, 0, sizeof(*tcp));
809 /* Detach traced process.
810 * Never call DETACH twice on the same process as both unattached and
811 * attached-unstopped processes give the same ESRCH. For unattached process we
812 * would SIGSTOP it and wait for its SIGSTOP notification forever.
815 detach(struct tcb *tcp)
821 * Linux wrongly insists the child be stopped
822 * before detaching. Arghh. We go through hoops
823 * to make a clean break of things.
826 if (!(tcp->flags & TCB_ATTACHED))
829 /* We attached but possibly didn't see the expected SIGSTOP.
830 * We must catch exactly one as otherwise the detached process
831 * would be left stopped (process state T).
833 if (tcp->flags & TCB_IGNORE_ONE_SIGSTOP)
836 error = ptrace(PTRACE_DETACH, tcp->pid, 0, 0);
838 /* On a clear day, you can see forever. */
841 if (errno != ESRCH) {
842 /* Shouldn't happen. */
843 perror_msg("detach: ptrace(PTRACE_DETACH,%u)", tcp->pid);
846 /* ESRCH: process is either not stopped or doesn't exist. */
847 if (my_tkill(tcp->pid, 0) < 0) {
849 /* Shouldn't happen. */
850 perror_msg("detach: tkill(%u,0)", tcp->pid);
851 /* else: process doesn't exist. */
854 /* Process is not stopped, need to stop it. */
857 * With SEIZE, tracee can be in group-stop already.
858 * In this state sending it another SIGSTOP does nothing.
859 * Need to use INTERRUPT.
860 * Testcase: trying to ^C a "strace -p <stopped_process>".
862 error = ptrace(PTRACE_INTERRUPT, tcp->pid, 0, 0);
866 perror_msg("detach: ptrace(PTRACE_INTERRUPT,%u)", tcp->pid);
868 error = my_tkill(tcp->pid, SIGSTOP);
872 perror_msg("detach: tkill(%u,SIGSTOP)", tcp->pid);
874 /* Either process doesn't exist, or some weird error. */
878 /* We end up here in three cases:
879 * 1. We sent PTRACE_INTERRUPT (use_seize case)
880 * 2. We sent SIGSTOP (!use_seize)
881 * 3. Attach SIGSTOP was already pending (TCB_IGNORE_ONE_SIGSTOP set)
885 if (waitpid(tcp->pid, &status, __WALL) < 0) {
889 * if (errno == ECHILD) break;
890 * ^^^ WRONG! We expect this PID to exist,
891 * and want to emit a message otherwise:
893 perror_msg("detach: waitpid(%u)", tcp->pid);
896 if (!WIFSTOPPED(status)) {
898 * Tracee exited or was killed by signal.
899 * We shouldn't normally reach this place:
900 * we don't want to consume exit status.
901 * Consider "strace -p PID" being ^C-ed:
902 * we want merely to detach from PID.
904 * However, we _can_ end up here if tracee
909 sig = WSTOPSIG(status);
911 error_msg("detach wait: event:%d sig:%d",
912 (unsigned)status >> 16, sig);
914 unsigned event = (unsigned)status >> 16;
915 if (event == PTRACE_EVENT_STOP /*&& sig == SIGTRAP*/) {
917 * sig == SIGTRAP: PTRACE_INTERRUPT stop.
918 * sig == other: process was already stopped
919 * with this stopping sig (see tests/detach-stopped).
920 * Looks like re-injecting this sig is not necessary
921 * in DETACH for the tracee to remain stopped.
926 * PTRACE_INTERRUPT is not guaranteed to produce
927 * the above event if other ptrace-stop is pending.
928 * See tests/detach-sleeping testcase:
929 * strace got SIGINT while tracee is sleeping.
930 * We sent PTRACE_INTERRUPT.
931 * We see syscall exit, not PTRACE_INTERRUPT stop.
932 * We won't get PTRACE_INTERRUPT stop
933 * if we would CONT now. Need to DETACH.
935 if (sig == syscall_trap_sig)
937 /* else: not sure in which case we can be here.
938 * Signal stop? Inject it while detaching.
940 ptrace_restart(PTRACE_DETACH, tcp, sig);
943 /* Note: this check has to be after use_seize check */
944 /* (else, in use_seize case SIGSTOP will be mistreated) */
945 if (sig == SIGSTOP) {
946 /* Detach, suppressing SIGSTOP */
947 ptrace_restart(PTRACE_DETACH, tcp, 0);
950 if (sig == syscall_trap_sig)
952 /* Can't detach just yet, may need to wait for SIGSTOP */
953 error = ptrace_restart(PTRACE_CONT, tcp, sig);
955 /* Should not happen.
956 * Note: ptrace_restart returns 0 on ESRCH, so it's not it.
957 * ptrace_restart already emitted error message.
964 if (!qflag && (tcp->flags & TCB_ATTACHED))
965 error_msg("Process %u detached", tcp->pid);
971 process_opt_p_list(char *opt)
975 * We accept -p PID,PID; -p "`pidof PROG`"; -p "`pgrep PROG`".
976 * pidof uses space as delim, pgrep uses newline. :(
979 char *delim = opt + strcspn(opt, "\n\t ,");
983 pid = string_to_uint(opt);
985 error_msg_and_die("Invalid process id: '%s'", opt);
987 if (pid == strace_tracer_pid) {
988 error_msg_and_die("I'm sorry, I can't let you do that, Dave.");
999 attach_tcb(struct tcb *const tcp)
1001 if (ptrace_attach_or_seize(tcp->pid) < 0) {
1002 perror_msg("attach: ptrace(%s, %d)",
1003 ptrace_attach_cmd, tcp->pid);
1008 tcp->flags |= TCB_ATTACHED | TCB_STARTUP | post_attach_sigstop;
1011 error_msg("attach to pid %d (main) succeeded", tcp->pid);
1013 char procdir[sizeof("/proc/%d/task") + sizeof(int) * 3];
1015 unsigned int ntid = 0, nerr = 0;
1017 if (followfork && tcp->pid != strace_child &&
1018 sprintf(procdir, "/proc/%d/task", tcp->pid) > 0 &&
1019 (dir = opendir(procdir)) != NULL) {
1022 while ((de = read_dir(dir)) != NULL) {
1023 if (de->d_fileno == 0)
1026 int tid = string_to_uint(de->d_name);
1027 if (tid <= 0 || tid == tcp->pid)
1031 if (ptrace_attach_or_seize(tid) < 0) {
1034 perror_msg("attach: ptrace(%s, %d)",
1035 ptrace_attach_cmd, tid);
1039 error_msg("attach to pid %d succeeded", tid);
1041 struct tcb *tid_tcp = alloctcb(tid);
1042 tid_tcp->flags |= TCB_ATTACHED | TCB_STARTUP |
1043 post_attach_sigstop;
1052 error_msg("Process %u attached"
1054 tcp->pid, ntid - nerr + 1);
1056 error_msg("Process %u attached",
1062 startup_attach(void)
1064 pid_t parent_pid = strace_tracer_pid;
1069 * Block user interruptions as we would leave the traced
1070 * process stopped (process state T) if we would terminate in
1071 * between PTRACE_ATTACH and wait4() on SIGSTOP.
1072 * We rely on cleanup() from this point on.
1075 sigprocmask(SIG_SETMASK, &blocked_set, NULL);
1077 if (daemonized_tracer) {
1080 perror_msg_and_die("fork");
1082 if (pid) { /* parent */
1084 * Wait for grandchild to attach to straced process
1085 * (grandparent). Grandchild SIGKILLs us after it attached.
1086 * Grandparent's wait() is unblocked by our death,
1087 * it proceeds to exec the straced program.
1090 _exit(0); /* paranoia */
1093 /* We will be the tracer process. Remember our new pid: */
1094 strace_tracer_pid = getpid();
1097 for (tcbi = 0; tcbi < tcbtabsize; tcbi++) {
1103 /* Is this a process we should attach to, but not yet attached? */
1104 if (tcp->flags & TCB_ATTACHED)
1105 continue; /* no, we already attached it */
1107 if (tcp->pid == parent_pid || tcp->pid == strace_tracer_pid) {
1109 perror_msg("attach: pid %d", tcp->pid);
1117 sigprocmask(SIG_SETMASK, &start_set, NULL);
1120 sigprocmask(SIG_SETMASK, &blocked_set, NULL);
1122 } /* for each tcbtab[] */
1124 if (daemonized_tracer) {
1126 * Make parent go away.
1127 * Also makes grandparent's wait() unblock.
1129 kill(parent_pid, SIGKILL);
1135 sigprocmask(SIG_SETMASK, &start_set, NULL);
1138 /* Stack-o-phobic exec helper, in the hope to work around
1139 * NOMMU + "daemonized tracer" difficulty.
1141 struct exec_params {
1147 struct sigaction child_sa;
1149 static struct exec_params params_for_tracee;
1151 static void ATTRIBUTE_NOINLINE ATTRIBUTE_NORETURN
1154 struct exec_params *params = ¶ms_for_tracee;
1156 if (params->fd_to_close >= 0)
1157 close(params->fd_to_close);
1158 if (!daemonized_tracer && !use_seize) {
1159 if (ptrace(PTRACE_TRACEME, 0L, 0L, 0L) < 0) {
1160 perror_msg_and_die("ptrace(PTRACE_TRACEME, ...)");
1164 if (username != NULL) {
1166 * It is important to set groups before we
1167 * lose privileges on setuid.
1169 if (initgroups(username, run_gid) < 0) {
1170 perror_msg_and_die("initgroups");
1172 if (setregid(run_gid, params->run_egid) < 0) {
1173 perror_msg_and_die("setregid");
1175 if (setreuid(run_uid, params->run_euid) < 0) {
1176 perror_msg_and_die("setreuid");
1178 } else if (geteuid() != 0)
1179 if (setreuid(run_uid, run_uid) < 0) {
1180 perror_msg_and_die("setreuid");
1183 if (!daemonized_tracer) {
1185 * Induce a ptrace stop. Tracer (our parent)
1186 * will resume us with PTRACE_SYSCALL and display
1187 * the immediately following execve syscall.
1188 * Can't do this on NOMMU systems, we are after
1189 * vfork: parent is blocked, stopping would deadlock.
1192 kill(getpid(), SIGSTOP);
1195 /* we depend on SIGCHLD set to SIG_DFL by init code */
1196 /* if it happens to be SIG_IGN'ed, wait won't block */
1201 if (params_for_tracee.child_sa.sa_handler != SIG_DFL)
1202 sigaction(SIGCHLD, ¶ms_for_tracee.child_sa, NULL);
1204 execv(params->pathname, params->argv);
1205 perror_msg_and_die("exec");
1209 * Open a dummy descriptor for use as a placeholder.
1210 * The descriptor is O_RDONLY with FD_CLOEXEC flag set.
1211 * A read attempt from such descriptor ends with EOF,
1212 * a write attempt is rejected with EBADF.
1215 open_dummy_desc(void)
1220 perror_msg_and_die("pipe");
1222 set_cloexec_flag(fds[0]);
1226 /* placeholder fds status for stdin and stdout */
1227 static bool fd_is_placeholder[2];
1230 * Ensure that all standard file descriptors are open by opening placeholder
1231 * file descriptors for those standard file descriptors that are not open.
1233 * The information which descriptors have been made open is saved
1234 * in fd_is_placeholder for later use.
1237 ensure_standard_fds_opened(void)
1241 while ((fd = open_dummy_desc()) <= 2) {
1244 fd_is_placeholder[fd] = true;
1252 * Redirect stdin and stdout unless they have been opened earlier
1253 * by ensure_standard_fds_opened as placeholders.
1256 redirect_standard_fds(void)
1261 * It might be a good idea to redirect stderr as well,
1262 * but we sometimes need to print error messages.
1264 for (i = 0; i <= 1; ++i) {
1265 if (!fd_is_placeholder[i]) {
1273 startup_child(char **argv)
1275 struct_stat statbuf;
1276 const char *filename;
1277 size_t filename_len;
1278 char pathname[PATH_MAX];
1283 filename_len = strlen(filename);
1285 if (filename_len > sizeof(pathname) - 1) {
1286 errno = ENAMETOOLONG;
1287 perror_msg_and_die("exec");
1289 if (strchr(filename, '/')) {
1290 strcpy(pathname, filename);
1292 #ifdef USE_DEBUGGING_EXEC
1294 * Debuggers customarily check the current directory
1295 * first regardless of the path but doing that gives
1296 * security geeks a panic attack.
1298 else if (stat_file(filename, &statbuf) == 0)
1299 strcpy(pathname, filename);
1300 #endif /* USE_DEBUGGING_EXEC */
1305 for (path = getenv("PATH"); path && *path; path += m) {
1306 const char *colon = strchr(path, ':');
1311 m = n = strlen(path);
1313 if (!getcwd(pathname, PATH_MAX))
1315 len = strlen(pathname);
1316 } else if (n > sizeof(pathname) - 1)
1319 strncpy(pathname, path, n);
1322 if (len && pathname[len - 1] != '/')
1323 pathname[len++] = '/';
1324 if (filename_len + len > sizeof(pathname) - 1)
1326 strcpy(pathname + len, filename);
1327 if (stat_file(pathname, &statbuf) == 0 &&
1328 /* Accept only regular files
1329 with some execute bits set.
1330 XXX not perfect, might still fail */
1331 S_ISREG(statbuf.st_mode) &&
1332 (statbuf.st_mode & 0111))
1335 if (!path || !*path)
1338 if (stat_file(pathname, &statbuf) < 0) {
1339 perror_msg_and_die("Can't stat '%s'", filename);
1342 params_for_tracee.fd_to_close = (shared_log != stderr) ? fileno(shared_log) : -1;
1343 params_for_tracee.run_euid = (statbuf.st_mode & S_ISUID) ? statbuf.st_uid : run_uid;
1344 params_for_tracee.run_egid = (statbuf.st_mode & S_ISGID) ? statbuf.st_gid : run_gid;
1345 params_for_tracee.argv = argv;
1347 * On NOMMU, can be safely freed only after execve in tracee.
1348 * It's hard to know when that happens, so we just leak it.
1350 params_for_tracee.pathname = NOMMU_SYSTEM ? xstrdup(pathname) : pathname;
1352 #if defined HAVE_PRCTL && defined PR_SET_PTRACER && defined PR_SET_PTRACER_ANY
1353 if (daemonized_tracer)
1354 prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY);
1359 perror_msg_and_die("fork");
1361 if ((pid != 0 && daemonized_tracer)
1362 || (pid == 0 && !daemonized_tracer)
1364 /* We are to become the tracee. Two cases:
1366 * not -D: we are child
1371 /* We are the tracer */
1373 if (!daemonized_tracer) {
1376 /* child did PTRACE_TRACEME, nothing to do in parent */
1378 if (!NOMMU_SYSTEM) {
1379 /* Wait until child stopped itself */
1381 while (waitpid(pid, &status, WSTOPPED) < 0) {
1384 perror_msg_and_die("waitpid");
1386 if (!WIFSTOPPED(status) || WSTOPSIG(status) != SIGSTOP) {
1387 kill_save_errno(pid, SIGKILL);
1388 perror_msg_and_die("Unexpected wait status %#x",
1392 /* Else: NOMMU case, we have no way to sync.
1393 * Just attach to it as soon as possible.
1394 * This means that we may miss a few first syscalls...
1397 if (ptrace_attach_or_seize(pid)) {
1398 kill_save_errno(pid, SIGKILL);
1399 perror_msg_and_die("attach: ptrace(%s, %d)",
1400 ptrace_attach_cmd, pid);
1405 tcp = alloctcb(pid);
1406 tcp->flags |= TCB_ATTACHED | TCB_STARTUP
1407 | TCB_SKIP_DETACH_ON_FIRST_EXEC
1408 | (NOMMU_SYSTEM ? 0 : (TCB_HIDE_LOG | post_attach_sigstop));
1411 /* With -D, we are *child* here, the tracee is our parent. */
1412 strace_child = strace_tracer_pid;
1413 strace_tracer_pid = getpid();
1414 tcp = alloctcb(strace_child);
1415 tcp->flags |= TCB_SKIP_DETACH_ON_FIRST_EXEC | TCB_HIDE_LOG;
1416 /* attaching will be done later, by startup_attach */
1417 /* note: we don't do newoutf(tcp) here either! */
1419 /* NOMMU BUG! -D mode is active, we (child) return,
1420 * and we will scribble over parent's stack!
1421 * When parent later unpauses, it segfaults.
1424 * (1) by declaring exec_or_die() NORETURN,
1425 * hopefully compiler will just jump to it
1426 * instead of call (won't push anything to stack),
1427 * (2) by trying very hard in exec_or_die()
1428 * to not use any stack,
1429 * (3) having a really big (PATH_MAX) stack object
1430 * in this function, which creates a "buffer" between
1431 * child's and parent's stack pointers.
1432 * This may save us if (1) and (2) failed
1433 * and compiler decided to use stack in exec_or_die() anyway
1434 * (happens on i386 because of stack parameter passing).
1436 * A cleaner solution is to use makecontext + setcontext
1437 * to create a genuine separate stack and execute on it.
1441 * A case where straced process is part of a pipe:
1442 * { sleep 1; yes | head -n99999; } | strace -o/dev/null sh -c 'exec <&-; sleep 9'
1443 * If strace won't close its fd#0, closing it in tracee is not enough:
1444 * the pipe is still open, it has a reader. Thus, "head" will not get its
1445 * SIGPIPE at once, on the first write.
1447 * Preventing it by redirecting strace's stdin/out.
1448 * (Don't leave fds 0 and 1 closed, this is bad practice: future opens
1449 * will reuse them, unexpectedly making a newly opened object "stdin").
1451 redirect_standard_fds();
1456 test_ptrace_seize(void)
1460 /* Need fork for test. NOMMU has no forks */
1462 post_attach_sigstop = 0; /* this sets use_seize to 1 */
1468 perror_msg_and_die("fork");
1475 /* PTRACE_SEIZE, unlike ATTACH, doesn't force tracee to trap. After
1476 * attaching tracee continues to run unless a trap condition occurs.
1477 * PTRACE_SEIZE doesn't affect signal or group stop state.
1479 if (ptrace(PTRACE_SEIZE, pid, 0, 0) == 0) {
1480 post_attach_sigstop = 0; /* this sets use_seize to 1 */
1481 } else if (debug_flag) {
1482 error_msg("PTRACE_SEIZE doesn't work");
1488 int status, tracee_pid;
1491 tracee_pid = waitpid(pid, &status, 0);
1492 if (tracee_pid <= 0) {
1495 perror_msg_and_die("%s: unexpected wait result %d",
1496 __func__, tracee_pid);
1498 if (WIFSIGNALED(status)) {
1501 error_msg_and_die("%s: unexpected wait status %#x",
1505 #else /* !USE_SEIZE */
1506 # define test_ptrace_seize() ((void)0)
1510 get_os_release(void)
1516 perror_msg_and_die("uname");
1517 /* u.release has this form: "3.2.9[-some-garbage]" */
1521 if (!(*p >= '0' && *p <= '9'))
1522 error_msg_and_die("Bad OS release string: '%s'", u.release);
1523 /* Note: this open-codes KERNEL_VERSION(): */
1524 rel = (rel << 8) | atoi(p);
1525 if (rel >= KERNEL_VERSION(1, 0, 0))
1527 while (*p >= '0' && *p <= '9')
1530 if (rel >= KERNEL_VERSION(0, 1, 0)) {
1531 /* "X.Y-something" means "X.Y.0" */
1535 error_msg_and_die("Bad OS release string: '%s'", u.release);
1543 set_sigaction(int signo, void (*sighandler)(int), struct sigaction *oldact)
1545 /* if signal handler is a function, add the signal to blocked_set */
1546 if (sighandler != SIG_IGN && sighandler != SIG_DFL)
1547 sigaddset(&blocked_set, signo);
1549 const struct sigaction sa = { .sa_handler = sighandler };
1550 sigaction(signo, &sa, oldact);
1554 * Initialization part of main() was eating much stack (~0.5k),
1555 * which was unused after init.
1556 * We can reuse it if we move init code into a separate function.
1558 * Don't want main() to inline us and defeat the reason
1559 * we have a separate function.
1561 static void ATTRIBUTE_NOINLINE
1562 init(int argc, char *argv[])
1567 if (!program_invocation_name || !*program_invocation_name) {
1568 static char name[] = "strace";
1569 program_invocation_name =
1570 (argv[0] && *argv[0]) ? argv[0] : name;
1573 strace_tracer_pid = getpid();
1575 os_release = get_os_release();
1577 shared_log = stderr;
1578 set_sortby(DEFAULT_SORTBY);
1579 set_personality(DEFAULT_PERSONALITY);
1580 qualify("trace=all");
1581 qualify("abbrev=all");
1582 qualify("verbose=all");
1583 #if DEFAULT_QUAL_FLAGS != (QUAL_TRACE | QUAL_ABBREV | QUAL_VERBOSE)
1584 # error Bug in DEFAULT_QUAL_FLAGS
1586 qualify("signal=all");
1587 while ((c = getopt(argc, argv,
1588 "+b:cCdfFhiqrtTvVwxyz"
1589 #ifdef USE_LIBUNWIND
1593 "a:e:o:O:p:s:S:u:E:P:I:")) != EOF) {
1596 if (strcmp(optarg, "execve") != 0)
1597 error_msg_and_die("Syscall '%s' for -b isn't supported",
1599 detach_on_execve = 1;
1602 if (cflag == CFLAG_BOTH) {
1603 error_msg_and_help("-c and -C are mutually exclusive");
1605 cflag = CFLAG_ONLY_STATS;
1608 if (cflag == CFLAG_ONLY_STATS) {
1609 error_msg_and_help("-c and -C are mutually exclusive");
1617 daemonized_tracer = 1;
1644 count_wallclock = 1;
1653 qualify("abbrev=none");
1660 not_failing_only = 1;
1663 acolumn = string_to_uint(optarg);
1665 error_opt_arg(c, optarg);
1674 i = string_to_uint(optarg);
1676 error_opt_arg(c, optarg);
1680 process_opt_p_list(optarg);
1683 pathtrace_select(optarg);
1686 i = string_to_uint(optarg);
1687 if (i < 0 || (unsigned int) i > -1U / 4)
1688 error_opt_arg(c, optarg);
1697 #ifdef USE_LIBUNWIND
1699 stack_trace_enabled = true;
1703 if (putenv(optarg) < 0)
1704 perror_msg_and_die("putenv");
1707 opt_intr = string_to_uint_upto(optarg, NUM_INTR_OPTS - 1);
1709 error_opt_arg(c, optarg);
1712 error_msg_and_help(NULL);
1720 if (argc < 0 || (!argv[0] && !nprocs)) {
1721 error_msg_and_help("must have PROG [ARGS] or -p PID");
1724 if (!argv[0] && daemonized_tracer) {
1725 error_msg_and_help("PROG [ARGS] must be specified with -D");
1731 if (followfork >= 2 && cflag) {
1732 error_msg_and_help("(-c or -C) and -ff are mutually exclusive");
1735 if (count_wallclock && !cflag) {
1736 error_msg_and_help("-w must be given with (-c or -C)");
1739 if (cflag == CFLAG_ONLY_STATS) {
1741 error_msg("-%c has no effect with -c", 'i');
1742 #ifdef USE_LIBUNWIND
1743 if (stack_trace_enabled)
1744 error_msg("-%c has no effect with -c", 'k');
1747 error_msg("-%c has no effect with -c", 'r');
1749 error_msg("-%c has no effect with -c", 't');
1751 error_msg("-%c has no effect with -c", 'T');
1753 error_msg("-%c has no effect with -c", 'y');
1758 error_msg("-tt has no effect with -r");
1762 acolumn_spaces = xmalloc(acolumn + 1);
1763 memset(acolumn_spaces, ' ', acolumn);
1764 acolumn_spaces[acolumn] = '\0';
1766 sigprocmask(SIG_SETMASK, NULL, &start_set);
1767 memcpy(&blocked_set, &start_set, sizeof(blocked_set));
1769 set_sigaction(SIGCHLD, SIG_DFL, ¶ms_for_tracee.child_sa);
1771 #ifdef USE_LIBUNWIND
1772 if (stack_trace_enabled) {
1776 for (tcbi = 0; tcbi < tcbtabsize; ++tcbi) {
1777 unwind_tcb_init(tcbtab[tcbi]);
1782 /* See if they want to run as another user. */
1783 if (username != NULL) {
1784 struct passwd *pent;
1786 if (getuid() != 0 || geteuid() != 0) {
1787 error_msg_and_die("You must be root to use the -u option");
1789 pent = getpwnam(username);
1791 error_msg_and_die("Cannot find user '%s'", username);
1793 run_uid = pent->pw_uid;
1794 run_gid = pent->pw_gid;
1801 ptrace_setoptions |= PTRACE_O_TRACECLONE |
1802 PTRACE_O_TRACEFORK |
1803 PTRACE_O_TRACEVFORK;
1805 error_msg("ptrace_setoptions = %#x", ptrace_setoptions);
1806 test_ptrace_seize();
1809 * Is something weird with our stdin and/or stdout -
1810 * for example, may they be not open? In this case,
1811 * ensure that none of the future opens uses them.
1813 * This was seen in the wild when /proc/sys/kernel/core_pattern
1814 * was set to "|/bin/strace -o/tmp/LOG PROG":
1815 * kernel runs coredump helper with fd#0 open but fd#1 closed (!),
1816 * therefore LOG gets opened to fd#1, and fd#1 is closed by
1817 * "don't hold up stdin/out open" code soon after.
1819 ensure_standard_fds_opened();
1821 /* Check if they want to redirect the output. */
1823 /* See if they want to pipe the output. */
1824 if (outfname[0] == '|' || outfname[0] == '!') {
1826 * We can't do the <outfname>.PID funny business
1827 * when using popen, so prohibit it.
1829 if (followfork >= 2)
1830 error_msg_and_help("piping the output and -ff are mutually exclusive");
1831 shared_log = strace_popen(outfname + 1);
1832 } else if (followfork < 2)
1833 shared_log = strace_fopen(outfname);
1835 /* -ff without -o FILE is the same as single -f */
1836 if (followfork >= 2)
1840 if (!outfname || outfname[0] == '|' || outfname[0] == '!') {
1841 setvbuf(shared_log, NULL, _IOLBF, 0);
1845 * argv[0] -pPID -oFILE Default interactive setting
1846 * yes * 0 INTR_WHILE_WAIT
1847 * no 1 0 INTR_WHILE_WAIT
1848 * yes * 1 INTR_NEVER
1849 * no 1 1 INTR_WHILE_WAIT
1852 if (outfname && argv[0]) {
1854 opt_intr = INTR_NEVER;
1859 opt_intr = INTR_WHILE_WAIT;
1862 * startup_child() must be called before the signal handlers get
1863 * installed below as they are inherited into the spawned process.
1864 * Also we do not need to be protected by them as during interruption
1865 * in the startup_child() mode we kill the spawned process anyway.
1868 startup_child(argv);
1871 set_sigaction(SIGTTOU, SIG_IGN, NULL);
1872 set_sigaction(SIGTTIN, SIG_IGN, NULL);
1873 if (opt_intr != INTR_ANYWHERE) {
1874 if (opt_intr == INTR_BLOCK_TSTP_TOO)
1875 set_sigaction(SIGTSTP, SIG_IGN, NULL);
1877 * In interactive mode (if no -o OUTFILE, or -p PID is used),
1878 * fatal signals are blocked while syscall stop is processed,
1879 * and acted on in between, when waiting for new syscall stops.
1880 * In non-interactive mode, signals are ignored.
1882 set_sigaction(SIGHUP, interactive ? interrupt : SIG_IGN, NULL);
1883 set_sigaction(SIGINT, interactive ? interrupt : SIG_IGN, NULL);
1884 set_sigaction(SIGQUIT, interactive ? interrupt : SIG_IGN, NULL);
1885 set_sigaction(SIGPIPE, interactive ? interrupt : SIG_IGN, NULL);
1886 set_sigaction(SIGTERM, interactive ? interrupt : SIG_IGN, NULL);
1889 if (nprocs != 0 || daemonized_tracer)
1892 /* Do we want pids printed in our -o OUTFILE?
1893 * -ff: no (every pid has its own file); or
1894 * -f: yes (there can be more pids in the future); or
1895 * -p PID1,PID2: yes (there are already more than one pid)
1897 print_pid_pfx = (outfname && followfork < 2 && (followfork == 1 || nprocs > 1));
1908 for (i = 0; i < tcbtabsize; i++) {
1909 struct tcb *tcp = tcbtab[i];
1910 if (tcp->pid == pid)
1924 /* 'interrupted' is a volatile object, fetch it only once */
1925 fatal_sig = interrupted;
1927 fatal_sig = SIGTERM;
1929 for (i = 0; i < tcbtabsize; i++) {
1934 error_msg("cleanup: looking at pid %u", tcp->pid);
1935 if (tcp->pid == strace_child) {
1936 kill(tcp->pid, SIGCONT);
1937 kill(tcp->pid, fatal_sig);
1942 call_summary(shared_log);
1952 print_debug_info(const int pid, int status)
1954 const unsigned int event = (unsigned int) status >> 16;
1955 char buf[sizeof("WIFEXITED,exitcode=%u") + sizeof(int)*3 /*paranoia:*/ + 16];
1956 char evbuf[sizeof(",EVENT_VFORK_DONE (%u)") + sizeof(int)*3 /*paranoia:*/ + 16];
1959 if (WIFSIGNALED(status))
1961 sprintf(buf, "WIFSIGNALED,%ssig=%s",
1962 WCOREDUMP(status) ? "core," : "",
1963 signame(WTERMSIG(status)));
1965 sprintf(buf, "WIFSIGNALED,sig=%s",
1966 signame(WTERMSIG(status)));
1968 if (WIFEXITED(status))
1969 sprintf(buf, "WIFEXITED,exitcode=%u", WEXITSTATUS(status));
1970 if (WIFSTOPPED(status))
1971 sprintf(buf, "WIFSTOPPED,sig=%s", signame(WSTOPSIG(status)));
1974 static const char *const event_names[] = {
1975 [PTRACE_EVENT_CLONE] = "CLONE",
1976 [PTRACE_EVENT_FORK] = "FORK",
1977 [PTRACE_EVENT_VFORK] = "VFORK",
1978 [PTRACE_EVENT_VFORK_DONE] = "VFORK_DONE",
1979 [PTRACE_EVENT_EXEC] = "EXEC",
1980 [PTRACE_EVENT_EXIT] = "EXIT",
1981 /* [PTRACE_EVENT_STOP (=128)] would make biggish array */
1983 const char *e = "??";
1984 if (event < ARRAY_SIZE(event_names))
1985 e = event_names[event];
1986 else if (event == PTRACE_EVENT_STOP)
1988 sprintf(evbuf, ",EVENT_%s (%u)", e, event);
1990 error_msg("[wait(0x%06x) = %u] %s%s", status, pid, buf, evbuf);
1994 maybe_allocate_tcb(const int pid, int status)
1996 if (!WIFSTOPPED(status)) {
1997 if (detach_on_execve && pid == strace_child) {
1998 /* example: strace -bexecve sh -c 'exec true' */
2003 * This can happen if we inherited an unknown child.
2004 * Example: (sleep 1 & exec strace true)
2006 error_msg("Exit of unknown pid %u ignored", pid);
2010 /* We assume it's a fork/vfork/clone child */
2011 struct tcb *tcp = alloctcb(pid);
2012 tcp->flags |= TCB_ATTACHED | TCB_STARTUP | post_attach_sigstop;
2015 error_msg("Process %d attached", pid);
2019 * This can happen if a clone call misused CLONE_PTRACE itself.
2021 * There used to be a dance around possible re-injection of
2022 * WSTOPSIG(status), but it was later removed as the only
2023 * observable stop here is the initial ptrace-stop.
2025 ptrace(PTRACE_DETACH, pid, NULL, 0L);
2026 error_msg("Detached unknown pid %d", pid);
2032 maybe_switch_tcbs(struct tcb *tcp, const int pid)
2035 struct tcb *execve_thread;
2038 if (ptrace(PTRACE_GETEVENTMSG, pid, NULL, &old_pid) < 0)
2040 /* Avoid truncation in pid2tcb() param passing */
2041 if (old_pid <= 0 || old_pid == pid)
2043 if ((unsigned long) old_pid > UINT_MAX)
2045 execve_thread = pid2tcb(old_pid);
2046 /* It should be !NULL, but I feel paranoid */
2050 if (execve_thread->curcol != 0) {
2052 * One case we are here is -ff:
2053 * try "strace -oLOG -ff test/threaded_execve"
2055 fprintf(execve_thread->outf, " <pid changed to %d ...>\n", pid);
2056 /*execve_thread->curcol = 0; - no need, see code below */
2058 /* Swap output FILEs (needed for -ff) */
2059 fp = execve_thread->outf;
2060 execve_thread->outf = tcp->outf;
2062 /* And their column positions */
2063 execve_thread->curcol = tcp->curcol;
2065 /* Drop leader, but close execve'd thread outfile (if -ff) */
2067 /* Switch to the thread, reusing leader's outfile and pid */
2068 tcp = execve_thread;
2070 if (cflag != CFLAG_ONLY_STATS) {
2072 tprintf("+++ superseded by execve in pid %lu +++\n", old_pid);
2074 tcp->flags |= TCB_REPRINT;
2081 print_signalled(struct tcb *tcp, const int pid, int status)
2083 if (pid == strace_child) {
2084 exit_code = 0x100 | WTERMSIG(status);
2088 if (cflag != CFLAG_ONLY_STATS
2089 && is_number_in_set(WTERMSIG(status), signal_set)) {
2092 tprintf("+++ killed by %s %s+++\n",
2093 signame(WTERMSIG(status)),
2094 WCOREDUMP(status) ? "(core dumped) " : "");
2096 tprintf("+++ killed by %s +++\n",
2097 signame(WTERMSIG(status)));
2104 print_exited(struct tcb *tcp, const int pid, int status)
2106 if (pid == strace_child) {
2107 exit_code = WEXITSTATUS(status);
2111 if (cflag != CFLAG_ONLY_STATS &&
2114 tprintf("+++ exited with %d +++\n", WEXITSTATUS(status));
2120 print_stopped(struct tcb *tcp, const siginfo_t *si, const unsigned int sig)
2122 if (cflag != CFLAG_ONLY_STATS
2124 && is_number_in_set(sig, signal_set)) {
2127 tprintf("--- %s ", signame(sig));
2131 tprintf("--- stopped by %s ---\n", signame(sig));
2137 startup_tcb(struct tcb *tcp)
2140 error_msg("pid %d has TCB_STARTUP, initializing it", tcp->pid);
2142 tcp->flags &= ~TCB_STARTUP;
2146 error_msg("setting opts 0x%x on pid %d",
2147 ptrace_setoptions, tcp->pid);
2148 if (ptrace(PTRACE_SETOPTIONS, tcp->pid, NULL, ptrace_setoptions) < 0) {
2149 if (errno != ESRCH) {
2150 /* Should never happen, really */
2151 perror_msg_and_die("PTRACE_SETOPTIONS");
2156 if (get_scno(tcp) == 1)
2157 tcp->s_prev_ent = tcp->s_ent;
2161 print_event_exit(struct tcb *tcp)
2163 if (entering(tcp) || filtered(tcp) || hide_log(tcp)
2164 || cflag == CFLAG_ONLY_STATS) {
2168 if (followfork < 2 && printing_tcp && printing_tcp != tcp
2169 && printing_tcp->curcol != 0) {
2170 current_tcp = printing_tcp;
2171 tprints(" <unfinished ...>\n");
2172 flush_tcp_output(printing_tcp);
2173 printing_tcp->curcol = 0;
2177 if ((followfork < 2 && printing_tcp != tcp)
2178 || (tcp->flags & TCB_REPRINT)) {
2179 tcp->flags &= ~TCB_REPRINT;
2181 tprintf("<... %s resumed>", tcp->s_ent->sys_name);
2184 if (!(tcp->sys_func_rval & RVAL_DECODED)) {
2186 * The decoder has probably decided to print something
2187 * on exiting syscall which is not going to happen.
2189 tprints(" <unfinished ...>");
2198 /* Break the main loop. */
2201 /* Call next_event() again. */
2204 /* Restart the tracee with signal 0 and call next_event() again. */
2208 * For all the events below, current_tcp is set to current tracee's
2209 * tcb. All the suggested actions imply that you want to continue
2210 * tracing of the current tracee; alternatively, you can detach it.
2214 * Syscall entry or exit.
2215 * Restart the tracee with signal 0, or with an injected signal number.
2220 * Tracee received signal with number WSTOPSIG(*pstatus); signal info
2221 * is written to *si. Restart the tracee (with that signal number
2222 * if you want to deliver it).
2224 TE_SIGNAL_DELIVERY_STOP,
2227 * Tracee was killed by a signal with number WTERMSIG(*pstatus).
2232 * Tracee was stopped by a signal with number WSTOPSIG(*pstatus).
2233 * Restart the tracee with that signal number.
2238 * Tracee exited with status WEXITSTATUS(*pstatus).
2243 * Tracee is going to perform execve().
2244 * Restart the tracee with signal 0.
2246 TE_STOP_BEFORE_EXECVE,
2249 * Tracee is going to terminate.
2250 * Restart the tracee with signal 0.
2252 TE_STOP_BEFORE_EXIT,
2255 static enum trace_event
2256 next_event(int *pstatus, siginfo_t *si)
2268 * Used to exit simply when nprocs hits zero, but in this testcase:
2269 * int main(void) { _exit(!!fork()); }
2270 * under strace -f, parent sometimes (rarely) manages
2271 * to exit before we see the first stop of the child,
2272 * and we are losing track of it:
2273 * 19923 clone(...) = 19924
2274 * 19923 exit_group(1) = ?
2275 * 19923 +++ exited with 1 +++
2276 * Exiting only when wait() returns ECHILD works better.
2278 if (popen_pid != 0) {
2279 /* However, if -o|logger is in use, we can't do that.
2280 * Can work around that by double-forking the logger,
2281 * but that loses the ability to wait for its completion
2282 * on exit. Oh well...
2289 sigprocmask(SIG_SETMASK, &start_set, NULL);
2290 pid = wait4(-1, pstatus, __WALL, (cflag ? &ru : NULL));
2293 sigprocmask(SIG_SETMASK, &blocked_set, NULL);
2296 if (wait_errno == EINTR)
2298 if (nprocs == 0 && wait_errno == ECHILD)
2301 * If nprocs > 0, ECHILD is not expected,
2302 * treat it as any other error here:
2305 perror_msg_and_die("wait4(__WALL)");
2310 if (pid == popen_pid) {
2311 if (!WIFSTOPPED(status))
2317 print_debug_info(pid, status);
2319 /* Look up 'pid' in our table. */
2323 tcp = maybe_allocate_tcb(pid, status);
2330 /* Set current output file */
2334 tv_sub(&tcp->dtime, &ru.ru_stime, &tcp->stime);
2335 tcp->stime = ru.ru_stime;
2338 if (WIFSIGNALED(status))
2339 return TE_SIGNALLED;
2341 if (WIFEXITED(status))
2345 * As WCONTINUED flag has not been specified to wait4,
2346 * it cannot be WIFCONTINUED(status), so the only case
2347 * that remains is WIFSTOPPED(status).
2350 /* Is this the very first time we see this tracee stopped? */
2351 if (tcp->flags & TCB_STARTUP)
2354 const unsigned int sig = WSTOPSIG(status);
2355 const unsigned int event = (unsigned int) status >> 16;
2360 * Is this post-attach SIGSTOP?
2361 * Interestingly, the process may stop
2362 * with STOPSIG equal to some other signal
2363 * than SIGSTOP if we happened to attach
2364 * just before the process takes a signal.
2366 if (sig == SIGSTOP && (tcp->flags & TCB_IGNORE_ONE_SIGSTOP)) {
2368 error_msg("ignored SIGSTOP on pid %d", tcp->pid);
2369 tcp->flags &= ~TCB_IGNORE_ONE_SIGSTOP;
2371 } else if (sig == syscall_trap_sig) {
2372 return TE_SYSCALL_STOP;
2374 *si = (siginfo_t) {};
2376 * True if tracee is stopped by signal
2377 * (as opposed to "tracee received signal").
2378 * TODO: shouldn't we check for errno == EINVAL too?
2379 * We can get ESRCH instead, you know...
2381 bool stopped = ptrace(PTRACE_GETSIGINFO, pid, 0, si) < 0;
2382 return stopped ? TE_GROUP_STOP : TE_SIGNAL_DELIVERY_STOP;
2386 case PTRACE_EVENT_STOP:
2388 * PTRACE_INTERRUPT-stop or group-stop.
2389 * PTRACE_INTERRUPT-stop has sig == SIGTRAP here.
2396 return TE_GROUP_STOP;
2400 case PTRACE_EVENT_EXEC:
2401 return TE_STOP_BEFORE_EXECVE;
2402 case PTRACE_EVENT_EXIT:
2403 return TE_STOP_BEFORE_EXIT;
2410 trace_syscall(struct tcb *tcp, unsigned int *sig)
2412 if (entering(tcp)) {
2413 int res = syscall_entering_decode(tcp);
2418 res = syscall_entering_trace(tcp, sig);
2420 syscall_entering_finish(tcp, res);
2423 struct timeval tv = {};
2424 int res = syscall_exiting_decode(tcp, &tv);
2426 res = syscall_exiting_trace(tcp, tv, res);
2428 syscall_exiting_finish(tcp);
2433 /* Returns true iff the main trace loop has to continue. */
2435 dispatch_event(enum trace_event ret, int *pstatus, siginfo_t *si)
2437 unsigned int restart_op = PTRACE_SYSCALL;
2438 unsigned int restart_sig = 0;
2450 case TE_SYSCALL_STOP:
2451 if (trace_syscall(current_tcp, &restart_sig) < 0) {
2453 * ptrace() failed in trace_syscall().
2454 * Likely a result of process disappearing mid-flight.
2455 * Observed case: exit_group() or SIGKILL terminating
2456 * all processes in thread group.
2457 * We assume that ptrace error was caused by process death.
2458 * We used to detach(current_tcp) here, but since we no
2459 * longer implement "detach before death" policy/hack,
2460 * we can let this process to report its death to us
2461 * normally, via WIFEXITED or WIFSIGNALED wait status.
2467 case TE_SIGNAL_DELIVERY_STOP:
2468 restart_sig = WSTOPSIG(*pstatus);
2469 print_stopped(current_tcp, si, restart_sig);
2473 print_signalled(current_tcp, current_tcp->pid, *pstatus);
2474 droptcb(current_tcp);
2478 restart_sig = WSTOPSIG(*pstatus);
2479 print_stopped(current_tcp, NULL, restart_sig);
2482 * This ends ptrace-stop, but does *not* end group-stop.
2483 * This makes stopping signals work properly on straced
2484 * process (that is, process really stops. It used to
2487 restart_op = PTRACE_LISTEN;
2493 print_exited(current_tcp, current_tcp->pid, *pstatus);
2494 droptcb(current_tcp);
2497 case TE_STOP_BEFORE_EXECVE:
2499 * Under Linux, execve changes pid to thread leader's pid,
2500 * and we see this changed pid on EVENT_EXEC and later,
2501 * execve sysexit. Leader "disappears" without exit
2502 * notification. Let user know that, drop leader's tcb,
2503 * and fix up pid in execve thread's tcb.
2504 * Effectively, execve thread's tcb replaces leader's tcb.
2506 * BTW, leader is 'stuck undead' (doesn't report WIFEXITED
2507 * on exit syscall) in multithreaded programs exactly
2508 * in order to handle this case.
2510 * PTRACE_GETEVENTMSG returns old pid starting from Linux 3.0.
2511 * On 2.6 and earlier, it can return garbage.
2513 if (os_release >= KERNEL_VERSION(3, 0, 0))
2514 current_tcp = maybe_switch_tcbs(current_tcp, current_tcp->pid);
2516 if (detach_on_execve) {
2517 if (current_tcp->flags & TCB_SKIP_DETACH_ON_FIRST_EXEC) {
2518 current_tcp->flags &= ~TCB_SKIP_DETACH_ON_FIRST_EXEC;
2520 detach(current_tcp); /* do "-b execve" thingy */
2526 case TE_STOP_BEFORE_EXIT:
2527 print_event_exit(current_tcp);
2531 /* We handled quick cases, we are permitted to interrupt now. */
2535 if (ptrace_restart(restart_op, current_tcp, restart_sig) < 0) {
2536 /* Note: ptrace_restart emitted error message */
2543 #ifdef ENABLE_COVERAGE_GCOV
2544 extern void __gcov_flush(void);
2547 static void ATTRIBUTE_NORETURN
2552 if (shared_log != stderr)
2555 while (waitpid(popen_pid, NULL, 0) < 0 && errno == EINTR)
2558 if (exit_code > 0xff) {
2559 /* Avoid potential core file clobbering. */
2560 struct_rlimit rlim = {0, 0};
2561 set_rlimit(RLIMIT_CORE, &rlim);
2563 /* Child was killed by a signal, mimic that. */
2565 signal(exit_code, SIG_DFL);
2566 #ifdef ENABLE_COVERAGE_GCOV
2571 /* Unblock the signal. */
2574 sigaddset(&mask, exit_code);
2575 #ifdef ENABLE_COVERAGE_GCOV
2578 sigprocmask(SIG_UNBLOCK, &mask, NULL);
2580 /* Paranoia - what if this signal is not fatal?
2581 Exit with 128 + signo then. */
2588 main(int argc, char *argv[])
2592 exit_code = !nprocs;
2596 while (dispatch_event(next_event(&status, &si), &status, &si))