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 void ATTRIBUTE_NORETURN
292 if (strace_tracer_pid == getpid()) {
300 error_opt_arg(int opt, const char *arg)
302 error_msg_and_help("invalid -%c argument: '%s'", opt, arg);
305 static const char *ptrace_attach_cmd;
308 ptrace_attach_or_seize(int pid)
313 return ptrace_attach_cmd = "PTRACE_ATTACH",
314 ptrace(PTRACE_ATTACH, pid, 0L, 0L);
315 r = ptrace(PTRACE_SEIZE, pid, 0L, (unsigned long) ptrace_setoptions);
317 return ptrace_attach_cmd = "PTRACE_SEIZE", r;
318 r = ptrace(PTRACE_INTERRUPT, pid, 0L, 0L);
319 return ptrace_attach_cmd = "PTRACE_INTERRUPT", r;
321 return ptrace_attach_cmd = "PTRACE_ATTACH",
322 ptrace(PTRACE_ATTACH, pid, 0L, 0L);
327 * Used when we want to unblock stopped traced process.
328 * Should be only used with PTRACE_CONT, PTRACE_DETACH and PTRACE_SYSCALL.
329 * Returns 0 on success or if error was ESRCH
330 * (presumably process was killed while we talk to it).
331 * Otherwise prints error message and returns -1.
334 ptrace_restart(const unsigned int op, struct tcb *const tcp, unsigned int sig)
340 ptrace(op, tcp->pid, 0L, (unsigned long) sig);
360 * Why curcol != 0? Otherwise sometimes we get this:
362 * 10252 kill(10253, SIGKILL) = 0
363 * <ptrace(SYSCALL,10252):No such process>10253 ...next decode...
365 * 10252 died after we retrieved syscall exit data,
366 * but before we tried to restart it. Log looks ugly.
368 if (current_tcp && current_tcp->curcol != 0) {
369 tprintf(" <ptrace(%s):%s>\n", msg, strerror(err));
375 perror_msg("ptrace(PTRACE_%s,pid:%d,sig:%u)", msg, tcp->pid, sig);
380 set_cloexec_flag(int fd)
384 flags = fcntl(fd, F_GETFD);
386 /* Can happen only if fd is bad.
387 * Should never happen: if it does, we have a bug
388 * in the caller. Therefore we just abort
389 * instead of propagating the error.
391 perror_msg_and_die("fcntl(%d, F_GETFD)", fd);
394 newflags = flags | FD_CLOEXEC;
395 if (flags == newflags)
398 fcntl(fd, F_SETFD, newflags); /* never fails */
402 kill_save_errno(pid_t pid, int sig)
404 int saved_errno = errno;
406 (void) kill(pid, sig);
411 * When strace is setuid executable, we have to swap uids
412 * before and after filesystem and process management operations.
417 int euid = geteuid(), uid = getuid();
419 if (euid != uid && setreuid(euid, uid) < 0) {
420 perror_msg_and_die("setreuid");
424 #ifdef _LARGEFILE64_SOURCE
426 # define fopen_for_output fopen64
428 # define fopen_for_output fopen
430 # define struct_stat struct stat64
431 # define stat_file stat64
432 # define struct_dirent struct dirent64
433 # define read_dir readdir64
434 # define struct_rlimit struct rlimit64
435 # define set_rlimit setrlimit64
437 # define fopen_for_output fopen
438 # define struct_stat struct stat
439 # define stat_file stat
440 # define struct_dirent struct dirent
441 # define read_dir readdir
442 # define struct_rlimit struct rlimit
443 # define set_rlimit setrlimit
447 strace_fopen(const char *path)
452 fp = fopen_for_output(path, "w");
454 perror_msg_and_die("Can't fopen '%s'", path);
456 set_cloexec_flag(fileno(fp));
460 static int popen_pid;
463 # define _PATH_BSHELL "/bin/sh"
467 * We cannot use standard popen(3) here because we have to distinguish
468 * popen child process from other processes we trace, and standard popen(3)
469 * does not export its child's pid.
472 strace_popen(const char *command)
480 perror_msg_and_die("pipe");
482 set_cloexec_flag(fds[1]); /* never fails */
486 perror_msg_and_die("vfork");
493 perror_msg_and_die("dup2");
496 execl(_PATH_BSHELL, "sh", "-c", command, NULL);
497 perror_msg_and_die("Can't execute '%s'", _PATH_BSHELL);
504 fp = fdopen(fds[1], "w");
506 perror_msg_and_die("fdopen");
510 ATTRIBUTE_FORMAT((printf, 1, 0))
512 tvprintf(const char *const fmt, va_list args)
515 int n = vfprintf(current_tcp->outf, fmt, args);
517 /* very unlikely due to vfprintf buffering */
518 if (current_tcp->outf != stderr)
519 perror_msg("%s", outfname);
521 current_tcp->curcol += n;
526 tprintf(const char *fmt, ...)
534 #ifndef HAVE_FPUTS_UNLOCKED
535 # define fputs_unlocked fputs
539 tprints(const char *str)
542 int n = fputs_unlocked(str, current_tcp->outf);
544 current_tcp->curcol += strlen(str);
547 /* very unlikely due to fputs_unlocked buffering */
548 if (current_tcp->outf != stderr)
549 perror_msg("%s", outfname);
554 tprints_comment(const char *const str)
557 tprintf(" /* %s */", str);
561 tprintf_comment(const char *fmt, ...)
575 flush_tcp_output(const struct tcb *const tcp)
577 if (fflush(tcp->outf) && tcp->outf != stderr)
578 perror_msg("%s", outfname);
585 current_tcp->curcol = 0;
586 flush_tcp_output(current_tcp);
589 printing_tcp->curcol = 0;
595 printleader(struct tcb *tcp)
597 /* If -ff, "previous tcb we printed" is always the same as current,
598 * because we have per-tcb output files.
604 current_tcp = printing_tcp;
605 if (printing_tcp->curcol != 0 && (followfork < 2 || printing_tcp == tcp)) {
607 * case 1: we have a shared log (i.e. not -ff), and last line
608 * wasn't finished (same or different tcb, doesn't matter).
609 * case 2: split log, we are the same tcb, but our last line
610 * didn't finish ("SIGKILL nuked us after syscall entry" etc).
612 tprints(" <unfinished ...>\n");
613 printing_tcp->curcol = 0;
619 current_tcp->curcol = 0;
622 tprintf("%-5d ", tcp->pid);
623 else if (nprocs > 1 && !outfname)
624 tprintf("[pid %5u] ", tcp->pid);
627 char str[sizeof("HH:MM:SS")];
628 struct timeval tv, dtv;
629 static struct timeval otv;
631 gettimeofday(&tv, NULL);
635 tv_sub(&dtv, &tv, &otv);
636 tprintf("%6ld.%06ld ",
637 (long) dtv.tv_sec, (long) dtv.tv_usec);
639 } else if (tflag > 2) {
640 tprintf("%ld.%06ld ",
641 (long) tv.tv_sec, (long) tv.tv_usec);
643 time_t local = tv.tv_sec;
644 strftime(str, sizeof(str), "%T", localtime(&local));
646 tprintf("%s.%06ld ", str, (long) tv.tv_usec);
658 if (current_tcp->curcol < acolumn)
659 tprints(acolumn_spaces + current_tcp->curcol);
662 /* Should be only called directly *after successful attach* to a tracee.
663 * Otherwise, "strace -oFILE -ff -p<nonexistant_pid>"
664 * may create bogus empty FILE.<nonexistant_pid>, and then die.
667 newoutf(struct tcb *tcp)
669 tcp->outf = shared_log; /* if not -ff mode, the same file is for all */
670 if (followfork >= 2) {
671 char name[520 + sizeof(int) * 3];
672 sprintf(name, "%.512s.%u", outfname, tcp->pid);
673 tcp->outf = strace_fopen(name);
680 /* Allocate some (more) TCBs (and expand the table).
681 We don't want to relocate the TCBs because our
682 callers have pointers and it would be a pain.
683 So tcbtab is a table of pointers. Since we never
684 free the TCBs, we allocate a single chunk of many. */
685 unsigned int new_tcbtabsize, alloc_tcbtabsize;
689 alloc_tcbtabsize = tcbtabsize;
690 new_tcbtabsize = tcbtabsize * 2;
692 new_tcbtabsize = alloc_tcbtabsize = 1;
695 newtcbs = xcalloc(alloc_tcbtabsize, sizeof(newtcbs[0]));
696 tcbtab = xreallocarray(tcbtab, new_tcbtabsize, sizeof(tcbtab[0]));
697 while (tcbtabsize < new_tcbtabsize)
698 tcbtab[tcbtabsize++] = newtcbs++;
707 if (nprocs == tcbtabsize)
710 for (i = 0; i < tcbtabsize; i++) {
713 memset(tcp, 0, sizeof(*tcp));
715 #if SUPPORTED_PERSONALITIES > 1
716 tcp->currpers = current_personality;
720 if (stack_trace_enabled)
721 unwind_tcb_init(tcp);
726 error_msg("new tcb for pid %d, active tcbs:%d",
731 error_msg_and_die("bug in alloctcb");
735 get_tcb_priv_data(const struct tcb *tcp)
737 return tcp->_priv_data;
741 set_tcb_priv_data(struct tcb *tcp, void *const priv_data,
742 void (*const free_priv_data)(void *))
747 tcp->_free_priv_data = free_priv_data;
748 tcp->_priv_data = priv_data;
754 free_tcb_priv_data(struct tcb *tcp)
756 if (tcp->_priv_data) {
757 if (tcp->_free_priv_data) {
758 tcp->_free_priv_data(tcp->_priv_data);
759 tcp->_free_priv_data = NULL;
761 tcp->_priv_data = NULL;
766 droptcb(struct tcb *tcp)
772 for (p = 0; p < SUPPORTED_PERSONALITIES; ++p)
773 free(tcp->inject_vec[p]);
775 free_tcb_priv_data(tcp);
778 if (stack_trace_enabled) {
785 error_msg("dropped tcb for pid %d, %d remain",
789 if (followfork >= 2) {
790 if (tcp->curcol != 0)
791 fprintf(tcp->outf, " <detached ...>\n");
794 if (printing_tcp == tcp && tcp->curcol != 0)
795 fprintf(tcp->outf, " <detached ...>\n");
796 flush_tcp_output(tcp);
800 if (current_tcp == tcp)
802 if (printing_tcp == tcp)
805 memset(tcp, 0, sizeof(*tcp));
808 /* Detach traced process.
809 * Never call DETACH twice on the same process as both unattached and
810 * attached-unstopped processes give the same ESRCH. For unattached process we
811 * would SIGSTOP it and wait for its SIGSTOP notification forever.
814 detach(struct tcb *tcp)
820 * Linux wrongly insists the child be stopped
821 * before detaching. Arghh. We go through hoops
822 * to make a clean break of things.
825 if (!(tcp->flags & TCB_ATTACHED))
828 /* We attached but possibly didn't see the expected SIGSTOP.
829 * We must catch exactly one as otherwise the detached process
830 * would be left stopped (process state T).
832 if (tcp->flags & TCB_IGNORE_ONE_SIGSTOP)
835 error = ptrace(PTRACE_DETACH, tcp->pid, 0, 0);
837 /* On a clear day, you can see forever. */
840 if (errno != ESRCH) {
841 /* Shouldn't happen. */
842 perror_msg("detach: ptrace(PTRACE_DETACH,%u)", tcp->pid);
845 /* ESRCH: process is either not stopped or doesn't exist. */
846 if (my_tkill(tcp->pid, 0) < 0) {
848 /* Shouldn't happen. */
849 perror_msg("detach: tkill(%u,0)", tcp->pid);
850 /* else: process doesn't exist. */
853 /* Process is not stopped, need to stop it. */
856 * With SEIZE, tracee can be in group-stop already.
857 * In this state sending it another SIGSTOP does nothing.
858 * Need to use INTERRUPT.
859 * Testcase: trying to ^C a "strace -p <stopped_process>".
861 error = ptrace(PTRACE_INTERRUPT, tcp->pid, 0, 0);
865 perror_msg("detach: ptrace(PTRACE_INTERRUPT,%u)", tcp->pid);
867 error = my_tkill(tcp->pid, SIGSTOP);
871 perror_msg("detach: tkill(%u,SIGSTOP)", tcp->pid);
873 /* Either process doesn't exist, or some weird error. */
877 /* We end up here in three cases:
878 * 1. We sent PTRACE_INTERRUPT (use_seize case)
879 * 2. We sent SIGSTOP (!use_seize)
880 * 3. Attach SIGSTOP was already pending (TCB_IGNORE_ONE_SIGSTOP set)
884 if (waitpid(tcp->pid, &status, __WALL) < 0) {
888 * if (errno == ECHILD) break;
889 * ^^^ WRONG! We expect this PID to exist,
890 * and want to emit a message otherwise:
892 perror_msg("detach: waitpid(%u)", tcp->pid);
895 if (!WIFSTOPPED(status)) {
897 * Tracee exited or was killed by signal.
898 * We shouldn't normally reach this place:
899 * we don't want to consume exit status.
900 * Consider "strace -p PID" being ^C-ed:
901 * we want merely to detach from PID.
903 * However, we _can_ end up here if tracee
908 sig = WSTOPSIG(status);
910 error_msg("detach wait: event:%d sig:%d",
911 (unsigned)status >> 16, sig);
913 unsigned event = (unsigned)status >> 16;
914 if (event == PTRACE_EVENT_STOP /*&& sig == SIGTRAP*/) {
916 * sig == SIGTRAP: PTRACE_INTERRUPT stop.
917 * sig == other: process was already stopped
918 * with this stopping sig (see tests/detach-stopped).
919 * Looks like re-injecting this sig is not necessary
920 * in DETACH for the tracee to remain stopped.
925 * PTRACE_INTERRUPT is not guaranteed to produce
926 * the above event if other ptrace-stop is pending.
927 * See tests/detach-sleeping testcase:
928 * strace got SIGINT while tracee is sleeping.
929 * We sent PTRACE_INTERRUPT.
930 * We see syscall exit, not PTRACE_INTERRUPT stop.
931 * We won't get PTRACE_INTERRUPT stop
932 * if we would CONT now. Need to DETACH.
934 if (sig == syscall_trap_sig)
936 /* else: not sure in which case we can be here.
937 * Signal stop? Inject it while detaching.
939 ptrace_restart(PTRACE_DETACH, tcp, sig);
942 /* Note: this check has to be after use_seize check */
943 /* (else, in use_seize case SIGSTOP will be mistreated) */
944 if (sig == SIGSTOP) {
945 /* Detach, suppressing SIGSTOP */
946 ptrace_restart(PTRACE_DETACH, tcp, 0);
949 if (sig == syscall_trap_sig)
951 /* Can't detach just yet, may need to wait for SIGSTOP */
952 error = ptrace_restart(PTRACE_CONT, tcp, sig);
954 /* Should not happen.
955 * Note: ptrace_restart returns 0 on ESRCH, so it's not it.
956 * ptrace_restart already emitted error message.
963 if (!qflag && (tcp->flags & TCB_ATTACHED))
964 error_msg("Process %u detached", tcp->pid);
970 process_opt_p_list(char *opt)
974 * We accept -p PID,PID; -p "`pidof PROG`"; -p "`pgrep PROG`".
975 * pidof uses space as delim, pgrep uses newline. :(
978 char *delim = opt + strcspn(opt, "\n\t ,");
982 pid = string_to_uint(opt);
984 error_msg_and_die("Invalid process id: '%s'", opt);
986 if (pid == strace_tracer_pid) {
987 error_msg_and_die("I'm sorry, I can't let you do that, Dave.");
998 attach_tcb(struct tcb *const tcp)
1000 if (ptrace_attach_or_seize(tcp->pid) < 0) {
1001 perror_msg("attach: ptrace(%s, %d)",
1002 ptrace_attach_cmd, tcp->pid);
1007 tcp->flags |= TCB_ATTACHED | TCB_STARTUP | post_attach_sigstop;
1010 error_msg("attach to pid %d (main) succeeded", tcp->pid);
1012 char procdir[sizeof("/proc/%d/task") + sizeof(int) * 3];
1014 unsigned int ntid = 0, nerr = 0;
1016 if (followfork && tcp->pid != strace_child &&
1017 sprintf(procdir, "/proc/%d/task", tcp->pid) > 0 &&
1018 (dir = opendir(procdir)) != NULL) {
1021 while ((de = read_dir(dir)) != NULL) {
1022 if (de->d_fileno == 0)
1025 int tid = string_to_uint(de->d_name);
1026 if (tid <= 0 || tid == tcp->pid)
1030 if (ptrace_attach_or_seize(tid) < 0) {
1033 perror_msg("attach: ptrace(%s, %d)",
1034 ptrace_attach_cmd, tid);
1038 error_msg("attach to pid %d succeeded", tid);
1040 struct tcb *tid_tcp = alloctcb(tid);
1041 tid_tcp->flags |= TCB_ATTACHED | TCB_STARTUP |
1042 post_attach_sigstop;
1051 error_msg("Process %u attached"
1053 tcp->pid, ntid - nerr + 1);
1055 error_msg("Process %u attached",
1061 startup_attach(void)
1063 pid_t parent_pid = strace_tracer_pid;
1068 * Block user interruptions as we would leave the traced
1069 * process stopped (process state T) if we would terminate in
1070 * between PTRACE_ATTACH and wait4() on SIGSTOP.
1071 * We rely on cleanup() from this point on.
1074 sigprocmask(SIG_SETMASK, &blocked_set, NULL);
1076 if (daemonized_tracer) {
1079 perror_msg_and_die("fork");
1081 if (pid) { /* parent */
1083 * Wait for grandchild to attach to straced process
1084 * (grandparent). Grandchild SIGKILLs us after it attached.
1085 * Grandparent's wait() is unblocked by our death,
1086 * it proceeds to exec the straced program.
1089 _exit(0); /* paranoia */
1092 /* We will be the tracer process. Remember our new pid: */
1093 strace_tracer_pid = getpid();
1096 for (tcbi = 0; tcbi < tcbtabsize; tcbi++) {
1102 /* Is this a process we should attach to, but not yet attached? */
1103 if (tcp->flags & TCB_ATTACHED)
1104 continue; /* no, we already attached it */
1106 if (tcp->pid == parent_pid || tcp->pid == strace_tracer_pid) {
1108 perror_msg("attach: pid %d", tcp->pid);
1116 sigprocmask(SIG_SETMASK, &start_set, NULL);
1119 sigprocmask(SIG_SETMASK, &blocked_set, NULL);
1121 } /* for each tcbtab[] */
1123 if (daemonized_tracer) {
1125 * Make parent go away.
1126 * Also makes grandparent's wait() unblock.
1128 kill(parent_pid, SIGKILL);
1134 sigprocmask(SIG_SETMASK, &start_set, NULL);
1137 /* Stack-o-phobic exec helper, in the hope to work around
1138 * NOMMU + "daemonized tracer" difficulty.
1140 struct exec_params {
1146 struct sigaction child_sa;
1148 static struct exec_params params_for_tracee;
1150 static void ATTRIBUTE_NOINLINE ATTRIBUTE_NORETURN
1153 struct exec_params *params = ¶ms_for_tracee;
1155 if (params->fd_to_close >= 0)
1156 close(params->fd_to_close);
1157 if (!daemonized_tracer && !use_seize) {
1158 if (ptrace(PTRACE_TRACEME, 0L, 0L, 0L) < 0) {
1159 perror_msg_and_die("ptrace(PTRACE_TRACEME, ...)");
1163 if (username != NULL) {
1165 * It is important to set groups before we
1166 * lose privileges on setuid.
1168 if (initgroups(username, run_gid) < 0) {
1169 perror_msg_and_die("initgroups");
1171 if (setregid(run_gid, params->run_egid) < 0) {
1172 perror_msg_and_die("setregid");
1174 if (setreuid(run_uid, params->run_euid) < 0) {
1175 perror_msg_and_die("setreuid");
1177 } else if (geteuid() != 0)
1178 if (setreuid(run_uid, run_uid) < 0) {
1179 perror_msg_and_die("setreuid");
1182 if (!daemonized_tracer) {
1184 * Induce a ptrace stop. Tracer (our parent)
1185 * will resume us with PTRACE_SYSCALL and display
1186 * the immediately following execve syscall.
1187 * Can't do this on NOMMU systems, we are after
1188 * vfork: parent is blocked, stopping would deadlock.
1191 kill(getpid(), SIGSTOP);
1194 /* we depend on SIGCHLD set to SIG_DFL by init code */
1195 /* if it happens to be SIG_IGN'ed, wait won't block */
1200 if (params_for_tracee.child_sa.sa_handler != SIG_DFL)
1201 sigaction(SIGCHLD, ¶ms_for_tracee.child_sa, NULL);
1203 execv(params->pathname, params->argv);
1204 perror_msg_and_die("exec");
1208 * Open a dummy descriptor for use as a placeholder.
1209 * The descriptor is O_RDONLY with FD_CLOEXEC flag set.
1210 * A read attempt from such descriptor ends with EOF,
1211 * a write attempt is rejected with EBADF.
1214 open_dummy_desc(void)
1219 perror_msg_and_die("pipe");
1221 set_cloexec_flag(fds[0]);
1225 /* placeholder fds status for stdin and stdout */
1226 static bool fd_is_placeholder[2];
1229 * Ensure that all standard file descriptors are open by opening placeholder
1230 * file descriptors for those standard file descriptors that are not open.
1232 * The information which descriptors have been made open is saved
1233 * in fd_is_placeholder for later use.
1236 ensure_standard_fds_opened(void)
1240 while ((fd = open_dummy_desc()) <= 2) {
1243 fd_is_placeholder[fd] = true;
1251 * Redirect stdin and stdout unless they have been opened earlier
1252 * by ensure_standard_fds_opened as placeholders.
1255 redirect_standard_fds(void)
1260 * It might be a good idea to redirect stderr as well,
1261 * but we sometimes need to print error messages.
1263 for (i = 0; i <= 1; ++i) {
1264 if (!fd_is_placeholder[i]) {
1272 startup_child(char **argv)
1274 struct_stat statbuf;
1275 const char *filename;
1276 size_t filename_len;
1277 char pathname[PATH_MAX];
1282 filename_len = strlen(filename);
1284 if (filename_len > sizeof(pathname) - 1) {
1285 errno = ENAMETOOLONG;
1286 perror_msg_and_die("exec");
1288 if (strchr(filename, '/')) {
1289 strcpy(pathname, filename);
1291 #ifdef USE_DEBUGGING_EXEC
1293 * Debuggers customarily check the current directory
1294 * first regardless of the path but doing that gives
1295 * security geeks a panic attack.
1297 else if (stat_file(filename, &statbuf) == 0)
1298 strcpy(pathname, filename);
1299 #endif /* USE_DEBUGGING_EXEC */
1304 for (path = getenv("PATH"); path && *path; path += m) {
1305 const char *colon = strchr(path, ':');
1310 m = n = strlen(path);
1312 if (!getcwd(pathname, PATH_MAX))
1314 len = strlen(pathname);
1315 } else if (n > sizeof(pathname) - 1)
1318 strncpy(pathname, path, n);
1321 if (len && pathname[len - 1] != '/')
1322 pathname[len++] = '/';
1323 if (filename_len + len > sizeof(pathname) - 1)
1325 strcpy(pathname + len, filename);
1326 if (stat_file(pathname, &statbuf) == 0 &&
1327 /* Accept only regular files
1328 with some execute bits set.
1329 XXX not perfect, might still fail */
1330 S_ISREG(statbuf.st_mode) &&
1331 (statbuf.st_mode & 0111))
1334 if (!path || !*path)
1337 if (stat_file(pathname, &statbuf) < 0) {
1338 perror_msg_and_die("Can't stat '%s'", filename);
1341 params_for_tracee.fd_to_close = (shared_log != stderr) ? fileno(shared_log) : -1;
1342 params_for_tracee.run_euid = (statbuf.st_mode & S_ISUID) ? statbuf.st_uid : run_uid;
1343 params_for_tracee.run_egid = (statbuf.st_mode & S_ISGID) ? statbuf.st_gid : run_gid;
1344 params_for_tracee.argv = argv;
1346 * On NOMMU, can be safely freed only after execve in tracee.
1347 * It's hard to know when that happens, so we just leak it.
1349 params_for_tracee.pathname = NOMMU_SYSTEM ? xstrdup(pathname) : pathname;
1351 #if defined HAVE_PRCTL && defined PR_SET_PTRACER && defined PR_SET_PTRACER_ANY
1352 if (daemonized_tracer)
1353 prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY);
1358 perror_msg_and_die("fork");
1360 if ((pid != 0 && daemonized_tracer)
1361 || (pid == 0 && !daemonized_tracer)
1363 /* We are to become the tracee. Two cases:
1365 * not -D: we are child
1370 /* We are the tracer */
1372 if (!daemonized_tracer) {
1375 /* child did PTRACE_TRACEME, nothing to do in parent */
1377 if (!NOMMU_SYSTEM) {
1378 /* Wait until child stopped itself */
1380 while (waitpid(pid, &status, WSTOPPED) < 0) {
1383 perror_msg_and_die("waitpid");
1385 if (!WIFSTOPPED(status) || WSTOPSIG(status) != SIGSTOP) {
1386 kill_save_errno(pid, SIGKILL);
1387 perror_msg_and_die("Unexpected wait status %#x",
1391 /* Else: NOMMU case, we have no way to sync.
1392 * Just attach to it as soon as possible.
1393 * This means that we may miss a few first syscalls...
1396 if (ptrace_attach_or_seize(pid)) {
1397 kill_save_errno(pid, SIGKILL);
1398 perror_msg_and_die("attach: ptrace(%s, %d)",
1399 ptrace_attach_cmd, pid);
1404 tcp = alloctcb(pid);
1405 tcp->flags |= TCB_ATTACHED | TCB_STARTUP
1406 | TCB_SKIP_DETACH_ON_FIRST_EXEC
1407 | (NOMMU_SYSTEM ? 0 : (TCB_HIDE_LOG | post_attach_sigstop));
1410 /* With -D, we are *child* here, the tracee is our parent. */
1411 strace_child = strace_tracer_pid;
1412 strace_tracer_pid = getpid();
1413 tcp = alloctcb(strace_child);
1414 tcp->flags |= TCB_SKIP_DETACH_ON_FIRST_EXEC | TCB_HIDE_LOG;
1415 /* attaching will be done later, by startup_attach */
1416 /* note: we don't do newoutf(tcp) here either! */
1418 /* NOMMU BUG! -D mode is active, we (child) return,
1419 * and we will scribble over parent's stack!
1420 * When parent later unpauses, it segfaults.
1423 * (1) by declaring exec_or_die() NORETURN,
1424 * hopefully compiler will just jump to it
1425 * instead of call (won't push anything to stack),
1426 * (2) by trying very hard in exec_or_die()
1427 * to not use any stack,
1428 * (3) having a really big (PATH_MAX) stack object
1429 * in this function, which creates a "buffer" between
1430 * child's and parent's stack pointers.
1431 * This may save us if (1) and (2) failed
1432 * and compiler decided to use stack in exec_or_die() anyway
1433 * (happens on i386 because of stack parameter passing).
1435 * A cleaner solution is to use makecontext + setcontext
1436 * to create a genuine separate stack and execute on it.
1440 * A case where straced process is part of a pipe:
1441 * { sleep 1; yes | head -n99999; } | strace -o/dev/null sh -c 'exec <&-; sleep 9'
1442 * If strace won't close its fd#0, closing it in tracee is not enough:
1443 * the pipe is still open, it has a reader. Thus, "head" will not get its
1444 * SIGPIPE at once, on the first write.
1446 * Preventing it by redirecting strace's stdin/out.
1447 * (Don't leave fds 0 and 1 closed, this is bad practice: future opens
1448 * will reuse them, unexpectedly making a newly opened object "stdin").
1450 redirect_standard_fds();
1455 test_ptrace_seize(void)
1459 /* Need fork for test. NOMMU has no forks */
1461 post_attach_sigstop = 0; /* this sets use_seize to 1 */
1467 perror_msg_and_die("fork");
1474 /* PTRACE_SEIZE, unlike ATTACH, doesn't force tracee to trap. After
1475 * attaching tracee continues to run unless a trap condition occurs.
1476 * PTRACE_SEIZE doesn't affect signal or group stop state.
1478 if (ptrace(PTRACE_SEIZE, pid, 0, 0) == 0) {
1479 post_attach_sigstop = 0; /* this sets use_seize to 1 */
1480 } else if (debug_flag) {
1481 error_msg("PTRACE_SEIZE doesn't work");
1487 int status, tracee_pid;
1490 tracee_pid = waitpid(pid, &status, 0);
1491 if (tracee_pid <= 0) {
1494 perror_msg_and_die("%s: unexpected wait result %d",
1495 __func__, tracee_pid);
1497 if (WIFSIGNALED(status)) {
1500 error_msg_and_die("%s: unexpected wait status %#x",
1504 #else /* !USE_SEIZE */
1505 # define test_ptrace_seize() ((void)0)
1509 get_os_release(void)
1515 perror_msg_and_die("uname");
1516 /* u.release has this form: "3.2.9[-some-garbage]" */
1520 if (!(*p >= '0' && *p <= '9'))
1521 error_msg_and_die("Bad OS release string: '%s'", u.release);
1522 /* Note: this open-codes KERNEL_VERSION(): */
1523 rel = (rel << 8) | atoi(p);
1524 if (rel >= KERNEL_VERSION(1, 0, 0))
1526 while (*p >= '0' && *p <= '9')
1529 if (rel >= KERNEL_VERSION(0, 1, 0)) {
1530 /* "X.Y-something" means "X.Y.0" */
1534 error_msg_and_die("Bad OS release string: '%s'", u.release);
1542 set_sigaction(int signo, void (*sighandler)(int), struct sigaction *oldact)
1544 /* if signal handler is a function, add the signal to blocked_set */
1545 if (sighandler != SIG_IGN && sighandler != SIG_DFL)
1546 sigaddset(&blocked_set, signo);
1548 const struct sigaction sa = { .sa_handler = sighandler };
1549 sigaction(signo, &sa, oldact);
1553 * Initialization part of main() was eating much stack (~0.5k),
1554 * which was unused after init.
1555 * We can reuse it if we move init code into a separate function.
1557 * Don't want main() to inline us and defeat the reason
1558 * we have a separate function.
1560 static void ATTRIBUTE_NOINLINE
1561 init(int argc, char *argv[])
1566 if (!program_invocation_name || !*program_invocation_name) {
1567 static char name[] = "strace";
1568 program_invocation_name =
1569 (argv[0] && *argv[0]) ? argv[0] : name;
1572 strace_tracer_pid = getpid();
1574 os_release = get_os_release();
1576 shared_log = stderr;
1577 set_sortby(DEFAULT_SORTBY);
1578 set_personality(DEFAULT_PERSONALITY);
1579 qualify("trace=all");
1580 qualify("abbrev=all");
1581 qualify("verbose=all");
1582 #if DEFAULT_QUAL_FLAGS != (QUAL_TRACE | QUAL_ABBREV | QUAL_VERBOSE)
1583 # error Bug in DEFAULT_QUAL_FLAGS
1585 qualify("signal=all");
1586 while ((c = getopt(argc, argv,
1587 "+b:cCdfFhiqrtTvVwxyz"
1588 #ifdef USE_LIBUNWIND
1592 "a:e:o:O:p:s:S:u:E:P:I:")) != EOF) {
1595 if (strcmp(optarg, "execve") != 0)
1596 error_msg_and_die("Syscall '%s' for -b isn't supported",
1598 detach_on_execve = 1;
1601 if (cflag == CFLAG_BOTH) {
1602 error_msg_and_help("-c and -C are mutually exclusive");
1604 cflag = CFLAG_ONLY_STATS;
1607 if (cflag == CFLAG_ONLY_STATS) {
1608 error_msg_and_help("-c and -C are mutually exclusive");
1616 daemonized_tracer = 1;
1643 count_wallclock = 1;
1652 qualify("abbrev=none");
1659 not_failing_only = 1;
1662 acolumn = string_to_uint(optarg);
1664 error_opt_arg(c, optarg);
1673 i = string_to_uint(optarg);
1675 error_opt_arg(c, optarg);
1679 process_opt_p_list(optarg);
1682 pathtrace_select(optarg);
1685 i = string_to_uint(optarg);
1686 if (i < 0 || (unsigned int) i > -1U / 4)
1687 error_opt_arg(c, optarg);
1696 #ifdef USE_LIBUNWIND
1698 stack_trace_enabled = true;
1702 if (putenv(optarg) < 0)
1703 perror_msg_and_die("putenv");
1706 opt_intr = string_to_uint_upto(optarg, NUM_INTR_OPTS - 1);
1708 error_opt_arg(c, optarg);
1711 error_msg_and_help(NULL);
1719 if (argc < 0 || (!argv[0] && !nprocs)) {
1720 error_msg_and_help("must have PROG [ARGS] or -p PID");
1723 if (!argv[0] && daemonized_tracer) {
1724 error_msg_and_help("PROG [ARGS] must be specified with -D");
1730 if (followfork >= 2 && cflag) {
1731 error_msg_and_help("(-c or -C) and -ff are mutually exclusive");
1734 if (count_wallclock && !cflag) {
1735 error_msg_and_help("-w must be given with (-c or -C)");
1738 if (cflag == CFLAG_ONLY_STATS) {
1740 error_msg("-%c has no effect with -c", 'i');
1741 #ifdef USE_LIBUNWIND
1742 if (stack_trace_enabled)
1743 error_msg("-%c has no effect with -c", 'k');
1746 error_msg("-%c has no effect with -c", 'r');
1748 error_msg("-%c has no effect with -c", 't');
1750 error_msg("-%c has no effect with -c", 'T');
1752 error_msg("-%c has no effect with -c", 'y');
1757 error_msg("-tt has no effect with -r");
1761 acolumn_spaces = xmalloc(acolumn + 1);
1762 memset(acolumn_spaces, ' ', acolumn);
1763 acolumn_spaces[acolumn] = '\0';
1765 sigprocmask(SIG_SETMASK, NULL, &start_set);
1766 memcpy(&blocked_set, &start_set, sizeof(blocked_set));
1768 set_sigaction(SIGCHLD, SIG_DFL, ¶ms_for_tracee.child_sa);
1770 #ifdef USE_LIBUNWIND
1771 if (stack_trace_enabled) {
1775 for (tcbi = 0; tcbi < tcbtabsize; ++tcbi) {
1776 unwind_tcb_init(tcbtab[tcbi]);
1781 /* See if they want to run as another user. */
1782 if (username != NULL) {
1783 struct passwd *pent;
1785 if (getuid() != 0 || geteuid() != 0) {
1786 error_msg_and_die("You must be root to use the -u option");
1788 pent = getpwnam(username);
1790 error_msg_and_die("Cannot find user '%s'", username);
1792 run_uid = pent->pw_uid;
1793 run_gid = pent->pw_gid;
1800 ptrace_setoptions |= PTRACE_O_TRACECLONE |
1801 PTRACE_O_TRACEFORK |
1802 PTRACE_O_TRACEVFORK;
1804 error_msg("ptrace_setoptions = %#x", ptrace_setoptions);
1805 test_ptrace_seize();
1808 * Is something weird with our stdin and/or stdout -
1809 * for example, may they be not open? In this case,
1810 * ensure that none of the future opens uses them.
1812 * This was seen in the wild when /proc/sys/kernel/core_pattern
1813 * was set to "|/bin/strace -o/tmp/LOG PROG":
1814 * kernel runs coredump helper with fd#0 open but fd#1 closed (!),
1815 * therefore LOG gets opened to fd#1, and fd#1 is closed by
1816 * "don't hold up stdin/out open" code soon after.
1818 ensure_standard_fds_opened();
1820 /* Check if they want to redirect the output. */
1822 /* See if they want to pipe the output. */
1823 if (outfname[0] == '|' || outfname[0] == '!') {
1825 * We can't do the <outfname>.PID funny business
1826 * when using popen, so prohibit it.
1828 if (followfork >= 2)
1829 error_msg_and_help("piping the output and -ff are mutually exclusive");
1830 shared_log = strace_popen(outfname + 1);
1831 } else if (followfork < 2)
1832 shared_log = strace_fopen(outfname);
1834 /* -ff without -o FILE is the same as single -f */
1835 if (followfork >= 2)
1839 if (!outfname || outfname[0] == '|' || outfname[0] == '!') {
1840 setvbuf(shared_log, NULL, _IOLBF, 0);
1844 * argv[0] -pPID -oFILE Default interactive setting
1845 * yes * 0 INTR_WHILE_WAIT
1846 * no 1 0 INTR_WHILE_WAIT
1847 * yes * 1 INTR_NEVER
1848 * no 1 1 INTR_WHILE_WAIT
1851 if (outfname && argv[0]) {
1853 opt_intr = INTR_NEVER;
1858 opt_intr = INTR_WHILE_WAIT;
1861 * startup_child() must be called before the signal handlers get
1862 * installed below as they are inherited into the spawned process.
1863 * Also we do not need to be protected by them as during interruption
1864 * in the startup_child() mode we kill the spawned process anyway.
1867 startup_child(argv);
1870 set_sigaction(SIGTTOU, SIG_IGN, NULL);
1871 set_sigaction(SIGTTIN, SIG_IGN, NULL);
1872 if (opt_intr != INTR_ANYWHERE) {
1873 if (opt_intr == INTR_BLOCK_TSTP_TOO)
1874 set_sigaction(SIGTSTP, SIG_IGN, NULL);
1876 * In interactive mode (if no -o OUTFILE, or -p PID is used),
1877 * fatal signals are blocked while syscall stop is processed,
1878 * and acted on in between, when waiting for new syscall stops.
1879 * In non-interactive mode, signals are ignored.
1881 set_sigaction(SIGHUP, interactive ? interrupt : SIG_IGN, NULL);
1882 set_sigaction(SIGINT, interactive ? interrupt : SIG_IGN, NULL);
1883 set_sigaction(SIGQUIT, interactive ? interrupt : SIG_IGN, NULL);
1884 set_sigaction(SIGPIPE, interactive ? interrupt : SIG_IGN, NULL);
1885 set_sigaction(SIGTERM, interactive ? interrupt : SIG_IGN, NULL);
1888 if (nprocs != 0 || daemonized_tracer)
1891 /* Do we want pids printed in our -o OUTFILE?
1892 * -ff: no (every pid has its own file); or
1893 * -f: yes (there can be more pids in the future); or
1894 * -p PID1,PID2: yes (there are already more than one pid)
1896 print_pid_pfx = (outfname && followfork < 2 && (followfork == 1 || nprocs > 1));
1907 for (i = 0; i < tcbtabsize; i++) {
1908 struct tcb *tcp = tcbtab[i];
1909 if (tcp->pid == pid)
1923 /* 'interrupted' is a volatile object, fetch it only once */
1924 fatal_sig = interrupted;
1926 fatal_sig = SIGTERM;
1928 for (i = 0; i < tcbtabsize; i++) {
1933 error_msg("cleanup: looking at pid %u", tcp->pid);
1934 if (tcp->pid == strace_child) {
1935 kill(tcp->pid, SIGCONT);
1936 kill(tcp->pid, fatal_sig);
1941 call_summary(shared_log);
1951 print_debug_info(const int pid, int status)
1953 const unsigned int event = (unsigned int) status >> 16;
1954 char buf[sizeof("WIFEXITED,exitcode=%u") + sizeof(int)*3 /*paranoia:*/ + 16];
1955 char evbuf[sizeof(",EVENT_VFORK_DONE (%u)") + sizeof(int)*3 /*paranoia:*/ + 16];
1958 if (WIFSIGNALED(status))
1960 sprintf(buf, "WIFSIGNALED,%ssig=%s",
1961 WCOREDUMP(status) ? "core," : "",
1962 signame(WTERMSIG(status)));
1964 sprintf(buf, "WIFSIGNALED,sig=%s",
1965 signame(WTERMSIG(status)));
1967 if (WIFEXITED(status))
1968 sprintf(buf, "WIFEXITED,exitcode=%u", WEXITSTATUS(status));
1969 if (WIFSTOPPED(status))
1970 sprintf(buf, "WIFSTOPPED,sig=%s", signame(WSTOPSIG(status)));
1973 static const char *const event_names[] = {
1974 [PTRACE_EVENT_CLONE] = "CLONE",
1975 [PTRACE_EVENT_FORK] = "FORK",
1976 [PTRACE_EVENT_VFORK] = "VFORK",
1977 [PTRACE_EVENT_VFORK_DONE] = "VFORK_DONE",
1978 [PTRACE_EVENT_EXEC] = "EXEC",
1979 [PTRACE_EVENT_EXIT] = "EXIT",
1980 /* [PTRACE_EVENT_STOP (=128)] would make biggish array */
1982 const char *e = "??";
1983 if (event < ARRAY_SIZE(event_names))
1984 e = event_names[event];
1985 else if (event == PTRACE_EVENT_STOP)
1987 sprintf(evbuf, ",EVENT_%s (%u)", e, event);
1989 error_msg("[wait(0x%06x) = %u] %s%s", status, pid, buf, evbuf);
1993 maybe_allocate_tcb(const int pid, int status)
1995 if (!WIFSTOPPED(status)) {
1996 if (detach_on_execve && pid == strace_child) {
1997 /* example: strace -bexecve sh -c 'exec true' */
2002 * This can happen if we inherited an unknown child.
2003 * Example: (sleep 1 & exec strace true)
2005 error_msg("Exit of unknown pid %u ignored", pid);
2009 /* We assume it's a fork/vfork/clone child */
2010 struct tcb *tcp = alloctcb(pid);
2011 tcp->flags |= TCB_ATTACHED | TCB_STARTUP | post_attach_sigstop;
2014 error_msg("Process %d attached", pid);
2018 * This can happen if a clone call misused CLONE_PTRACE itself.
2020 * There used to be a dance around possible re-injection of
2021 * WSTOPSIG(status), but it was later removed as the only
2022 * observable stop here is the initial ptrace-stop.
2024 ptrace(PTRACE_DETACH, pid, NULL, 0L);
2025 error_msg("Detached unknown pid %d", pid);
2031 maybe_switch_tcbs(struct tcb *tcp, const int pid)
2034 struct tcb *execve_thread;
2037 if (ptrace(PTRACE_GETEVENTMSG, pid, NULL, &old_pid) < 0)
2039 /* Avoid truncation in pid2tcb() param passing */
2040 if (old_pid <= 0 || old_pid == pid)
2042 if ((unsigned long) old_pid > UINT_MAX)
2044 execve_thread = pid2tcb(old_pid);
2045 /* It should be !NULL, but I feel paranoid */
2049 if (execve_thread->curcol != 0) {
2051 * One case we are here is -ff:
2052 * try "strace -oLOG -ff test/threaded_execve"
2054 fprintf(execve_thread->outf, " <pid changed to %d ...>\n", pid);
2055 /*execve_thread->curcol = 0; - no need, see code below */
2057 /* Swap output FILEs (needed for -ff) */
2058 fp = execve_thread->outf;
2059 execve_thread->outf = tcp->outf;
2061 /* And their column positions */
2062 execve_thread->curcol = tcp->curcol;
2064 /* Drop leader, but close execve'd thread outfile (if -ff) */
2066 /* Switch to the thread, reusing leader's outfile and pid */
2067 tcp = execve_thread;
2069 if (cflag != CFLAG_ONLY_STATS) {
2071 tprintf("+++ superseded by execve in pid %lu +++\n", old_pid);
2073 tcp->flags |= TCB_REPRINT;
2080 print_signalled(struct tcb *tcp, const int pid, int status)
2082 if (pid == strace_child) {
2083 exit_code = 0x100 | WTERMSIG(status);
2087 if (cflag != CFLAG_ONLY_STATS
2088 && is_number_in_set(WTERMSIG(status), &signal_set)) {
2091 tprintf("+++ killed by %s %s+++\n",
2092 signame(WTERMSIG(status)),
2093 WCOREDUMP(status) ? "(core dumped) " : "");
2095 tprintf("+++ killed by %s +++\n",
2096 signame(WTERMSIG(status)));
2103 print_exited(struct tcb *tcp, const int pid, int status)
2105 if (pid == strace_child) {
2106 exit_code = WEXITSTATUS(status);
2110 if (cflag != CFLAG_ONLY_STATS &&
2113 tprintf("+++ exited with %d +++\n", WEXITSTATUS(status));
2119 print_stopped(struct tcb *tcp, const siginfo_t *si, const unsigned int sig)
2121 if (cflag != CFLAG_ONLY_STATS
2123 && is_number_in_set(sig, &signal_set)) {
2126 tprintf("--- %s ", signame(sig));
2130 tprintf("--- stopped by %s ---\n", signame(sig));
2136 startup_tcb(struct tcb *tcp)
2139 error_msg("pid %d has TCB_STARTUP, initializing it", tcp->pid);
2141 tcp->flags &= ~TCB_STARTUP;
2145 error_msg("setting opts 0x%x on pid %d",
2146 ptrace_setoptions, tcp->pid);
2147 if (ptrace(PTRACE_SETOPTIONS, tcp->pid, NULL, ptrace_setoptions) < 0) {
2148 if (errno != ESRCH) {
2149 /* Should never happen, really */
2150 perror_msg_and_die("PTRACE_SETOPTIONS");
2155 if (get_scno(tcp) == 1)
2156 tcp->s_prev_ent = tcp->s_ent;
2160 print_event_exit(struct tcb *tcp)
2162 if (entering(tcp) || filtered(tcp) || hide_log(tcp)
2163 || cflag == CFLAG_ONLY_STATS) {
2167 if (followfork < 2 && printing_tcp && printing_tcp != tcp
2168 && printing_tcp->curcol != 0) {
2169 current_tcp = printing_tcp;
2170 tprints(" <unfinished ...>\n");
2171 flush_tcp_output(printing_tcp);
2172 printing_tcp->curcol = 0;
2176 if ((followfork < 2 && printing_tcp != tcp)
2177 || (tcp->flags & TCB_REPRINT)) {
2178 tcp->flags &= ~TCB_REPRINT;
2180 tprintf("<... %s resumed>", tcp->s_ent->sys_name);
2183 if (!(tcp->sys_func_rval & RVAL_DECODED)) {
2185 * The decoder has probably decided to print something
2186 * on exiting syscall which is not going to happen.
2188 tprints(" <unfinished ...>");
2197 /* Break the main loop. */
2200 /* Call next_event() again. */
2203 /* Restart the tracee with signal 0 and call next_event() again. */
2207 * For all the events below, current_tcp is set to current tracee's
2208 * tcb. All the suggested actions imply that you want to continue
2209 * tracing of the current tracee; alternatively, you can detach it.
2213 * Syscall entry or exit.
2214 * Restart the tracee with signal 0, or with an injected signal number.
2219 * Tracee received signal with number WSTOPSIG(*pstatus); signal info
2220 * is written to *si. Restart the tracee (with that signal number
2221 * if you want to deliver it).
2223 TE_SIGNAL_DELIVERY_STOP,
2226 * Tracee was killed by a signal with number WTERMSIG(*pstatus).
2231 * Tracee was stopped by a signal with number WSTOPSIG(*pstatus).
2232 * Restart the tracee with that signal number.
2237 * Tracee exited with status WEXITSTATUS(*pstatus).
2242 * Tracee is going to perform execve().
2243 * Restart the tracee with signal 0.
2245 TE_STOP_BEFORE_EXECVE,
2248 * Tracee is going to terminate.
2249 * Restart the tracee with signal 0.
2251 TE_STOP_BEFORE_EXIT,
2254 static enum trace_event
2255 next_event(int *pstatus, siginfo_t *si)
2267 * Used to exit simply when nprocs hits zero, but in this testcase:
2268 * int main(void) { _exit(!!fork()); }
2269 * under strace -f, parent sometimes (rarely) manages
2270 * to exit before we see the first stop of the child,
2271 * and we are losing track of it:
2272 * 19923 clone(...) = 19924
2273 * 19923 exit_group(1) = ?
2274 * 19923 +++ exited with 1 +++
2275 * Exiting only when wait() returns ECHILD works better.
2277 if (popen_pid != 0) {
2278 /* However, if -o|logger is in use, we can't do that.
2279 * Can work around that by double-forking the logger,
2280 * but that loses the ability to wait for its completion
2281 * on exit. Oh well...
2288 sigprocmask(SIG_SETMASK, &start_set, NULL);
2289 pid = wait4(-1, pstatus, __WALL, (cflag ? &ru : NULL));
2292 sigprocmask(SIG_SETMASK, &blocked_set, NULL);
2295 if (wait_errno == EINTR)
2297 if (nprocs == 0 && wait_errno == ECHILD)
2300 * If nprocs > 0, ECHILD is not expected,
2301 * treat it as any other error here:
2304 perror_msg_and_die("wait4(__WALL)");
2309 if (pid == popen_pid) {
2310 if (!WIFSTOPPED(status))
2316 print_debug_info(pid, status);
2318 /* Look up 'pid' in our table. */
2322 tcp = maybe_allocate_tcb(pid, status);
2329 /* Set current output file */
2333 tv_sub(&tcp->dtime, &ru.ru_stime, &tcp->stime);
2334 tcp->stime = ru.ru_stime;
2337 if (WIFSIGNALED(status))
2338 return TE_SIGNALLED;
2340 if (WIFEXITED(status))
2344 * As WCONTINUED flag has not been specified to wait4,
2345 * it cannot be WIFCONTINUED(status), so the only case
2346 * that remains is WIFSTOPPED(status).
2349 /* Is this the very first time we see this tracee stopped? */
2350 if (tcp->flags & TCB_STARTUP)
2353 const unsigned int sig = WSTOPSIG(status);
2354 const unsigned int event = (unsigned int) status >> 16;
2359 * Is this post-attach SIGSTOP?
2360 * Interestingly, the process may stop
2361 * with STOPSIG equal to some other signal
2362 * than SIGSTOP if we happened to attach
2363 * just before the process takes a signal.
2365 if (sig == SIGSTOP && (tcp->flags & TCB_IGNORE_ONE_SIGSTOP)) {
2367 error_msg("ignored SIGSTOP on pid %d", tcp->pid);
2368 tcp->flags &= ~TCB_IGNORE_ONE_SIGSTOP;
2370 } else if (sig == syscall_trap_sig) {
2371 return TE_SYSCALL_STOP;
2373 *si = (siginfo_t) {};
2375 * True if tracee is stopped by signal
2376 * (as opposed to "tracee received signal").
2377 * TODO: shouldn't we check for errno == EINVAL too?
2378 * We can get ESRCH instead, you know...
2380 bool stopped = ptrace(PTRACE_GETSIGINFO, pid, 0, si) < 0;
2381 return stopped ? TE_GROUP_STOP : TE_SIGNAL_DELIVERY_STOP;
2385 case PTRACE_EVENT_STOP:
2387 * PTRACE_INTERRUPT-stop or group-stop.
2388 * PTRACE_INTERRUPT-stop has sig == SIGTRAP here.
2395 return TE_GROUP_STOP;
2399 case PTRACE_EVENT_EXEC:
2400 return TE_STOP_BEFORE_EXECVE;
2401 case PTRACE_EVENT_EXIT:
2402 return TE_STOP_BEFORE_EXIT;
2409 trace_syscall(struct tcb *tcp, unsigned int *sig)
2411 if (entering(tcp)) {
2412 int res = syscall_entering_decode(tcp);
2417 res = syscall_entering_trace(tcp, sig);
2419 syscall_entering_finish(tcp, res);
2422 struct timeval tv = {};
2423 int res = syscall_exiting_decode(tcp, &tv);
2425 res = syscall_exiting_trace(tcp, tv, res);
2427 syscall_exiting_finish(tcp);
2432 /* Returns true iff the main trace loop has to continue. */
2434 dispatch_event(enum trace_event ret, int *pstatus, siginfo_t *si)
2436 unsigned int restart_op = PTRACE_SYSCALL;
2437 unsigned int restart_sig = 0;
2449 case TE_SYSCALL_STOP:
2450 if (trace_syscall(current_tcp, &restart_sig) < 0) {
2452 * ptrace() failed in trace_syscall().
2453 * Likely a result of process disappearing mid-flight.
2454 * Observed case: exit_group() or SIGKILL terminating
2455 * all processes in thread group.
2456 * We assume that ptrace error was caused by process death.
2457 * We used to detach(current_tcp) here, but since we no
2458 * longer implement "detach before death" policy/hack,
2459 * we can let this process to report its death to us
2460 * normally, via WIFEXITED or WIFSIGNALED wait status.
2466 case TE_SIGNAL_DELIVERY_STOP:
2467 restart_sig = WSTOPSIG(*pstatus);
2468 print_stopped(current_tcp, si, restart_sig);
2472 print_signalled(current_tcp, current_tcp->pid, *pstatus);
2473 droptcb(current_tcp);
2477 restart_sig = WSTOPSIG(*pstatus);
2478 print_stopped(current_tcp, NULL, restart_sig);
2481 * This ends ptrace-stop, but does *not* end group-stop.
2482 * This makes stopping signals work properly on straced
2483 * process (that is, process really stops. It used to
2486 restart_op = PTRACE_LISTEN;
2492 print_exited(current_tcp, current_tcp->pid, *pstatus);
2493 droptcb(current_tcp);
2496 case TE_STOP_BEFORE_EXECVE:
2498 * Under Linux, execve changes pid to thread leader's pid,
2499 * and we see this changed pid on EVENT_EXEC and later,
2500 * execve sysexit. Leader "disappears" without exit
2501 * notification. Let user know that, drop leader's tcb,
2502 * and fix up pid in execve thread's tcb.
2503 * Effectively, execve thread's tcb replaces leader's tcb.
2505 * BTW, leader is 'stuck undead' (doesn't report WIFEXITED
2506 * on exit syscall) in multithreaded programs exactly
2507 * in order to handle this case.
2509 * PTRACE_GETEVENTMSG returns old pid starting from Linux 3.0.
2510 * On 2.6 and earlier, it can return garbage.
2512 if (os_release >= KERNEL_VERSION(3, 0, 0))
2513 current_tcp = maybe_switch_tcbs(current_tcp, current_tcp->pid);
2515 if (detach_on_execve) {
2516 if (current_tcp->flags & TCB_SKIP_DETACH_ON_FIRST_EXEC) {
2517 current_tcp->flags &= ~TCB_SKIP_DETACH_ON_FIRST_EXEC;
2519 detach(current_tcp); /* do "-b execve" thingy */
2525 case TE_STOP_BEFORE_EXIT:
2526 print_event_exit(current_tcp);
2530 /* We handled quick cases, we are permitted to interrupt now. */
2534 if (ptrace_restart(restart_op, current_tcp, restart_sig) < 0) {
2535 /* Note: ptrace_restart emitted error message */
2542 #ifdef ENABLE_COVERAGE_GCOV
2543 extern void __gcov_flush(void);
2546 static void ATTRIBUTE_NORETURN
2551 if (shared_log != stderr)
2554 while (waitpid(popen_pid, NULL, 0) < 0 && errno == EINTR)
2557 if (exit_code > 0xff) {
2558 /* Avoid potential core file clobbering. */
2559 struct_rlimit rlim = {0, 0};
2560 set_rlimit(RLIMIT_CORE, &rlim);
2562 /* Child was killed by a signal, mimic that. */
2564 signal(exit_code, SIG_DFL);
2565 #ifdef ENABLE_COVERAGE_GCOV
2570 /* Unblock the signal. */
2573 sigaddset(&mask, exit_code);
2574 #ifdef ENABLE_COVERAGE_GCOV
2577 sigprocmask(SIG_UNBLOCK, &mask, NULL);
2579 /* Paranoia - what if this signal is not fatal?
2580 Exit with 128 + signo then. */
2587 main(int argc, char *argv[])
2591 exit_code = !nprocs;
2595 while (dispatch_event(next_event(&status, &si), &status, &si))