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 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 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 printf("%s -- version %s\n"
197 "Copyright (c) 1991-%s The strace developers <%s>.\n"
198 "This is free software; see the source for copying conditions. There is NO\n"
199 "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n",
200 PACKAGE_NAME, PACKAGE_VERSION, COPYRIGHT_YEAR, PACKAGE_URL);
207 usage: strace [-CdffhiqrtttTvVwxxy] [-I n] [-e expr]...\n\
208 [-a column] [-o file] [-s strsize] [-P path]...\n\
209 -p pid... / [-D] [-E var=val]... [-u username] PROG [ARGS]\n\
210 or: strace -c[dfw] [-I n] [-e expr]... [-O overhead] [-S sortby]\n\
211 -p pid... / [-D] [-E var=val]... [-u username] PROG [ARGS]\n\
214 -a column alignment COLUMN for printing syscall results (default %d)\n\
215 -i print instruction pointer at time of syscall\n\
219 -k obtain stack trace between each syscall (experimental)\n\
223 -o file send trace output to FILE instead of stderr\n\
224 -q suppress messages about attaching, detaching, etc.\n\
225 -r print relative timestamp\n\
226 -s strsize limit length of print strings to STRSIZE chars (default %d)\n\
227 -t print absolute timestamp\n\
228 -tt print absolute timestamp with usecs\n\
229 -T print time spent in each syscall\n\
230 -x print non-ascii strings in hex\n\
231 -xx print all strings in hex\n\
232 -y print paths associated with file descriptor arguments\n\
233 -yy print protocol specific information associated with socket file descriptors\n\
236 -c count time, calls, and errors for each syscall and report summary\n\
237 -C like -c but also print regular output\n\
238 -O overhead set overhead for tracing syscalls to OVERHEAD usecs\n\
239 -S sortby sort syscall counts by: time, calls, name, nothing (default %s)\n\
240 -w summarise syscall latency (default is system time)\n\
243 -e expr a qualifying expression: option=[!]all or option=[!]val1[,val2]...\n\
244 options: trace, abbrev, verbose, raw, signal, read, write, fault\n\
245 -P path trace accesses to path\n\
248 -b execve detach on execve syscall\n\
249 -D run tracer process as a detached grandchild, not as parent\n\
251 -ff follow forks with output into separate files\n\
253 1: no signals are blocked\n\
254 2: fatal signals are blocked while decoding syscall (default)\n\
255 3: fatal signals are always blocked (default if '-o FILE PROG')\n\
256 4: fatal signals and SIGTSTP (^Z) are always blocked\n\
257 (useful to make 'strace -o FILE PROG' not stop on ^Z)\n\
260 -E var remove var from the environment for command\n\
261 -E var=val put var=val in the environment for command\n\
262 -p pid trace process with process id PID, may be repeated\n\
263 -u username run command as username handling setuid and/or setgid\n\
266 -d enable debug output to stderr\n\
267 -v verbose mode: print unabbreviated argv, stat, termios, etc. args\n\
268 -h print help message\n\
271 /* ancient, no one should use it
272 -F -- attempt to follow vforks (deprecated, use -f)\n\
274 /* this is broken, so don't document it
275 -z -- print only succeeding syscalls\n\
277 , DEFAULT_ACOLUMN, DEFAULT_STRLEN, DEFAULT_SORTBY);
281 static void ATTRIBUTE_NORETURN
284 if (strace_tracer_pid == getpid()) {
291 static void verror_msg(int err_no, const char *fmt, va_list p)
297 /* We want to print entire message with single fprintf to ensure
298 * message integrity if stderr is shared with other programs.
299 * Thus we use vasprintf + single fprintf.
302 if (vasprintf(&msg, fmt, p) >= 0) {
304 fprintf(stderr, "%s: %s: %s\n",
305 program_invocation_name, msg, strerror(err_no));
307 fprintf(stderr, "%s: %s\n",
308 program_invocation_name, msg);
311 /* malloc in vasprintf failed, try it without malloc */
312 fprintf(stderr, "%s: ", program_invocation_name);
313 vfprintf(stderr, fmt, p);
315 fprintf(stderr, ": %s\n", strerror(err_no));
319 /* We don't switch stderr to buffered, thus fprintf(stderr)
320 * always flushes its output and this is not necessary: */
321 /* fflush(stderr); */
324 void error_msg(const char *fmt, ...)
328 verror_msg(0, fmt, p);
332 void error_msg_and_die(const char *fmt, ...)
336 verror_msg(0, fmt, p);
340 void error_msg_and_help(const char *fmt, ...)
345 verror_msg(0, fmt, p);
347 fprintf(stderr, "Try '%s -h' for more information.\n",
348 program_invocation_name);
352 void perror_msg(const char *fmt, ...)
356 verror_msg(errno, fmt, p);
360 void perror_msg_and_die(const char *fmt, ...)
364 verror_msg(errno, fmt, p);
369 error_opt_arg(int opt, const char *arg)
371 error_msg_and_help("invalid -%c argument: '%s'", opt, arg);
374 static const char *ptrace_attach_cmd;
377 ptrace_attach_or_seize(int pid)
382 return ptrace_attach_cmd = "PTRACE_ATTACH",
383 ptrace(PTRACE_ATTACH, pid, 0L, 0L);
384 r = ptrace(PTRACE_SEIZE, pid, 0L, (unsigned long) ptrace_setoptions);
386 return ptrace_attach_cmd = "PTRACE_SEIZE", r;
387 r = ptrace(PTRACE_INTERRUPT, pid, 0L, 0L);
388 return ptrace_attach_cmd = "PTRACE_INTERRUPT", r;
390 return ptrace_attach_cmd = "PTRACE_ATTACH",
391 ptrace(PTRACE_ATTACH, pid, 0L, 0L);
396 * Used when we want to unblock stopped traced process.
397 * Should be only used with PTRACE_CONT, PTRACE_DETACH and PTRACE_SYSCALL.
398 * Returns 0 on success or if error was ESRCH
399 * (presumably process was killed while we talk to it).
400 * Otherwise prints error message and returns -1.
403 ptrace_restart(const unsigned int op, struct tcb *const tcp, unsigned int sig)
409 ptrace(op, tcp->pid, 0L, (unsigned long) sig);
429 * Why curcol != 0? Otherwise sometimes we get this:
431 * 10252 kill(10253, SIGKILL) = 0
432 * <ptrace(SYSCALL,10252):No such process>10253 ...next decode...
434 * 10252 died after we retrieved syscall exit data,
435 * but before we tried to restart it. Log looks ugly.
437 if (current_tcp && current_tcp->curcol != 0) {
438 tprintf(" <ptrace(%s):%s>\n", msg, strerror(err));
444 perror_msg("ptrace(PTRACE_%s,pid:%d,sig:%u)", msg, tcp->pid, sig);
449 set_cloexec_flag(int fd)
453 flags = fcntl(fd, F_GETFD);
455 /* Can happen only if fd is bad.
456 * Should never happen: if it does, we have a bug
457 * in the caller. Therefore we just abort
458 * instead of propagating the error.
460 perror_msg_and_die("fcntl(%d, F_GETFD)", fd);
463 newflags = flags | FD_CLOEXEC;
464 if (flags == newflags)
467 fcntl(fd, F_SETFD, newflags); /* never fails */
471 kill_save_errno(pid_t pid, int sig)
473 int saved_errno = errno;
475 (void) kill(pid, sig);
480 * When strace is setuid executable, we have to swap uids
481 * before and after filesystem and process management operations.
486 int euid = geteuid(), uid = getuid();
488 if (euid != uid && setreuid(euid, uid) < 0) {
489 perror_msg_and_die("setreuid");
493 #ifdef _LARGEFILE64_SOURCE
495 # define fopen_for_output fopen64
497 # define fopen_for_output fopen
499 # define struct_stat struct stat64
500 # define stat_file stat64
501 # define struct_dirent struct dirent64
502 # define read_dir readdir64
503 # define struct_rlimit struct rlimit64
504 # define set_rlimit setrlimit64
506 # define fopen_for_output fopen
507 # define struct_stat struct stat
508 # define stat_file stat
509 # define struct_dirent struct dirent
510 # define read_dir readdir
511 # define struct_rlimit struct rlimit
512 # define set_rlimit setrlimit
516 strace_fopen(const char *path)
521 fp = fopen_for_output(path, "w");
523 perror_msg_and_die("Can't fopen '%s'", path);
525 set_cloexec_flag(fileno(fp));
529 static int popen_pid;
532 # define _PATH_BSHELL "/bin/sh"
536 * We cannot use standard popen(3) here because we have to distinguish
537 * popen child process from other processes we trace, and standard popen(3)
538 * does not export its child's pid.
541 strace_popen(const char *command)
549 perror_msg_and_die("pipe");
551 set_cloexec_flag(fds[1]); /* never fails */
555 perror_msg_and_die("vfork");
562 perror_msg_and_die("dup2");
565 execl(_PATH_BSHELL, "sh", "-c", command, NULL);
566 perror_msg_and_die("Can't execute '%s'", _PATH_BSHELL);
573 fp = fdopen(fds[1], "w");
575 perror_msg_and_die("fdopen");
579 ATTRIBUTE_FORMAT((printf, 1, 0))
581 tvprintf(const char *const fmt, va_list args)
584 int n = vfprintf(current_tcp->outf, fmt, args);
586 if (current_tcp->outf != stderr)
587 perror_msg("%s", outfname);
589 current_tcp->curcol += n;
594 tprintf(const char *fmt, ...)
602 #ifndef HAVE_FPUTS_UNLOCKED
603 # define fputs_unlocked fputs
607 tprints(const char *str)
610 int n = fputs_unlocked(str, current_tcp->outf);
612 current_tcp->curcol += strlen(str);
615 if (current_tcp->outf != stderr)
616 perror_msg("%s", outfname);
621 tprints_comment(const char *const str)
624 tprintf(" /* %s */", str);
628 tprintf_comment(const char *fmt, ...)
645 current_tcp->curcol = 0;
646 fflush(current_tcp->outf);
649 printing_tcp->curcol = 0;
655 printleader(struct tcb *tcp)
657 /* If -ff, "previous tcb we printed" is always the same as current,
658 * because we have per-tcb output files.
664 current_tcp = printing_tcp;
665 if (printing_tcp->curcol != 0 && (followfork < 2 || printing_tcp == tcp)) {
667 * case 1: we have a shared log (i.e. not -ff), and last line
668 * wasn't finished (same or different tcb, doesn't matter).
669 * case 2: split log, we are the same tcb, but our last line
670 * didn't finish ("SIGKILL nuked us after syscall entry" etc).
672 tprints(" <unfinished ...>\n");
673 printing_tcp->curcol = 0;
679 current_tcp->curcol = 0;
682 tprintf("%-5d ", tcp->pid);
683 else if (nprocs > 1 && !outfname)
684 tprintf("[pid %5u] ", tcp->pid);
687 char str[sizeof("HH:MM:SS")];
688 struct timeval tv, dtv;
689 static struct timeval otv;
691 gettimeofday(&tv, NULL);
695 tv_sub(&dtv, &tv, &otv);
696 tprintf("%6ld.%06ld ",
697 (long) dtv.tv_sec, (long) dtv.tv_usec);
699 } else if (tflag > 2) {
700 tprintf("%ld.%06ld ",
701 (long) tv.tv_sec, (long) tv.tv_usec);
703 time_t local = tv.tv_sec;
704 strftime(str, sizeof(str), "%T", localtime(&local));
706 tprintf("%s.%06ld ", str, (long) tv.tv_usec);
718 if (current_tcp->curcol < acolumn)
719 tprints(acolumn_spaces + current_tcp->curcol);
722 /* Should be only called directly *after successful attach* to a tracee.
723 * Otherwise, "strace -oFILE -ff -p<nonexistant_pid>"
724 * may create bogus empty FILE.<nonexistant_pid>, and then die.
727 newoutf(struct tcb *tcp)
729 tcp->outf = shared_log; /* if not -ff mode, the same file is for all */
730 if (followfork >= 2) {
731 char name[520 + sizeof(int) * 3];
732 sprintf(name, "%.512s.%u", outfname, tcp->pid);
733 tcp->outf = strace_fopen(name);
740 /* Allocate some (more) TCBs (and expand the table).
741 We don't want to relocate the TCBs because our
742 callers have pointers and it would be a pain.
743 So tcbtab is a table of pointers. Since we never
744 free the TCBs, we allocate a single chunk of many. */
745 unsigned int new_tcbtabsize, alloc_tcbtabsize;
749 alloc_tcbtabsize = tcbtabsize;
750 new_tcbtabsize = tcbtabsize * 2;
752 new_tcbtabsize = alloc_tcbtabsize = 1;
755 newtcbs = xcalloc(alloc_tcbtabsize, sizeof(newtcbs[0]));
756 tcbtab = xreallocarray(tcbtab, new_tcbtabsize, sizeof(tcbtab[0]));
757 while (tcbtabsize < new_tcbtabsize)
758 tcbtab[tcbtabsize++] = newtcbs++;
767 if (nprocs == tcbtabsize)
770 for (i = 0; i < tcbtabsize; i++) {
773 memset(tcp, 0, sizeof(*tcp));
775 #if SUPPORTED_PERSONALITIES > 1
776 tcp->currpers = current_personality;
780 if (stack_trace_enabled)
781 unwind_tcb_init(tcp);
786 error_msg("new tcb for pid %d, active tcbs:%d",
791 error_msg_and_die("bug in alloctcb");
795 get_tcb_priv_data(const struct tcb *tcp)
797 return tcp->_priv_data;
801 set_tcb_priv_data(struct tcb *tcp, void *const priv_data,
802 void (*const free_priv_data)(void *))
807 tcp->_free_priv_data = free_priv_data;
808 tcp->_priv_data = priv_data;
814 free_tcb_priv_data(struct tcb *tcp)
816 if (tcp->_priv_data) {
817 if (tcp->_free_priv_data) {
818 tcp->_free_priv_data(tcp->_priv_data);
819 tcp->_free_priv_data = NULL;
821 tcp->_priv_data = NULL;
826 droptcb(struct tcb *tcp)
832 for (p = 0; p < SUPPORTED_PERSONALITIES; ++p)
833 free(tcp->inject_vec[p]);
835 free_tcb_priv_data(tcp);
838 if (stack_trace_enabled) {
845 error_msg("dropped tcb for pid %d, %d remain",
849 if (followfork >= 2) {
850 if (tcp->curcol != 0)
851 fprintf(tcp->outf, " <detached ...>\n");
854 if (printing_tcp == tcp && tcp->curcol != 0)
855 fprintf(tcp->outf, " <detached ...>\n");
860 if (current_tcp == tcp)
862 if (printing_tcp == tcp)
865 memset(tcp, 0, sizeof(*tcp));
868 /* Detach traced process.
869 * Never call DETACH twice on the same process as both unattached and
870 * attached-unstopped processes give the same ESRCH. For unattached process we
871 * would SIGSTOP it and wait for its SIGSTOP notification forever.
874 detach(struct tcb *tcp)
880 * Linux wrongly insists the child be stopped
881 * before detaching. Arghh. We go through hoops
882 * to make a clean break of things.
885 if (!(tcp->flags & TCB_ATTACHED))
888 /* We attached but possibly didn't see the expected SIGSTOP.
889 * We must catch exactly one as otherwise the detached process
890 * would be left stopped (process state T).
892 if (tcp->flags & TCB_IGNORE_ONE_SIGSTOP)
895 error = ptrace(PTRACE_DETACH, tcp->pid, 0, 0);
897 /* On a clear day, you can see forever. */
900 if (errno != ESRCH) {
901 /* Shouldn't happen. */
902 perror_msg("detach: ptrace(PTRACE_DETACH,%u)", tcp->pid);
905 /* ESRCH: process is either not stopped or doesn't exist. */
906 if (my_tkill(tcp->pid, 0) < 0) {
908 /* Shouldn't happen. */
909 perror_msg("detach: tkill(%u,0)", tcp->pid);
910 /* else: process doesn't exist. */
913 /* Process is not stopped, need to stop it. */
916 * With SEIZE, tracee can be in group-stop already.
917 * In this state sending it another SIGSTOP does nothing.
918 * Need to use INTERRUPT.
919 * Testcase: trying to ^C a "strace -p <stopped_process>".
921 error = ptrace(PTRACE_INTERRUPT, tcp->pid, 0, 0);
925 perror_msg("detach: ptrace(PTRACE_INTERRUPT,%u)", tcp->pid);
927 error = my_tkill(tcp->pid, SIGSTOP);
931 perror_msg("detach: tkill(%u,SIGSTOP)", tcp->pid);
933 /* Either process doesn't exist, or some weird error. */
937 /* We end up here in three cases:
938 * 1. We sent PTRACE_INTERRUPT (use_seize case)
939 * 2. We sent SIGSTOP (!use_seize)
940 * 3. Attach SIGSTOP was already pending (TCB_IGNORE_ONE_SIGSTOP set)
944 if (waitpid(tcp->pid, &status, __WALL) < 0) {
948 * if (errno == ECHILD) break;
949 * ^^^ WRONG! We expect this PID to exist,
950 * and want to emit a message otherwise:
952 perror_msg("detach: waitpid(%u)", tcp->pid);
955 if (!WIFSTOPPED(status)) {
957 * Tracee exited or was killed by signal.
958 * We shouldn't normally reach this place:
959 * we don't want to consume exit status.
960 * Consider "strace -p PID" being ^C-ed:
961 * we want merely to detach from PID.
963 * However, we _can_ end up here if tracee
968 sig = WSTOPSIG(status);
970 error_msg("detach wait: event:%d sig:%d",
971 (unsigned)status >> 16, sig);
973 unsigned event = (unsigned)status >> 16;
974 if (event == PTRACE_EVENT_STOP /*&& sig == SIGTRAP*/) {
976 * sig == SIGTRAP: PTRACE_INTERRUPT stop.
977 * sig == other: process was already stopped
978 * with this stopping sig (see tests/detach-stopped).
979 * Looks like re-injecting this sig is not necessary
980 * in DETACH for the tracee to remain stopped.
985 * PTRACE_INTERRUPT is not guaranteed to produce
986 * the above event if other ptrace-stop is pending.
987 * See tests/detach-sleeping testcase:
988 * strace got SIGINT while tracee is sleeping.
989 * We sent PTRACE_INTERRUPT.
990 * We see syscall exit, not PTRACE_INTERRUPT stop.
991 * We won't get PTRACE_INTERRUPT stop
992 * if we would CONT now. Need to DETACH.
994 if (sig == syscall_trap_sig)
996 /* else: not sure in which case we can be here.
997 * Signal stop? Inject it while detaching.
999 ptrace_restart(PTRACE_DETACH, tcp, sig);
1002 /* Note: this check has to be after use_seize check */
1003 /* (else, in use_seize case SIGSTOP will be mistreated) */
1004 if (sig == SIGSTOP) {
1005 /* Detach, suppressing SIGSTOP */
1006 ptrace_restart(PTRACE_DETACH, tcp, 0);
1009 if (sig == syscall_trap_sig)
1011 /* Can't detach just yet, may need to wait for SIGSTOP */
1012 error = ptrace_restart(PTRACE_CONT, tcp, sig);
1014 /* Should not happen.
1015 * Note: ptrace_restart returns 0 on ESRCH, so it's not it.
1016 * ptrace_restart already emitted error message.
1023 if (!qflag && (tcp->flags & TCB_ATTACHED))
1024 error_msg("Process %u detached", tcp->pid);
1030 process_opt_p_list(char *opt)
1034 * We accept -p PID,PID; -p "`pidof PROG`"; -p "`pgrep PROG`".
1035 * pidof uses space as delim, pgrep uses newline. :(
1038 char *delim = opt + strcspn(opt, "\n\t ,");
1042 pid = string_to_uint(opt);
1044 error_msg_and_die("Invalid process id: '%s'", opt);
1046 if (pid == strace_tracer_pid) {
1047 error_msg_and_die("I'm sorry, I can't let you do that, Dave.");
1058 attach_tcb(struct tcb *const tcp)
1060 if (ptrace_attach_or_seize(tcp->pid) < 0) {
1061 perror_msg("attach: ptrace(%s, %d)",
1062 ptrace_attach_cmd, tcp->pid);
1067 tcp->flags |= TCB_ATTACHED | TCB_STARTUP | post_attach_sigstop;
1070 error_msg("attach to pid %d (main) succeeded", tcp->pid);
1072 char procdir[sizeof("/proc/%d/task") + sizeof(int) * 3];
1074 unsigned int ntid = 0, nerr = 0;
1076 if (followfork && tcp->pid != strace_child &&
1077 sprintf(procdir, "/proc/%d/task", tcp->pid) > 0 &&
1078 (dir = opendir(procdir)) != NULL) {
1081 while ((de = read_dir(dir)) != NULL) {
1082 if (de->d_fileno == 0)
1085 int tid = string_to_uint(de->d_name);
1086 if (tid <= 0 || tid == tcp->pid)
1090 if (ptrace_attach_or_seize(tid) < 0) {
1093 perror_msg("attach: ptrace(%s, %d)",
1094 ptrace_attach_cmd, tid);
1098 error_msg("attach to pid %d succeeded", tid);
1100 struct tcb *tid_tcp = alloctcb(tid);
1101 tid_tcp->flags |= TCB_ATTACHED | TCB_STARTUP |
1102 post_attach_sigstop;
1111 error_msg("Process %u attached"
1113 tcp->pid, ntid - nerr + 1);
1115 error_msg("Process %u attached",
1121 startup_attach(void)
1123 pid_t parent_pid = strace_tracer_pid;
1128 * Block user interruptions as we would leave the traced
1129 * process stopped (process state T) if we would terminate in
1130 * between PTRACE_ATTACH and wait4() on SIGSTOP.
1131 * We rely on cleanup() from this point on.
1134 sigprocmask(SIG_SETMASK, &blocked_set, NULL);
1136 if (daemonized_tracer) {
1139 perror_msg_and_die("fork");
1141 if (pid) { /* parent */
1143 * Wait for grandchild to attach to straced process
1144 * (grandparent). Grandchild SIGKILLs us after it attached.
1145 * Grandparent's wait() is unblocked by our death,
1146 * it proceeds to exec the straced program.
1149 _exit(0); /* paranoia */
1152 /* We will be the tracer process. Remember our new pid: */
1153 strace_tracer_pid = getpid();
1156 for (tcbi = 0; tcbi < tcbtabsize; tcbi++) {
1162 /* Is this a process we should attach to, but not yet attached? */
1163 if (tcp->flags & TCB_ATTACHED)
1164 continue; /* no, we already attached it */
1166 if (tcp->pid == parent_pid || tcp->pid == strace_tracer_pid) {
1168 perror_msg("attach: pid %d", tcp->pid);
1176 sigprocmask(SIG_SETMASK, &start_set, NULL);
1179 sigprocmask(SIG_SETMASK, &blocked_set, NULL);
1181 } /* for each tcbtab[] */
1183 if (daemonized_tracer) {
1185 * Make parent go away.
1186 * Also makes grandparent's wait() unblock.
1188 kill(parent_pid, SIGKILL);
1194 sigprocmask(SIG_SETMASK, &start_set, NULL);
1197 /* Stack-o-phobic exec helper, in the hope to work around
1198 * NOMMU + "daemonized tracer" difficulty.
1200 struct exec_params {
1206 struct sigaction child_sa;
1208 static struct exec_params params_for_tracee;
1210 static void ATTRIBUTE_NOINLINE ATTRIBUTE_NORETURN
1213 struct exec_params *params = ¶ms_for_tracee;
1215 if (params->fd_to_close >= 0)
1216 close(params->fd_to_close);
1217 if (!daemonized_tracer && !use_seize) {
1218 if (ptrace(PTRACE_TRACEME, 0L, 0L, 0L) < 0) {
1219 perror_msg_and_die("ptrace(PTRACE_TRACEME, ...)");
1223 if (username != NULL) {
1225 * It is important to set groups before we
1226 * lose privileges on setuid.
1228 if (initgroups(username, run_gid) < 0) {
1229 perror_msg_and_die("initgroups");
1231 if (setregid(run_gid, params->run_egid) < 0) {
1232 perror_msg_and_die("setregid");
1234 if (setreuid(run_uid, params->run_euid) < 0) {
1235 perror_msg_and_die("setreuid");
1237 } else if (geteuid() != 0)
1238 if (setreuid(run_uid, run_uid) < 0) {
1239 perror_msg_and_die("setreuid");
1242 if (!daemonized_tracer) {
1244 * Induce a ptrace stop. Tracer (our parent)
1245 * will resume us with PTRACE_SYSCALL and display
1246 * the immediately following execve syscall.
1247 * Can't do this on NOMMU systems, we are after
1248 * vfork: parent is blocked, stopping would deadlock.
1251 kill(getpid(), SIGSTOP);
1254 /* we depend on SIGCHLD set to SIG_DFL by init code */
1255 /* if it happens to be SIG_IGN'ed, wait won't block */
1260 if (params_for_tracee.child_sa.sa_handler != SIG_DFL)
1261 sigaction(SIGCHLD, ¶ms_for_tracee.child_sa, NULL);
1263 execv(params->pathname, params->argv);
1264 perror_msg_and_die("exec");
1268 * Open a dummy descriptor for use as a placeholder.
1269 * The descriptor is O_RDONLY with FD_CLOEXEC flag set.
1270 * A read attempt from such descriptor ends with EOF,
1271 * a write attempt is rejected with EBADF.
1274 open_dummy_desc(void)
1279 perror_msg_and_die("pipe");
1281 set_cloexec_flag(fds[0]);
1285 /* placeholder fds status for stdin and stdout */
1286 static bool fd_is_placeholder[2];
1289 * Ensure that all standard file descriptors are open by opening placeholder
1290 * file descriptors for those standard file descriptors that are not open.
1292 * The information which descriptors have been made open is saved
1293 * in fd_is_placeholder for later use.
1296 ensure_standard_fds_opened(void)
1300 while ((fd = open_dummy_desc()) <= 2) {
1303 fd_is_placeholder[fd] = true;
1311 * Redirect stdin and stdout unless they have been opened earlier
1312 * by ensure_standard_fds_opened as placeholders.
1315 redirect_standard_fds(void)
1320 * It might be a good idea to redirect stderr as well,
1321 * but we sometimes need to print error messages.
1323 for (i = 0; i <= 1; ++i) {
1324 if (!fd_is_placeholder[i]) {
1332 startup_child(char **argv)
1334 struct_stat statbuf;
1335 const char *filename;
1336 size_t filename_len;
1337 char pathname[PATH_MAX];
1342 filename_len = strlen(filename);
1344 if (filename_len > sizeof(pathname) - 1) {
1345 errno = ENAMETOOLONG;
1346 perror_msg_and_die("exec");
1348 if (strchr(filename, '/')) {
1349 strcpy(pathname, filename);
1351 #ifdef USE_DEBUGGING_EXEC
1353 * Debuggers customarily check the current directory
1354 * first regardless of the path but doing that gives
1355 * security geeks a panic attack.
1357 else if (stat_file(filename, &statbuf) == 0)
1358 strcpy(pathname, filename);
1359 #endif /* USE_DEBUGGING_EXEC */
1364 for (path = getenv("PATH"); path && *path; path += m) {
1365 const char *colon = strchr(path, ':');
1370 m = n = strlen(path);
1372 if (!getcwd(pathname, PATH_MAX))
1374 len = strlen(pathname);
1375 } else if (n > sizeof(pathname) - 1)
1378 strncpy(pathname, path, n);
1381 if (len && pathname[len - 1] != '/')
1382 pathname[len++] = '/';
1383 if (filename_len + len > sizeof(pathname) - 1)
1385 strcpy(pathname + len, filename);
1386 if (stat_file(pathname, &statbuf) == 0 &&
1387 /* Accept only regular files
1388 with some execute bits set.
1389 XXX not perfect, might still fail */
1390 S_ISREG(statbuf.st_mode) &&
1391 (statbuf.st_mode & 0111))
1394 if (!path || !*path)
1397 if (stat_file(pathname, &statbuf) < 0) {
1398 perror_msg_and_die("Can't stat '%s'", filename);
1401 params_for_tracee.fd_to_close = (shared_log != stderr) ? fileno(shared_log) : -1;
1402 params_for_tracee.run_euid = (statbuf.st_mode & S_ISUID) ? statbuf.st_uid : run_uid;
1403 params_for_tracee.run_egid = (statbuf.st_mode & S_ISGID) ? statbuf.st_gid : run_gid;
1404 params_for_tracee.argv = argv;
1406 * On NOMMU, can be safely freed only after execve in tracee.
1407 * It's hard to know when that happens, so we just leak it.
1409 params_for_tracee.pathname = NOMMU_SYSTEM ? xstrdup(pathname) : pathname;
1411 #if defined HAVE_PRCTL && defined PR_SET_PTRACER && defined PR_SET_PTRACER_ANY
1412 if (daemonized_tracer)
1413 prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY);
1418 perror_msg_and_die("fork");
1420 if ((pid != 0 && daemonized_tracer)
1421 || (pid == 0 && !daemonized_tracer)
1423 /* We are to become the tracee. Two cases:
1425 * not -D: we are child
1430 /* We are the tracer */
1432 if (!daemonized_tracer) {
1435 /* child did PTRACE_TRACEME, nothing to do in parent */
1437 if (!NOMMU_SYSTEM) {
1438 /* Wait until child stopped itself */
1440 while (waitpid(pid, &status, WSTOPPED) < 0) {
1443 perror_msg_and_die("waitpid");
1445 if (!WIFSTOPPED(status) || WSTOPSIG(status) != SIGSTOP) {
1446 kill_save_errno(pid, SIGKILL);
1447 perror_msg_and_die("Unexpected wait status %#x",
1451 /* Else: NOMMU case, we have no way to sync.
1452 * Just attach to it as soon as possible.
1453 * This means that we may miss a few first syscalls...
1456 if (ptrace_attach_or_seize(pid)) {
1457 kill_save_errno(pid, SIGKILL);
1458 perror_msg_and_die("attach: ptrace(%s, %d)",
1459 ptrace_attach_cmd, pid);
1464 tcp = alloctcb(pid);
1465 tcp->flags |= TCB_ATTACHED | TCB_STARTUP
1466 | TCB_SKIP_DETACH_ON_FIRST_EXEC
1467 | (NOMMU_SYSTEM ? 0 : (TCB_HIDE_LOG | post_attach_sigstop));
1470 /* With -D, we are *child* here, the tracee is our parent. */
1471 strace_child = strace_tracer_pid;
1472 strace_tracer_pid = getpid();
1473 tcp = alloctcb(strace_child);
1474 tcp->flags |= TCB_SKIP_DETACH_ON_FIRST_EXEC | TCB_HIDE_LOG;
1475 /* attaching will be done later, by startup_attach */
1476 /* note: we don't do newoutf(tcp) here either! */
1478 /* NOMMU BUG! -D mode is active, we (child) return,
1479 * and we will scribble over parent's stack!
1480 * When parent later unpauses, it segfaults.
1483 * (1) by declaring exec_or_die() NORETURN,
1484 * hopefully compiler will just jump to it
1485 * instead of call (won't push anything to stack),
1486 * (2) by trying very hard in exec_or_die()
1487 * to not use any stack,
1488 * (3) having a really big (PATH_MAX) stack object
1489 * in this function, which creates a "buffer" between
1490 * child's and parent's stack pointers.
1491 * This may save us if (1) and (2) failed
1492 * and compiler decided to use stack in exec_or_die() anyway
1493 * (happens on i386 because of stack parameter passing).
1495 * A cleaner solution is to use makecontext + setcontext
1496 * to create a genuine separate stack and execute on it.
1500 * A case where straced process is part of a pipe:
1501 * { sleep 1; yes | head -n99999; } | strace -o/dev/null sh -c 'exec <&-; sleep 9'
1502 * If strace won't close its fd#0, closing it in tracee is not enough:
1503 * the pipe is still open, it has a reader. Thus, "head" will not get its
1504 * SIGPIPE at once, on the first write.
1506 * Preventing it by redirecting strace's stdin/out.
1507 * (Don't leave fds 0 and 1 closed, this is bad practice: future opens
1508 * will reuse them, unexpectedly making a newly opened object "stdin").
1510 redirect_standard_fds();
1515 test_ptrace_seize(void)
1519 /* Need fork for test. NOMMU has no forks */
1521 post_attach_sigstop = 0; /* this sets use_seize to 1 */
1527 perror_msg_and_die("fork");
1534 /* PTRACE_SEIZE, unlike ATTACH, doesn't force tracee to trap. After
1535 * attaching tracee continues to run unless a trap condition occurs.
1536 * PTRACE_SEIZE doesn't affect signal or group stop state.
1538 if (ptrace(PTRACE_SEIZE, pid, 0, 0) == 0) {
1539 post_attach_sigstop = 0; /* this sets use_seize to 1 */
1540 } else if (debug_flag) {
1541 error_msg("PTRACE_SEIZE doesn't work");
1547 int status, tracee_pid;
1550 tracee_pid = waitpid(pid, &status, 0);
1551 if (tracee_pid <= 0) {
1554 perror_msg_and_die("%s: unexpected wait result %d",
1555 __func__, tracee_pid);
1557 if (WIFSIGNALED(status)) {
1560 error_msg_and_die("%s: unexpected wait status %#x",
1564 #else /* !USE_SEIZE */
1565 # define test_ptrace_seize() ((void)0)
1569 get_os_release(void)
1575 perror_msg_and_die("uname");
1576 /* u.release has this form: "3.2.9[-some-garbage]" */
1580 if (!(*p >= '0' && *p <= '9'))
1581 error_msg_and_die("Bad OS release string: '%s'", u.release);
1582 /* Note: this open-codes KERNEL_VERSION(): */
1583 rel = (rel << 8) | atoi(p);
1584 if (rel >= KERNEL_VERSION(1, 0, 0))
1586 while (*p >= '0' && *p <= '9')
1589 if (rel >= KERNEL_VERSION(0, 1, 0)) {
1590 /* "X.Y-something" means "X.Y.0" */
1594 error_msg_and_die("Bad OS release string: '%s'", u.release);
1602 set_sigaction(int signo, void (*sighandler)(int), struct sigaction *oldact)
1604 /* if signal handler is a function, add the signal to blocked_set */
1605 if (sighandler != SIG_IGN && sighandler != SIG_DFL)
1606 sigaddset(&blocked_set, signo);
1608 const struct sigaction sa = { .sa_handler = sighandler };
1609 sigaction(signo, &sa, oldact);
1613 * Initialization part of main() was eating much stack (~0.5k),
1614 * which was unused after init.
1615 * We can reuse it if we move init code into a separate function.
1617 * Don't want main() to inline us and defeat the reason
1618 * we have a separate function.
1620 static void ATTRIBUTE_NOINLINE
1621 init(int argc, char *argv[])
1626 if (!program_invocation_name || !*program_invocation_name) {
1627 static char name[] = "strace";
1628 program_invocation_name =
1629 (argv[0] && *argv[0]) ? argv[0] : name;
1632 strace_tracer_pid = getpid();
1634 os_release = get_os_release();
1636 shared_log = stderr;
1637 set_sortby(DEFAULT_SORTBY);
1638 set_personality(DEFAULT_PERSONALITY);
1639 qualify("trace=all");
1640 qualify("abbrev=all");
1641 qualify("verbose=all");
1642 #if DEFAULT_QUAL_FLAGS != (QUAL_TRACE | QUAL_ABBREV | QUAL_VERBOSE)
1643 # error Bug in DEFAULT_QUAL_FLAGS
1645 qualify("signal=all");
1646 while ((c = getopt(argc, argv,
1647 "+b:cCdfFhiqrtTvVwxyz"
1648 #ifdef USE_LIBUNWIND
1652 "a:e:o:O:p:s:S:u:E:P:I:")) != EOF) {
1655 if (strcmp(optarg, "execve") != 0)
1656 error_msg_and_die("Syscall '%s' for -b isn't supported",
1658 detach_on_execve = 1;
1661 if (cflag == CFLAG_BOTH) {
1662 error_msg_and_help("-c and -C are mutually exclusive");
1664 cflag = CFLAG_ONLY_STATS;
1667 if (cflag == CFLAG_ONLY_STATS) {
1668 error_msg_and_help("-c and -C are mutually exclusive");
1676 daemonized_tracer = 1;
1703 count_wallclock = 1;
1712 qualify("abbrev=none");
1719 not_failing_only = 1;
1722 acolumn = string_to_uint(optarg);
1724 error_opt_arg(c, optarg);
1730 outfname = xstrdup(optarg);
1733 i = string_to_uint(optarg);
1735 error_opt_arg(c, optarg);
1739 process_opt_p_list(optarg);
1742 pathtrace_select(optarg);
1745 i = string_to_uint(optarg);
1746 if (i < 0 || (unsigned int) i > -1U / 4)
1747 error_opt_arg(c, optarg);
1754 username = xstrdup(optarg);
1756 #ifdef USE_LIBUNWIND
1758 stack_trace_enabled = true;
1762 if (putenv(optarg) < 0)
1763 perror_msg_and_die("putenv");
1766 opt_intr = string_to_uint_upto(optarg, NUM_INTR_OPTS - 1);
1768 error_opt_arg(c, optarg);
1771 error_msg_and_help(NULL);
1779 if (argc < 0 || (!argv[0] && !nprocs)) {
1780 error_msg_and_help("must have PROG [ARGS] or -p PID");
1783 if (!argv[0] && daemonized_tracer) {
1784 error_msg_and_help("PROG [ARGS] must be specified with -D");
1790 if (followfork >= 2 && cflag) {
1791 error_msg_and_help("(-c or -C) and -ff are mutually exclusive");
1794 if (count_wallclock && !cflag) {
1795 error_msg_and_help("-w must be given with (-c or -C)");
1798 if (cflag == CFLAG_ONLY_STATS) {
1800 error_msg("-%c has no effect with -c", 'i');
1801 #ifdef USE_LIBUNWIND
1802 if (stack_trace_enabled)
1803 error_msg("-%c has no effect with -c", 'k');
1806 error_msg("-%c has no effect with -c", 'r');
1808 error_msg("-%c has no effect with -c", 't');
1810 error_msg("-%c has no effect with -c", 'T');
1812 error_msg("-%c has no effect with -c", 'y');
1817 error_msg("-tt has no effect with -r");
1821 acolumn_spaces = xmalloc(acolumn + 1);
1822 memset(acolumn_spaces, ' ', acolumn);
1823 acolumn_spaces[acolumn] = '\0';
1825 sigprocmask(SIG_SETMASK, NULL, &start_set);
1826 memcpy(&blocked_set, &start_set, sizeof(blocked_set));
1828 set_sigaction(SIGCHLD, SIG_DFL, ¶ms_for_tracee.child_sa);
1830 #ifdef USE_LIBUNWIND
1831 if (stack_trace_enabled) {
1835 for (tcbi = 0; tcbi < tcbtabsize; ++tcbi) {
1836 unwind_tcb_init(tcbtab[tcbi]);
1841 /* See if they want to run as another user. */
1842 if (username != NULL) {
1843 struct passwd *pent;
1845 if (getuid() != 0 || geteuid() != 0) {
1846 error_msg_and_die("You must be root to use the -u option");
1848 pent = getpwnam(username);
1850 error_msg_and_die("Cannot find user '%s'", username);
1852 run_uid = pent->pw_uid;
1853 run_gid = pent->pw_gid;
1860 ptrace_setoptions |= PTRACE_O_TRACECLONE |
1861 PTRACE_O_TRACEFORK |
1862 PTRACE_O_TRACEVFORK;
1864 error_msg("ptrace_setoptions = %#x", ptrace_setoptions);
1865 test_ptrace_seize();
1868 * Is something weird with our stdin and/or stdout -
1869 * for example, may they be not open? In this case,
1870 * ensure that none of the future opens uses them.
1872 * This was seen in the wild when /proc/sys/kernel/core_pattern
1873 * was set to "|/bin/strace -o/tmp/LOG PROG":
1874 * kernel runs coredump helper with fd#0 open but fd#1 closed (!),
1875 * therefore LOG gets opened to fd#1, and fd#1 is closed by
1876 * "don't hold up stdin/out open" code soon after.
1878 ensure_standard_fds_opened();
1880 /* Check if they want to redirect the output. */
1882 /* See if they want to pipe the output. */
1883 if (outfname[0] == '|' || outfname[0] == '!') {
1885 * We can't do the <outfname>.PID funny business
1886 * when using popen, so prohibit it.
1888 if (followfork >= 2)
1889 error_msg_and_help("piping the output and -ff are mutually exclusive");
1890 shared_log = strace_popen(outfname + 1);
1891 } else if (followfork < 2)
1892 shared_log = strace_fopen(outfname);
1894 /* -ff without -o FILE is the same as single -f */
1895 if (followfork >= 2)
1899 if (!outfname || outfname[0] == '|' || outfname[0] == '!') {
1900 setvbuf(shared_log, NULL, _IOLBF, 0);
1904 * argv[0] -pPID -oFILE Default interactive setting
1905 * yes * 0 INTR_WHILE_WAIT
1906 * no 1 0 INTR_WHILE_WAIT
1907 * yes * 1 INTR_NEVER
1908 * no 1 1 INTR_WHILE_WAIT
1911 if (outfname && argv[0]) {
1913 opt_intr = INTR_NEVER;
1918 opt_intr = INTR_WHILE_WAIT;
1921 * startup_child() must be called before the signal handlers get
1922 * installed below as they are inherited into the spawned process.
1923 * Also we do not need to be protected by them as during interruption
1924 * in the startup_child() mode we kill the spawned process anyway.
1927 startup_child(argv);
1930 set_sigaction(SIGTTOU, SIG_IGN, NULL);
1931 set_sigaction(SIGTTIN, SIG_IGN, NULL);
1932 if (opt_intr != INTR_ANYWHERE) {
1933 if (opt_intr == INTR_BLOCK_TSTP_TOO)
1934 set_sigaction(SIGTSTP, SIG_IGN, NULL);
1936 * In interactive mode (if no -o OUTFILE, or -p PID is used),
1937 * fatal signals are blocked while syscall stop is processed,
1938 * and acted on in between, when waiting for new syscall stops.
1939 * In non-interactive mode, signals are ignored.
1941 set_sigaction(SIGHUP, interactive ? interrupt : SIG_IGN, NULL);
1942 set_sigaction(SIGINT, interactive ? interrupt : SIG_IGN, NULL);
1943 set_sigaction(SIGQUIT, interactive ? interrupt : SIG_IGN, NULL);
1944 set_sigaction(SIGPIPE, interactive ? interrupt : SIG_IGN, NULL);
1945 set_sigaction(SIGTERM, interactive ? interrupt : SIG_IGN, NULL);
1948 if (nprocs != 0 || daemonized_tracer)
1951 /* Do we want pids printed in our -o OUTFILE?
1952 * -ff: no (every pid has its own file); or
1953 * -f: yes (there can be more pids in the future); or
1954 * -p PID1,PID2: yes (there are already more than one pid)
1956 print_pid_pfx = (outfname && followfork < 2 && (followfork == 1 || nprocs > 1));
1967 for (i = 0; i < tcbtabsize; i++) {
1968 struct tcb *tcp = tcbtab[i];
1969 if (tcp->pid == pid)
1983 /* 'interrupted' is a volatile object, fetch it only once */
1984 fatal_sig = interrupted;
1986 fatal_sig = SIGTERM;
1988 for (i = 0; i < tcbtabsize; i++) {
1993 error_msg("cleanup: looking at pid %u", tcp->pid);
1994 if (tcp->pid == strace_child) {
1995 kill(tcp->pid, SIGCONT);
1996 kill(tcp->pid, fatal_sig);
2001 call_summary(shared_log);
2011 print_debug_info(const int pid, int status)
2013 const unsigned int event = (unsigned int) status >> 16;
2014 char buf[sizeof("WIFEXITED,exitcode=%u") + sizeof(int)*3 /*paranoia:*/ + 16];
2015 char evbuf[sizeof(",EVENT_VFORK_DONE (%u)") + sizeof(int)*3 /*paranoia:*/ + 16];
2018 if (WIFSIGNALED(status))
2020 sprintf(buf, "WIFSIGNALED,%ssig=%s",
2021 WCOREDUMP(status) ? "core," : "",
2022 signame(WTERMSIG(status)));
2024 sprintf(buf, "WIFSIGNALED,sig=%s",
2025 signame(WTERMSIG(status)));
2027 if (WIFEXITED(status))
2028 sprintf(buf, "WIFEXITED,exitcode=%u", WEXITSTATUS(status));
2029 if (WIFSTOPPED(status))
2030 sprintf(buf, "WIFSTOPPED,sig=%s", signame(WSTOPSIG(status)));
2033 static const char *const event_names[] = {
2034 [PTRACE_EVENT_CLONE] = "CLONE",
2035 [PTRACE_EVENT_FORK] = "FORK",
2036 [PTRACE_EVENT_VFORK] = "VFORK",
2037 [PTRACE_EVENT_VFORK_DONE] = "VFORK_DONE",
2038 [PTRACE_EVENT_EXEC] = "EXEC",
2039 [PTRACE_EVENT_EXIT] = "EXIT",
2040 /* [PTRACE_EVENT_STOP (=128)] would make biggish array */
2042 const char *e = "??";
2043 if (event < ARRAY_SIZE(event_names))
2044 e = event_names[event];
2045 else if (event == PTRACE_EVENT_STOP)
2047 sprintf(evbuf, ",EVENT_%s (%u)", e, event);
2049 error_msg("[wait(0x%06x) = %u] %s%s", status, pid, buf, evbuf);
2053 maybe_allocate_tcb(const int pid, int status)
2055 if (!WIFSTOPPED(status)) {
2056 if (detach_on_execve && pid == strace_child) {
2057 /* example: strace -bexecve sh -c 'exec true' */
2062 * This can happen if we inherited an unknown child.
2063 * Example: (sleep 1 & exec strace true)
2065 error_msg("Exit of unknown pid %u ignored", pid);
2069 /* We assume it's a fork/vfork/clone child */
2070 struct tcb *tcp = alloctcb(pid);
2071 tcp->flags |= TCB_ATTACHED | TCB_STARTUP | post_attach_sigstop;
2074 error_msg("Process %d attached", pid);
2077 /* This can happen if a clone call used
2078 * CLONE_PTRACE itself.
2080 ptrace(PTRACE_CONT, pid, NULL, 0);
2081 error_msg("Stop of unknown pid %u seen, PTRACE_CONTed it", pid);
2087 maybe_switch_tcbs(struct tcb *tcp, const int pid)
2090 struct tcb *execve_thread;
2093 if (ptrace(PTRACE_GETEVENTMSG, pid, NULL, &old_pid) < 0)
2095 /* Avoid truncation in pid2tcb() param passing */
2096 if (old_pid <= 0 || old_pid == pid)
2098 if ((unsigned long) old_pid > UINT_MAX)
2100 execve_thread = pid2tcb(old_pid);
2101 /* It should be !NULL, but I feel paranoid */
2105 if (execve_thread->curcol != 0) {
2107 * One case we are here is -ff:
2108 * try "strace -oLOG -ff test/threaded_execve"
2110 fprintf(execve_thread->outf, " <pid changed to %d ...>\n", pid);
2111 /*execve_thread->curcol = 0; - no need, see code below */
2113 /* Swap output FILEs (needed for -ff) */
2114 fp = execve_thread->outf;
2115 execve_thread->outf = tcp->outf;
2117 /* And their column positions */
2118 execve_thread->curcol = tcp->curcol;
2120 /* Drop leader, but close execve'd thread outfile (if -ff) */
2122 /* Switch to the thread, reusing leader's outfile and pid */
2123 tcp = execve_thread;
2125 if (cflag != CFLAG_ONLY_STATS) {
2127 tprintf("+++ superseded by execve in pid %lu +++\n", old_pid);
2129 tcp->flags |= TCB_REPRINT;
2136 print_signalled(struct tcb *tcp, const int pid, int status)
2138 if (pid == strace_child) {
2139 exit_code = 0x100 | WTERMSIG(status);
2143 if (cflag != CFLAG_ONLY_STATS
2144 && is_number_in_set(WTERMSIG(status), &signal_set)) {
2147 tprintf("+++ killed by %s %s+++\n",
2148 signame(WTERMSIG(status)),
2149 WCOREDUMP(status) ? "(core dumped) " : "");
2151 tprintf("+++ killed by %s +++\n",
2152 signame(WTERMSIG(status)));
2159 print_exited(struct tcb *tcp, const int pid, int status)
2161 if (pid == strace_child) {
2162 exit_code = WEXITSTATUS(status);
2166 if (cflag != CFLAG_ONLY_STATS &&
2169 tprintf("+++ exited with %d +++\n", WEXITSTATUS(status));
2175 print_stopped(struct tcb *tcp, const siginfo_t *si, const unsigned int sig)
2177 if (cflag != CFLAG_ONLY_STATS
2179 && is_number_in_set(sig, &signal_set)) {
2182 tprintf("--- %s ", signame(sig));
2186 tprintf("--- stopped by %s ---\n", signame(sig));
2192 startup_tcb(struct tcb *tcp)
2195 error_msg("pid %d has TCB_STARTUP, initializing it", tcp->pid);
2197 tcp->flags &= ~TCB_STARTUP;
2201 error_msg("setting opts 0x%x on pid %d",
2202 ptrace_setoptions, tcp->pid);
2203 if (ptrace(PTRACE_SETOPTIONS, tcp->pid, NULL, ptrace_setoptions) < 0) {
2204 if (errno != ESRCH) {
2205 /* Should never happen, really */
2206 perror_msg_and_die("PTRACE_SETOPTIONS");
2211 if (get_scno(tcp) == 1)
2212 tcp->s_prev_ent = tcp->s_ent;
2216 print_event_exit(struct tcb *tcp)
2218 if (entering(tcp) || filtered(tcp) || hide_log(tcp)
2219 || cflag == CFLAG_ONLY_STATS) {
2223 if (followfork < 2 && printing_tcp && printing_tcp != tcp
2224 && printing_tcp->curcol != 0) {
2225 current_tcp = printing_tcp;
2226 tprints(" <unfinished ...>\n");
2227 fflush(printing_tcp->outf);
2228 printing_tcp->curcol = 0;
2232 if ((followfork < 2 && printing_tcp != tcp)
2233 || (tcp->flags & TCB_REPRINT)) {
2234 tcp->flags &= ~TCB_REPRINT;
2236 tprintf("<... %s resumed>", tcp->s_ent->sys_name);
2239 if (!(tcp->sys_func_rval & RVAL_DECODED)) {
2241 * The decoder has probably decided to print something
2242 * on exiting syscall which is not going to happen.
2244 tprints(" <unfinished ...>");
2253 /* Break the main loop. */
2256 /* Call next_event() again. */
2259 /* Restart the tracee with signal 0 and call next_event() again. */
2263 * For all the events below, current_tcp is set to current tracee's
2264 * tcb. All the suggested actions imply that you want to continue
2265 * tracing of the current tracee; alternatively, you can detach it.
2269 * Syscall entry or exit.
2270 * Restart the tracee with signal 0, or with an injected signal number.
2275 * Tracee received signal with number WSTOPSIG(*pstatus); signal info
2276 * is written to *si. Restart the tracee (with that signal number
2277 * if you want to deliver it).
2279 TE_SIGNAL_DELIVERY_STOP,
2282 * Tracee was killed by a signal with number WTERMSIG(*pstatus).
2287 * Tracee was stopped by a signal with number WSTOPSIG(*pstatus).
2288 * Restart the tracee with that signal number.
2293 * Tracee exited with status WEXITSTATUS(*pstatus).
2298 * Tracee is going to perform execve().
2299 * Restart the tracee with signal 0.
2301 TE_STOP_BEFORE_EXECVE,
2304 * Tracee is going to terminate.
2305 * Restart the tracee with signal 0.
2307 TE_STOP_BEFORE_EXIT,
2310 static enum trace_event
2311 next_event(int *pstatus, siginfo_t *si)
2323 * Used to exit simply when nprocs hits zero, but in this testcase:
2324 * int main(void) { _exit(!!fork()); }
2325 * under strace -f, parent sometimes (rarely) manages
2326 * to exit before we see the first stop of the child,
2327 * and we are losing track of it:
2328 * 19923 clone(...) = 19924
2329 * 19923 exit_group(1) = ?
2330 * 19923 +++ exited with 1 +++
2331 * Exiting only when wait() returns ECHILD works better.
2333 if (popen_pid != 0) {
2334 /* However, if -o|logger is in use, we can't do that.
2335 * Can work around that by double-forking the logger,
2336 * but that loses the ability to wait for its completion
2337 * on exit. Oh well...
2344 sigprocmask(SIG_SETMASK, &start_set, NULL);
2345 pid = wait4(-1, pstatus, __WALL, (cflag ? &ru : NULL));
2348 sigprocmask(SIG_SETMASK, &blocked_set, NULL);
2351 if (wait_errno == EINTR)
2353 if (nprocs == 0 && wait_errno == ECHILD)
2356 * If nprocs > 0, ECHILD is not expected,
2357 * treat it as any other error here:
2360 perror_msg_and_die("wait4(__WALL)");
2365 if (pid == popen_pid) {
2366 if (!WIFSTOPPED(status))
2372 print_debug_info(pid, status);
2374 /* Look up 'pid' in our table. */
2378 tcp = maybe_allocate_tcb(pid, status);
2385 /* Set current output file */
2389 tv_sub(&tcp->dtime, &ru.ru_stime, &tcp->stime);
2390 tcp->stime = ru.ru_stime;
2393 if (WIFSIGNALED(status))
2394 return TE_SIGNALLED;
2396 if (WIFEXITED(status))
2400 * As WCONTINUED flag has not been specified to wait4,
2401 * it cannot be WIFCONTINUED(status), so the only case
2402 * that remains is WIFSTOPPED(status).
2405 /* Is this the very first time we see this tracee stopped? */
2406 if (tcp->flags & TCB_STARTUP)
2409 const unsigned int sig = WSTOPSIG(status);
2410 const unsigned int event = (unsigned int) status >> 16;
2415 * Is this post-attach SIGSTOP?
2416 * Interestingly, the process may stop
2417 * with STOPSIG equal to some other signal
2418 * than SIGSTOP if we happened to attach
2419 * just before the process takes a signal.
2421 if (sig == SIGSTOP && (tcp->flags & TCB_IGNORE_ONE_SIGSTOP)) {
2423 error_msg("ignored SIGSTOP on pid %d", tcp->pid);
2424 tcp->flags &= ~TCB_IGNORE_ONE_SIGSTOP;
2426 } else if (sig == syscall_trap_sig) {
2427 return TE_SYSCALL_STOP;
2429 *si = (siginfo_t) {};
2431 * True if tracee is stopped by signal
2432 * (as opposed to "tracee received signal").
2433 * TODO: shouldn't we check for errno == EINVAL too?
2434 * We can get ESRCH instead, you know...
2436 bool stopped = ptrace(PTRACE_GETSIGINFO, pid, 0, si) < 0;
2437 return stopped ? TE_GROUP_STOP : TE_SIGNAL_DELIVERY_STOP;
2441 case PTRACE_EVENT_STOP:
2443 * PTRACE_INTERRUPT-stop or group-stop.
2444 * PTRACE_INTERRUPT-stop has sig == SIGTRAP here.
2451 return TE_GROUP_STOP;
2455 case PTRACE_EVENT_EXEC:
2456 return TE_STOP_BEFORE_EXECVE;
2457 case PTRACE_EVENT_EXIT:
2458 return TE_STOP_BEFORE_EXIT;
2465 trace_syscall(struct tcb *tcp, unsigned int *sig)
2467 if (entering(tcp)) {
2468 int res = syscall_entering_decode(tcp);
2473 res = syscall_entering_trace(tcp, sig);
2475 syscall_entering_finish(tcp, res);
2478 struct timeval tv = {};
2479 int res = syscall_exiting_decode(tcp, &tv);
2481 res = syscall_exiting_trace(tcp, tv, res);
2483 syscall_exiting_finish(tcp);
2488 /* Returns true iff the main trace loop has to continue. */
2490 dispatch_event(enum trace_event ret, int *pstatus, siginfo_t *si)
2492 unsigned int restart_op = PTRACE_SYSCALL;
2493 unsigned int restart_sig = 0;
2505 case TE_SYSCALL_STOP:
2506 if (trace_syscall(current_tcp, &restart_sig) < 0) {
2508 * ptrace() failed in trace_syscall().
2509 * Likely a result of process disappearing mid-flight.
2510 * Observed case: exit_group() or SIGKILL terminating
2511 * all processes in thread group.
2512 * We assume that ptrace error was caused by process death.
2513 * We used to detach(current_tcp) here, but since we no
2514 * longer implement "detach before death" policy/hack,
2515 * we can let this process to report its death to us
2516 * normally, via WIFEXITED or WIFSIGNALED wait status.
2522 case TE_SIGNAL_DELIVERY_STOP:
2523 restart_sig = WSTOPSIG(*pstatus);
2524 print_stopped(current_tcp, si, restart_sig);
2528 print_signalled(current_tcp, current_tcp->pid, *pstatus);
2529 droptcb(current_tcp);
2533 restart_sig = WSTOPSIG(*pstatus);
2534 print_stopped(current_tcp, NULL, restart_sig);
2537 * This ends ptrace-stop, but does *not* end group-stop.
2538 * This makes stopping signals work properly on straced
2539 * process (that is, process really stops. It used to
2542 restart_op = PTRACE_LISTEN;
2548 print_exited(current_tcp, current_tcp->pid, *pstatus);
2549 droptcb(current_tcp);
2552 case TE_STOP_BEFORE_EXECVE:
2554 * Under Linux, execve changes pid to thread leader's pid,
2555 * and we see this changed pid on EVENT_EXEC and later,
2556 * execve sysexit. Leader "disappears" without exit
2557 * notification. Let user know that, drop leader's tcb,
2558 * and fix up pid in execve thread's tcb.
2559 * Effectively, execve thread's tcb replaces leader's tcb.
2561 * BTW, leader is 'stuck undead' (doesn't report WIFEXITED
2562 * on exit syscall) in multithreaded programs exactly
2563 * in order to handle this case.
2565 * PTRACE_GETEVENTMSG returns old pid starting from Linux 3.0.
2566 * On 2.6 and earlier, it can return garbage.
2568 if (os_release >= KERNEL_VERSION(3, 0, 0))
2569 current_tcp = maybe_switch_tcbs(current_tcp, current_tcp->pid);
2571 if (detach_on_execve) {
2572 if (current_tcp->flags & TCB_SKIP_DETACH_ON_FIRST_EXEC) {
2573 current_tcp->flags &= ~TCB_SKIP_DETACH_ON_FIRST_EXEC;
2575 detach(current_tcp); /* do "-b execve" thingy */
2581 case TE_STOP_BEFORE_EXIT:
2582 print_event_exit(current_tcp);
2586 /* We handled quick cases, we are permitted to interrupt now. */
2590 if (ptrace_restart(restart_op, current_tcp, restart_sig) < 0) {
2591 /* Note: ptrace_restart emitted error message */
2598 #ifdef ENABLE_COVERAGE_GCOV
2599 extern void __gcov_flush(void);
2602 static void ATTRIBUTE_NORETURN
2607 if (shared_log != stderr)
2610 while (waitpid(popen_pid, NULL, 0) < 0 && errno == EINTR)
2613 if (exit_code > 0xff) {
2614 /* Avoid potential core file clobbering. */
2615 struct_rlimit rlim = {0, 0};
2616 set_rlimit(RLIMIT_CORE, &rlim);
2618 /* Child was killed by a signal, mimic that. */
2620 signal(exit_code, SIG_DFL);
2621 #ifdef ENABLE_COVERAGE_GCOV
2626 /* Unblock the signal. */
2629 sigaddset(&mask, exit_code);
2630 #ifdef ENABLE_COVERAGE_GCOV
2633 sigprocmask(SIG_UNBLOCK, &mask, NULL);
2635 /* Paranoia - what if this signal is not fatal?
2636 Exit with 128 + signo then. */
2643 main(int argc, char *argv[])
2647 exit_code = !nprocs;
2651 while (dispatch_event(next_event(&status, &si), &status, &si))