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>
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. The name of the author may not be used to endorse or promote products
17 * derived from this software without specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 #include <sys/param.h>
35 #include <sys/resource.h>
41 #include <sys/utsname.h>
43 # include <sys/prctl.h>
46 # include <asm/ptrace_offsets.h>
48 /* In some libc, these aren't declared. Do it ourself: */
49 extern char **environ;
54 #if defined __NR_tkill
55 # define my_tkill(tid, sig) syscall(__NR_tkill, (tid), (sig))
57 /* kill() may choose arbitrarily the target task of the process group
58 while we later wait on a that specific TID. PID process waits become
59 TID task specific waits for a process under ptrace(2). */
60 # warning "tkill(2) not available, risk of strace hangs!"
61 # define my_tkill(tid, sig) kill((tid), (sig))
64 /* Glue for systems without a MMU that cannot provide fork() */
65 #if !defined(HAVE_FORK)
67 # define NOMMU_SYSTEM 1
70 # define fork() vfork()
73 cflag_t cflag = CFLAG_NONE;
74 unsigned int followfork = 0;
75 unsigned int ptrace_setoptions = 0;
76 unsigned int xflag = 0;
77 bool need_fork_exec_workarounds = 0;
81 bool count_wallclock = 0;
82 unsigned int qflag = 0;
83 /* Which WSTOPSIG(status) value marks syscall traps? */
84 static unsigned int syscall_trap_sig = SIGTRAP;
85 static unsigned int tflag = 0;
86 static bool rflag = 0;
87 static bool print_pid_pfx = 0;
92 INTR_ANYWHERE = 1, /* don't block/ignore any signals */
93 INTR_WHILE_WAIT = 2, /* block fatal signals while decoding syscall. default */
94 INTR_NEVER = 3, /* block fatal signals. default if '-o FILE PROG' */
95 INTR_BLOCK_TSTP_TOO = 4, /* block fatal signals and SIGTSTP (^Z) */
99 /* We play with signal mask only if this mode is active: */
100 #define interactive (opt_intr == INTR_WHILE_WAIT)
103 * daemonized_tracer supports -D option.
104 * With this option, strace forks twice.
105 * Unlike normal case, with -D *grandparent* process exec's,
106 * becoming a traced process. Child exits (this prevents traced process
107 * from having children it doesn't expect to have), and grandchild
108 * attaches to grandparent similarly to strace -p PID.
109 * This allows for more transparent interaction in cases
110 * when process and its parent are communicating via signals,
111 * wait() etc. Without -D, strace process gets lodged in between,
112 * disrupting parent<->child link.
114 static bool daemonized_tracer = 0;
117 static int post_attach_sigstop = TCB_IGNORE_ONE_SIGSTOP;
118 # define use_seize (post_attach_sigstop == 0)
120 # define post_attach_sigstop TCB_IGNORE_ONE_SIGSTOP
124 /* Sometimes we want to print only succeeding syscalls. */
125 bool not_failing_only = 0;
127 /* Show path associated with fd arguments */
128 bool show_fd_path = 0;
130 static bool detach_on_execve = 0;
131 /* Are we "strace PROG" and need to skip detach on first execve? */
132 static bool skip_one_b_execve = 0;
133 /* Are we "strace PROG" and need to hide everything until execve? */
134 bool hide_log_until_execve = 0;
136 static int exit_code = 0;
137 static int strace_child = 0;
138 static int strace_tracer_pid = 0;
140 static char *username = NULL;
141 static uid_t run_uid;
142 static gid_t run_gid;
144 unsigned int max_strlen = DEFAULT_STRLEN;
145 static int acolumn = DEFAULT_ACOLUMN;
146 static char *acolumn_spaces;
148 static char *outfname = NULL;
149 /* If -ff, points to stderr. Else, it's our common output log */
150 static FILE *shared_log;
152 struct tcb *printing_tcp = NULL;
153 static struct tcb *current_tcp;
155 static struct tcb **tcbtab;
156 static unsigned int nprocs, tcbtabsize;
157 static const char *progname;
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 empty_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 */
194 usage(FILE *ofp, int exitval)
197 usage: strace [-CdffhiqrtttTvVxxy] [-I n] [-e expr]...\n\
198 [-a column] [-o file] [-s strsize] [-P path]...\n\
199 -p pid... / [-D] [-E var=val]... [-u username] PROG [ARGS]\n\
200 or: strace -c[df] [-I n] [-e expr]... [-O overhead] [-S sortby]\n\
201 -p pid... / [-D] [-E var=val]... [-u username] PROG [ARGS]\n\
202 -c -- count time, calls, and errors for each syscall and report summary\n\
203 -C -- like -c but also print regular output\n\
204 -w -- summarise syscall latency (default is system time)\n\
205 -d -- enable debug output to stderr\n\
206 -D -- run tracer process as a detached grandchild, not as parent\n\
207 -f -- follow forks, -ff -- with output into separate files\n\
208 -i -- print instruction pointer at time of syscall\n\
209 -q -- suppress messages about attaching, detaching, etc.\n\
210 -r -- print relative timestamp, -t -- absolute timestamp, -tt -- with usecs\n\
211 -T -- print time spent in each syscall\n\
212 -v -- verbose mode: print unabbreviated argv, stat, termios, etc. args\n\
213 -x -- print non-ascii strings in hex, -xx -- print all strings in hex\n\
214 -y -- print paths associated with file descriptor arguments\n\
215 -h -- print help message, -V -- print version\n\
216 -a column -- alignment COLUMN for printing syscall results (default %d)\n\
217 -b execve -- detach on this syscall\n\
218 -e expr -- a qualifying expression: option=[!]all or option=[!]val1[,val2]...\n\
219 options: trace, abbrev, verbose, raw, signal, read, write\n\
220 -I interruptible --\n\
221 1: no signals are blocked\n\
222 2: fatal signals are blocked while decoding syscall (default)\n\
223 3: fatal signals are always blocked (default if '-o FILE PROG')\n\
224 4: fatal signals and SIGTSTP (^Z) are always blocked\n\
225 (useful to make 'strace -o FILE PROG' not stop on ^Z)\n\
226 -o file -- send trace output to FILE instead of stderr\n\
227 -O overhead -- set overhead for tracing syscalls to OVERHEAD usecs\n\
228 -p pid -- trace process with process id PID, may be repeated\n\
229 -s strsize -- limit length of print strings to STRSIZE chars (default %d)\n\
230 -S sortby -- sort syscall counts by: time, calls, name, nothing (default %s)\n\
231 -u username -- run command as username handling setuid and/or setgid\n\
232 -E var=val -- put var=val in the environment for command\n\
233 -E var -- remove var from the environment for command\n\
234 -P path -- trace accesses to path\n\
236 /* ancient, no one should use it
237 -F -- attempt to follow vforks (deprecated, use -f)\n\
239 /* this is broken, so don't document it
240 -z -- print only succeeding syscalls\n\
242 , DEFAULT_ACOLUMN, DEFAULT_STRLEN, DEFAULT_SORTBY);
246 static void die(void) __attribute__ ((noreturn));
247 static void die(void)
249 if (strace_tracer_pid == getpid()) {
256 static void verror_msg(int err_no, const char *fmt, va_list p)
262 /* We want to print entire message with single fprintf to ensure
263 * message integrity if stderr is shared with other programs.
264 * Thus we use vasprintf + single fprintf.
267 if (vasprintf(&msg, fmt, p) >= 0) {
269 fprintf(stderr, "%s: %s: %s\n", progname, msg, strerror(err_no));
271 fprintf(stderr, "%s: %s\n", progname, msg);
274 /* malloc in vasprintf failed, try it without malloc */
275 fprintf(stderr, "%s: ", progname);
276 vfprintf(stderr, fmt, p);
278 fprintf(stderr, ": %s\n", strerror(err_no));
282 /* We don't switch stderr to buffered, thus fprintf(stderr)
283 * always flushes its output and this is not necessary: */
284 /* fflush(stderr); */
287 void error_msg(const char *fmt, ...)
291 verror_msg(0, fmt, p);
295 void error_msg_and_die(const char *fmt, ...)
299 verror_msg(0, fmt, p);
303 void perror_msg(const char *fmt, ...)
307 verror_msg(errno, fmt, p);
311 void perror_msg_and_die(const char *fmt, ...)
315 verror_msg(errno, fmt, p);
319 void die_out_of_memory(void)
321 static bool recursed = 0;
325 error_msg_and_die("Out of memory");
329 error_opt_arg(int opt, const char *arg)
331 error_msg_and_die("Invalid -%c argument: '%s'", opt, arg);
336 ptrace_attach_or_seize(int pid)
340 return ptrace(PTRACE_ATTACH, pid, 0L, 0L);
341 r = ptrace(PTRACE_SEIZE, pid, 0L, (unsigned long)ptrace_setoptions);
344 r = ptrace(PTRACE_INTERRUPT, pid, 0L, 0L);
348 # define ptrace_attach_or_seize(pid) ptrace(PTRACE_ATTACH, (pid), 0, 0)
352 * Used when we want to unblock stopped traced process.
353 * Should be only used with PTRACE_CONT, PTRACE_DETACH and PTRACE_SYSCALL.
354 * Returns 0 on success or if error was ESRCH
355 * (presumably process was killed while we talk to it).
356 * Otherwise prints error message and returns -1.
359 ptrace_restart(int op, struct tcb *tcp, int sig)
365 ptrace(op, tcp->pid, (void *) 0, (long) sig);
371 if (op == PTRACE_CONT)
373 if (op == PTRACE_DETACH)
376 if (op == PTRACE_LISTEN)
380 * Why curcol != 0? Otherwise sometimes we get this:
382 * 10252 kill(10253, SIGKILL) = 0
383 * <ptrace(SYSCALL,10252):No such process>10253 ...next decode...
385 * 10252 died after we retrieved syscall exit data,
386 * but before we tried to restart it. Log looks ugly.
388 if (current_tcp && current_tcp->curcol != 0) {
389 tprintf(" <ptrace(%s):%s>\n", msg, strerror(err));
395 perror_msg("ptrace(PTRACE_%s,pid:%d,sig:%d)", msg, tcp->pid, sig);
400 set_cloexec_flag(int fd)
404 flags = fcntl(fd, F_GETFD);
406 /* Can happen only if fd is bad.
407 * Should never happen: if it does, we have a bug
408 * in the caller. Therefore we just abort
409 * instead of propagating the error.
411 perror_msg_and_die("fcntl(%d, F_GETFD)", fd);
414 newflags = flags | FD_CLOEXEC;
415 if (flags == newflags)
418 fcntl(fd, F_SETFD, newflags); /* never fails */
421 static void kill_save_errno(pid_t pid, int sig)
423 int saved_errno = errno;
425 (void) kill(pid, sig);
430 * When strace is setuid executable, we have to swap uids
431 * before and after filesystem and process management operations.
436 int euid = geteuid(), uid = getuid();
438 if (euid != uid && setreuid(euid, uid) < 0) {
439 perror_msg_and_die("setreuid");
443 #ifdef _LARGEFILE64_SOURCE
445 # define fopen_for_output fopen64
447 # define fopen_for_output fopen
449 # define struct_stat struct stat64
450 # define stat_file stat64
451 # define struct_dirent struct dirent64
452 # define read_dir readdir64
453 # define struct_rlimit struct rlimit64
454 # define set_rlimit setrlimit64
456 # define fopen_for_output fopen
457 # define struct_stat struct stat
458 # define stat_file stat
459 # define struct_dirent struct dirent
460 # define read_dir readdir
461 # define struct_rlimit struct rlimit
462 # define set_rlimit setrlimit
466 strace_fopen(const char *path)
471 fp = fopen_for_output(path, "w");
473 perror_msg_and_die("Can't fopen '%s'", path);
475 set_cloexec_flag(fileno(fp));
479 static int popen_pid = 0;
482 # define _PATH_BSHELL "/bin/sh"
486 * We cannot use standard popen(3) here because we have to distinguish
487 * popen child process from other processes we trace, and standard popen(3)
488 * does not export its child's pid.
491 strace_popen(const char *command)
499 perror_msg_and_die("pipe");
501 set_cloexec_flag(fds[1]); /* never fails */
505 perror_msg_and_die("vfork");
512 perror_msg_and_die("dup2");
515 execl(_PATH_BSHELL, "sh", "-c", command, NULL);
516 perror_msg_and_die("Can't execute '%s'", _PATH_BSHELL);
523 fp = fdopen(fds[1], "w");
530 tprintf(const char *fmt, ...)
536 int n = strace_vfprintf(current_tcp->outf, fmt, args);
538 if (current_tcp->outf != stderr)
539 perror_msg("%s", outfname);
541 current_tcp->curcol += n;
546 #ifndef HAVE_FPUTS_UNLOCKED
547 # define fputs_unlocked fputs
551 tprints(const char *str)
554 int n = fputs_unlocked(str, current_tcp->outf);
556 current_tcp->curcol += strlen(str);
559 if (current_tcp->outf != stderr)
560 perror_msg("%s", outfname);
568 current_tcp->curcol = 0;
569 fflush(current_tcp->outf);
572 printing_tcp->curcol = 0;
578 printleader(struct tcb *tcp)
580 /* If -ff, "previous tcb we printed" is always the same as current,
581 * because we have per-tcb output files.
587 current_tcp = printing_tcp;
588 if (printing_tcp->curcol != 0 && (followfork < 2 || printing_tcp == tcp)) {
590 * case 1: we have a shared log (i.e. not -ff), and last line
591 * wasn't finished (same or different tcb, doesn't matter).
592 * case 2: split log, we are the same tcb, but our last line
593 * didn't finish ("SIGKILL nuked us after syscall entry" etc).
595 tprints(" <unfinished ...>\n");
596 printing_tcp->curcol = 0;
602 current_tcp->curcol = 0;
605 tprintf("%-5d ", tcp->pid);
606 else if (nprocs > 1 && !outfname)
607 tprintf("[pid %5u] ", tcp->pid);
610 char str[sizeof("HH:MM:SS")];
611 struct timeval tv, dtv;
612 static struct timeval otv;
614 gettimeofday(&tv, NULL);
618 tv_sub(&dtv, &tv, &otv);
619 tprintf("%6ld.%06ld ",
620 (long) dtv.tv_sec, (long) dtv.tv_usec);
623 else if (tflag > 2) {
624 tprintf("%ld.%06ld ",
625 (long) tv.tv_sec, (long) tv.tv_usec);
628 time_t local = tv.tv_sec;
629 strftime(str, sizeof(str), "%T", localtime(&local));
631 tprintf("%s.%06ld ", str, (long) tv.tv_usec);
643 if (current_tcp->curcol < acolumn)
644 tprints(acolumn_spaces + current_tcp->curcol);
647 /* Should be only called directly *after successful attach* to a tracee.
648 * Otherwise, "strace -oFILE -ff -p<nonexistant_pid>"
649 * may create bogus empty FILE.<nonexistant_pid>, and then die.
652 newoutf(struct tcb *tcp)
654 tcp->outf = shared_log; /* if not -ff mode, the same file is for all */
655 if (followfork >= 2) {
656 char name[520 + sizeof(int) * 3];
657 sprintf(name, "%.512s.%u", outfname, tcp->pid);
658 tcp->outf = strace_fopen(name);
665 /* Allocate some more TCBs and expand the table.
666 We don't want to relocate the TCBs because our
667 callers have pointers and it would be a pain.
668 So tcbtab is a table of pointers. Since we never
669 free the TCBs, we allocate a single chunk of many. */
671 struct tcb *newtcbs = calloc(tcbtabsize, sizeof(newtcbs[0]));
672 struct tcb **newtab = realloc(tcbtab, tcbtabsize * 2 * sizeof(tcbtab[0]));
673 if (!newtab || !newtcbs)
677 while (i < tcbtabsize)
678 tcbtab[i++] = newtcbs++;
687 if (nprocs == tcbtabsize)
690 for (i = 0; i < tcbtabsize; i++) {
693 memset(tcp, 0, sizeof(*tcp));
695 #if SUPPORTED_PERSONALITIES > 1
696 tcp->currpers = current_personality;
700 fprintf(stderr, "new tcb for pid %d, active tcbs:%d\n", tcp->pid, nprocs);
704 error_msg_and_die("bug in alloctcb");
708 droptcb(struct tcb *tcp)
715 fprintf(stderr, "dropped tcb for pid %d, %d remain\n", tcp->pid, nprocs);
718 if (followfork >= 2) {
719 if (tcp->curcol != 0)
720 fprintf(tcp->outf, " <detached ...>\n");
723 if (printing_tcp == tcp && tcp->curcol != 0)
724 fprintf(tcp->outf, " <detached ...>\n");
729 if (current_tcp == tcp)
731 if (printing_tcp == tcp)
734 memset(tcp, 0, sizeof(*tcp));
737 /* Detach traced process.
738 * Never call DETACH twice on the same process as both unattached and
739 * attached-unstopped processes give the same ESRCH. For unattached process we
740 * would SIGSTOP it and wait for its SIGSTOP notification forever.
743 detach(struct tcb *tcp)
748 if (tcp->flags & TCB_BPTSET)
752 * Linux wrongly insists the child be stopped
753 * before detaching. Arghh. We go through hoops
754 * to make a clean break of things.
757 # undef PTRACE_DETACH
758 # define PTRACE_DETACH PTRACE_SUNDETACH
761 if (!(tcp->flags & TCB_ATTACHED))
764 /* We attached but possibly didn't see the expected SIGSTOP.
765 * We must catch exactly one as otherwise the detached process
766 * would be left stopped (process state T).
768 if (tcp->flags & TCB_IGNORE_ONE_SIGSTOP)
771 error = ptrace(PTRACE_DETACH, tcp->pid, 0, 0);
773 /* On a clear day, you can see forever. */
776 if (errno != ESRCH) {
777 /* Shouldn't happen. */
778 perror_msg("detach: ptrace(PTRACE_DETACH,%u)", tcp->pid);
781 /* ESRCH: process is either not stopped or doesn't exist. */
782 if (my_tkill(tcp->pid, 0) < 0) {
784 /* Shouldn't happen. */
785 perror_msg("detach: tkill(%u,0)", tcp->pid);
786 /* else: process doesn't exist. */
789 /* Process is not stopped, need to stop it. */
792 * With SEIZE, tracee can be in group-stop already.
793 * In this state sending it another SIGSTOP does nothing.
794 * Need to use INTERRUPT.
795 * Testcase: trying to ^C a "strace -p <stopped_process>".
797 error = ptrace(PTRACE_INTERRUPT, tcp->pid, 0, 0);
801 perror_msg("detach: ptrace(PTRACE_INTERRUPT,%u)", tcp->pid);
804 error = my_tkill(tcp->pid, SIGSTOP);
808 perror_msg("detach: tkill(%u,SIGSTOP)", tcp->pid);
810 /* Either process doesn't exist, or some weird error. */
814 /* We end up here in three cases:
815 * 1. We sent PTRACE_INTERRUPT (use_seize case)
816 * 2. We sent SIGSTOP (!use_seize)
817 * 3. Attach SIGSTOP was already pending (TCB_IGNORE_ONE_SIGSTOP set)
821 if (waitpid(tcp->pid, &status, __WALL) < 0) {
825 * if (errno == ECHILD) break;
826 * ^^^ WRONG! We expect this PID to exist,
827 * and want to emit a message otherwise:
829 perror_msg("detach: waitpid(%u)", tcp->pid);
832 if (!WIFSTOPPED(status)) {
834 * Tracee exited or was killed by signal.
835 * We shouldn't normally reach this place:
836 * we don't want to consume exit status.
837 * Consider "strace -p PID" being ^C-ed:
838 * we want merely to detach from PID.
840 * However, we _can_ end up here if tracee
845 sig = WSTOPSIG(status);
847 fprintf(stderr, "detach wait: event:%d sig:%d\n",
848 (unsigned)status >> 16, sig);
850 unsigned event = (unsigned)status >> 16;
851 if (event == PTRACE_EVENT_STOP /*&& sig == SIGTRAP*/) {
853 * sig == SIGTRAP: PTRACE_INTERRUPT stop.
854 * sig == other: process was already stopped
855 * with this stopping sig (see tests/detach-stopped).
856 * Looks like re-injecting this sig is not necessary
857 * in DETACH for the tracee to remain stopped.
862 * PTRACE_INTERRUPT is not guaranteed to produce
863 * the above event if other ptrace-stop is pending.
864 * See tests/detach-sleeping testcase:
865 * strace got SIGINT while tracee is sleeping.
866 * We sent PTRACE_INTERRUPT.
867 * We see syscall exit, not PTRACE_INTERRUPT stop.
868 * We won't get PTRACE_INTERRUPT stop
869 * if we would CONT now. Need to DETACH.
871 if (sig == syscall_trap_sig)
873 /* else: not sure in which case we can be here.
874 * Signal stop? Inject it while detaching.
876 ptrace_restart(PTRACE_DETACH, tcp, sig);
879 /* Note: this check has to be after use_seize check */
880 /* (else, in use_seize case SIGSTOP will be mistreated) */
881 if (sig == SIGSTOP) {
882 /* Detach, suppressing SIGSTOP */
883 ptrace_restart(PTRACE_DETACH, tcp, 0);
886 if (sig == syscall_trap_sig)
888 /* Can't detach just yet, may need to wait for SIGSTOP */
889 error = ptrace_restart(PTRACE_CONT, tcp, sig);
891 /* Should not happen.
892 * Note: ptrace_restart returns 0 on ESRCH, so it's not it.
893 * ptrace_restart already emitted error message.
900 if (!qflag && (tcp->flags & TCB_ATTACHED))
901 fprintf(stderr, "Process %u detached\n", tcp->pid);
907 process_opt_p_list(char *opt)
911 * We accept -p PID,PID; -p "`pidof PROG`"; -p "`pgrep PROG`".
912 * pidof uses space as delim, pgrep uses newline. :(
915 char *delim = opt + strcspn(opt, ", \n\t");
919 pid = string_to_uint(opt);
921 error_msg_and_die("Invalid process id: '%s'", opt);
923 if (pid == strace_tracer_pid) {
924 error_msg_and_die("I'm sorry, I can't let you do that, Dave.");
941 * Block user interruptions as we would leave the traced
942 * process stopped (process state T) if we would terminate in
943 * between PTRACE_ATTACH and wait4() on SIGSTOP.
944 * We rely on cleanup() from this point on.
947 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
949 if (daemonized_tracer) {
952 perror_msg_and_die("fork");
954 if (pid) { /* parent */
956 * Wait for grandchild to attach to straced process
957 * (grandparent). Grandchild SIGKILLs us after it attached.
958 * Grandparent's wait() is unblocked by our death,
959 * it proceeds to exec the straced program.
962 _exit(0); /* paranoia */
965 /* We will be the tracer process. Remember our new pid: */
966 strace_tracer_pid = getpid();
969 for (tcbi = 0; tcbi < tcbtabsize; tcbi++) {
975 /* Is this a process we should attach to, but not yet attached? */
976 if (tcp->flags & TCB_ATTACHED)
977 continue; /* no, we already attached it */
979 if (followfork && !daemonized_tracer) {
980 char procdir[sizeof("/proc/%d/task") + sizeof(int) * 3];
983 sprintf(procdir, "/proc/%d/task", tcp->pid);
984 dir = opendir(procdir);
986 unsigned int ntid = 0, nerr = 0;
989 while ((de = read_dir(dir)) != NULL) {
993 if (de->d_fileno == 0)
995 /* we trust /proc filesystem */
996 tid = atoi(de->d_name);
1000 if (ptrace_attach_or_seize(tid) < 0) {
1003 fprintf(stderr, "attach to pid %d failed\n", tid);
1007 fprintf(stderr, "attach to pid %d succeeded\n", tid);
1009 if (tid != tcp->pid)
1010 cur_tcp = alloctcb(tid);
1011 cur_tcp->flags |= TCB_ATTACHED | TCB_STARTUP | post_attach_sigstop;
1016 sigprocmask(SIG_SETMASK, &empty_set, NULL);
1019 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
1023 perror_msg("attach: ptrace(PTRACE_ATTACH, ...)");
1028 fprintf(stderr, ntid > 1
1029 ? "Process %u attached with %u threads\n"
1030 : "Process %u attached\n",
1033 if (!(tcp->flags & TCB_ATTACHED)) {
1034 /* -p PID, we failed to attach to PID itself
1035 * but did attach to some of its sibling threads.
1041 } /* if (opendir worked) */
1043 if (ptrace_attach_or_seize(tcp->pid) < 0) {
1044 perror_msg("attach: ptrace(PTRACE_ATTACH, ...)");
1048 tcp->flags |= TCB_ATTACHED | TCB_STARTUP | post_attach_sigstop;
1051 fprintf(stderr, "attach to pid %d (main) succeeded\n", tcp->pid);
1053 if (daemonized_tracer) {
1055 * Make parent go away.
1056 * Also makes grandparent's wait() unblock.
1058 kill(getppid(), SIGKILL);
1063 "Process %u attached\n",
1065 } /* for each tcbtab[] */
1069 sigprocmask(SIG_SETMASK, &empty_set, NULL);
1072 /* Stack-o-phobic exec helper, in the hope to work around
1073 * NOMMU + "daemonized tracer" difficulty.
1075 struct exec_params {
1082 static struct exec_params params_for_tracee;
1083 static void __attribute__ ((noinline, noreturn))
1086 struct exec_params *params = ¶ms_for_tracee;
1088 if (params->fd_to_close >= 0)
1089 close(params->fd_to_close);
1090 if (!daemonized_tracer && !use_seize) {
1091 if (ptrace(PTRACE_TRACEME, 0L, 0L, 0L) < 0) {
1092 perror_msg_and_die("ptrace(PTRACE_TRACEME, ...)");
1096 if (username != NULL) {
1098 * It is important to set groups before we
1099 * lose privileges on setuid.
1101 if (initgroups(username, run_gid) < 0) {
1102 perror_msg_and_die("initgroups");
1104 if (setregid(run_gid, params->run_egid) < 0) {
1105 perror_msg_and_die("setregid");
1107 if (setreuid(run_uid, params->run_euid) < 0) {
1108 perror_msg_and_die("setreuid");
1111 else if (geteuid() != 0)
1112 if (setreuid(run_uid, run_uid) < 0) {
1113 perror_msg_and_die("setreuid");
1116 if (!daemonized_tracer) {
1118 * Induce a ptrace stop. Tracer (our parent)
1119 * will resume us with PTRACE_SYSCALL and display
1120 * the immediately following execve syscall.
1121 * Can't do this on NOMMU systems, we are after
1122 * vfork: parent is blocked, stopping would deadlock.
1125 kill(getpid(), SIGSTOP);
1128 /* we depend on SIGCHLD set to SIG_DFL by init code */
1129 /* if it happens to be SIG_IGN'ed, wait won't block */
1134 execv(params->pathname, params->argv);
1135 perror_msg_and_die("exec");
1139 startup_child(char **argv)
1141 struct_stat statbuf;
1142 const char *filename;
1143 char pathname[MAXPATHLEN];
1148 if (strchr(filename, '/')) {
1149 if (strlen(filename) > sizeof pathname - 1) {
1150 errno = ENAMETOOLONG;
1151 perror_msg_and_die("exec");
1153 strcpy(pathname, filename);
1155 #ifdef USE_DEBUGGING_EXEC
1157 * Debuggers customarily check the current directory
1158 * first regardless of the path but doing that gives
1159 * security geeks a panic attack.
1161 else if (stat_file(filename, &statbuf) == 0)
1162 strcpy(pathname, filename);
1163 #endif /* USE_DEBUGGING_EXEC */
1168 for (path = getenv("PATH"); path && *path; path += m) {
1169 const char *colon = strchr(path, ':');
1175 m = n = strlen(path);
1177 if (!getcwd(pathname, MAXPATHLEN))
1179 len = strlen(pathname);
1181 else if (n > sizeof pathname - 1)
1184 strncpy(pathname, path, n);
1187 if (len && pathname[len - 1] != '/')
1188 pathname[len++] = '/';
1189 strcpy(pathname + len, filename);
1190 if (stat_file(pathname, &statbuf) == 0 &&
1191 /* Accept only regular files
1192 with some execute bits set.
1193 XXX not perfect, might still fail */
1194 S_ISREG(statbuf.st_mode) &&
1195 (statbuf.st_mode & 0111))
1199 if (stat_file(pathname, &statbuf) < 0) {
1200 perror_msg_and_die("Can't stat '%s'", filename);
1203 params_for_tracee.fd_to_close = (shared_log != stderr) ? fileno(shared_log) : -1;
1204 params_for_tracee.run_euid = (statbuf.st_mode & S_ISUID) ? statbuf.st_uid : run_uid;
1205 params_for_tracee.run_egid = (statbuf.st_mode & S_ISGID) ? statbuf.st_gid : run_gid;
1206 params_for_tracee.argv = argv;
1208 * On NOMMU, can be safely freed only after execve in tracee.
1209 * It's hard to know when that happens, so we just leak it.
1211 params_for_tracee.pathname = NOMMU_SYSTEM ? strdup(pathname) : pathname;
1213 #if defined HAVE_PRCTL && defined PR_SET_PTRACER && defined PR_SET_PTRACER_ANY
1214 if (daemonized_tracer)
1215 prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY);
1220 perror_msg_and_die("fork");
1222 if ((pid != 0 && daemonized_tracer)
1223 || (pid == 0 && !daemonized_tracer)
1225 /* We are to become the tracee. Two cases:
1227 * not -D: we are child
1232 /* We are the tracer */
1234 if (!daemonized_tracer) {
1237 /* child did PTRACE_TRACEME, nothing to do in parent */
1239 if (!NOMMU_SYSTEM) {
1240 /* Wait until child stopped itself */
1242 while (waitpid(pid, &status, WSTOPPED) < 0) {
1245 perror_msg_and_die("waitpid");
1247 if (!WIFSTOPPED(status) || WSTOPSIG(status) != SIGSTOP) {
1248 kill_save_errno(pid, SIGKILL);
1249 perror_msg_and_die("Unexpected wait status %x", status);
1252 /* Else: NOMMU case, we have no way to sync.
1253 * Just attach to it as soon as possible.
1254 * This means that we may miss a few first syscalls...
1257 if (ptrace_attach_or_seize(pid)) {
1258 kill_save_errno(pid, SIGKILL);
1259 perror_msg_and_die("Can't attach to %d", pid);
1264 tcp = alloctcb(pid);
1266 tcp->flags |= TCB_ATTACHED | TCB_STARTUP | post_attach_sigstop;
1268 tcp->flags |= TCB_ATTACHED | TCB_STARTUP;
1272 /* With -D, we are *child* here, IOW: different pid. Fetch it: */
1273 strace_tracer_pid = getpid();
1274 /* The tracee is our parent: */
1277 /* attaching will be done later, by startup_attach */
1278 /* note: we don't do newoutf(tcp) here either! */
1280 /* NOMMU BUG! -D mode is active, we (child) return,
1281 * and we will scribble over parent's stack!
1282 * When parent later unpauses, it segfaults.
1285 * (1) by declaring exec_or_die() NORETURN,
1286 * hopefully compiler will just jump to it
1287 * instead of call (won't push anything to stack),
1288 * (2) by trying very hard in exec_or_die()
1289 * to not use any stack,
1290 * (3) having a really big (MAXPATHLEN) stack object
1291 * in this function, which creates a "buffer" between
1292 * child's and parent's stack pointers.
1293 * This may save us if (1) and (2) failed
1294 * and compiler decided to use stack in exec_or_die() anyway
1295 * (happens on i386 because of stack parameter passing).
1297 * A cleaner solution is to use makecontext + setcontext
1298 * to create a genuine separate stack and execute on it.
1304 * Test whether the kernel support PTRACE_O_TRACECLONE et al options.
1305 * First fork a new child, call ptrace with PTRACE_SETOPTIONS on it,
1306 * and then see which options are supported by the kernel.
1309 test_ptrace_setoptions_followfork(void)
1311 int pid, expected_grandchild = 0, found_grandchild = 0;
1312 const unsigned int test_options = PTRACE_O_TRACECLONE |
1313 PTRACE_O_TRACEFORK |
1314 PTRACE_O_TRACEVFORK;
1316 /* Need fork for test. NOMMU has no forks */
1318 goto worked; /* be bold, and pretend that test succeeded */
1322 perror_msg_and_die("fork");
1325 if (ptrace(PTRACE_TRACEME, 0L, 0L, 0L) < 0)
1326 perror_msg_and_die("%s: PTRACE_TRACEME doesn't work",
1328 kill_save_errno(pid, SIGSTOP);
1330 perror_msg_and_die("fork");
1335 int status, tracee_pid;
1338 tracee_pid = wait(&status);
1339 if (tracee_pid <= 0) {
1342 if (errno == ECHILD)
1344 kill_save_errno(pid, SIGKILL);
1345 perror_msg_and_die("%s: unexpected wait result %d",
1346 __func__, tracee_pid);
1348 if (WIFEXITED(status)) {
1349 if (WEXITSTATUS(status)) {
1350 if (tracee_pid != pid)
1351 kill_save_errno(pid, SIGKILL);
1352 error_msg_and_die("%s: unexpected exit status %u",
1353 __func__, WEXITSTATUS(status));
1357 if (WIFSIGNALED(status)) {
1358 if (tracee_pid != pid)
1359 kill_save_errno(pid, SIGKILL);
1360 error_msg_and_die("%s: unexpected signal %u",
1361 __func__, WTERMSIG(status));
1363 if (!WIFSTOPPED(status)) {
1364 if (tracee_pid != pid)
1365 kill_save_errno(tracee_pid, SIGKILL);
1366 kill_save_errno(pid, SIGKILL);
1367 error_msg_and_die("%s: unexpected wait status %x",
1370 if (tracee_pid != pid) {
1371 found_grandchild = tracee_pid;
1372 if (ptrace(PTRACE_CONT, tracee_pid, 0, 0) < 0) {
1373 kill_save_errno(tracee_pid, SIGKILL);
1374 kill_save_errno(pid, SIGKILL);
1375 perror_msg_and_die("PTRACE_CONT doesn't work");
1379 switch (WSTOPSIG(status)) {
1381 if (ptrace(PTRACE_SETOPTIONS, pid, 0, test_options) < 0
1382 && errno != EINVAL && errno != EIO)
1383 perror_msg("PTRACE_SETOPTIONS");
1386 if (status >> 16 == PTRACE_EVENT_FORK) {
1389 if (ptrace(PTRACE_GETEVENTMSG, pid,
1390 NULL, (long) &msg) == 0)
1391 expected_grandchild = msg;
1395 if (ptrace(PTRACE_SYSCALL, pid, 0, 0) < 0) {
1396 kill_save_errno(pid, SIGKILL);
1397 perror_msg_and_die("PTRACE_SYSCALL doesn't work");
1400 if (expected_grandchild && expected_grandchild == found_grandchild) {
1402 ptrace_setoptions |= test_options;
1404 fprintf(stderr, "ptrace_setoptions = %#x\n",
1408 error_msg("Test for PTRACE_O_TRACECLONE failed, "
1409 "giving up using this feature.");
1414 * Test whether the kernel support PTRACE_O_TRACESYSGOOD.
1415 * First fork a new child, call ptrace(PTRACE_SETOPTIONS) on it,
1416 * and then see whether it will stop with (SIGTRAP | 0x80).
1418 * Use of this option enables correct handling of user-generated SIGTRAPs,
1419 * and SIGTRAPs generated by special instructions such as int3 on x86:
1421 # compile with: gcc -nostartfiles -nostdlib -o int3 int3.S
1422 _start: .globl _start
1429 test_ptrace_setoptions_for_all(void)
1431 const unsigned int test_options = PTRACE_O_TRACESYSGOOD |
1436 /* Need fork for test. NOMMU has no forks */
1438 goto worked; /* be bold, and pretend that test succeeded */
1442 perror_msg_and_die("fork");
1446 if (ptrace(PTRACE_TRACEME, 0L, 0L, 0L) < 0)
1447 /* Note: exits with exitcode 1 */
1448 perror_msg_and_die("%s: PTRACE_TRACEME doesn't work",
1451 _exit(0); /* parent should see entry into this syscall */
1455 int status, tracee_pid;
1458 tracee_pid = wait(&status);
1459 if (tracee_pid <= 0) {
1462 kill_save_errno(pid, SIGKILL);
1463 perror_msg_and_die("%s: unexpected wait result %d",
1464 __func__, tracee_pid);
1466 if (WIFEXITED(status)) {
1467 if (WEXITSTATUS(status) == 0)
1469 error_msg_and_die("%s: unexpected exit status %u",
1470 __func__, WEXITSTATUS(status));
1472 if (WIFSIGNALED(status)) {
1473 error_msg_and_die("%s: unexpected signal %u",
1474 __func__, WTERMSIG(status));
1476 if (!WIFSTOPPED(status)) {
1478 error_msg_and_die("%s: unexpected wait status %x",
1481 if (WSTOPSIG(status) == SIGSTOP) {
1483 * We don't check "options aren't accepted" error.
1484 * If it happens, we'll never get (SIGTRAP | 0x80),
1485 * and thus will decide to not use the option.
1486 * IOW: the outcome of the test will be correct.
1488 if (ptrace(PTRACE_SETOPTIONS, pid, 0L, test_options) < 0
1489 && errno != EINVAL && errno != EIO)
1490 perror_msg("PTRACE_SETOPTIONS");
1492 if (WSTOPSIG(status) == (SIGTRAP | 0x80)) {
1495 if (ptrace(PTRACE_SYSCALL, pid, 0L, 0L) < 0) {
1496 kill_save_errno(pid, SIGKILL);
1497 perror_msg_and_die("PTRACE_SYSCALL doesn't work");
1503 syscall_trap_sig = (SIGTRAP | 0x80);
1504 ptrace_setoptions |= test_options;
1506 fprintf(stderr, "ptrace_setoptions = %#x\n",
1511 error_msg("Test for PTRACE_O_TRACESYSGOOD failed, "
1512 "giving up using this feature.");
1518 test_ptrace_seize(void)
1522 /* Need fork for test. NOMMU has no forks */
1524 post_attach_sigstop = 0; /* this sets use_seize to 1 */
1530 perror_msg_and_die("fork");
1537 /* PTRACE_SEIZE, unlike ATTACH, doesn't force tracee to trap. After
1538 * attaching tracee continues to run unless a trap condition occurs.
1539 * PTRACE_SEIZE doesn't affect signal or group stop state.
1541 if (ptrace(PTRACE_SEIZE, pid, 0, 0) == 0) {
1542 post_attach_sigstop = 0; /* this sets use_seize to 1 */
1543 } else if (debug_flag) {
1544 fprintf(stderr, "PTRACE_SEIZE doesn't work\n");
1550 int status, tracee_pid;
1553 tracee_pid = waitpid(pid, &status, 0);
1554 if (tracee_pid <= 0) {
1557 perror_msg_and_die("%s: unexpected wait result %d",
1558 __func__, tracee_pid);
1560 if (WIFSIGNALED(status)) {
1563 error_msg_and_die("%s: unexpected wait status %x",
1567 #else /* !USE_SEIZE */
1568 # define test_ptrace_seize() ((void)0)
1572 get_os_release(void)
1578 perror_msg_and_die("uname");
1579 /* u.release has this form: "3.2.9[-some-garbage]" */
1583 if (!(*p >= '0' && *p <= '9'))
1584 error_msg_and_die("Bad OS release string: '%s'", u.release);
1585 /* Note: this open-codes KERNEL_VERSION(): */
1586 rel = (rel << 8) | atoi(p);
1587 if (rel >= KERNEL_VERSION(1,0,0))
1589 while (*p >= '0' && *p <= '9')
1592 if (rel >= KERNEL_VERSION(0,1,0)) {
1593 /* "X.Y-something" means "X.Y.0" */
1597 error_msg_and_die("Bad OS release string: '%s'", u.release);
1605 * Initialization part of main() was eating much stack (~0.5k),
1606 * which was unused after init.
1607 * We can reuse it if we move init code into a separate function.
1609 * Don't want main() to inline us and defeat the reason
1610 * we have a separate function.
1612 static void __attribute__ ((noinline))
1613 init(int argc, char *argv[])
1618 struct sigaction sa;
1620 progname = argv[0] ? argv[0] : "strace";
1622 /* Make sure SIGCHLD has the default action so that waitpid
1623 definitely works without losing track of children. The user
1624 should not have given us a bogus state to inherit, but he might
1625 have. Arguably we should detect SIG_IGN here and pass it on
1626 to children, but probably noone really needs that. */
1627 signal(SIGCHLD, SIG_DFL);
1629 strace_tracer_pid = getpid();
1631 os_release = get_os_release();
1633 /* Allocate the initial tcbtab. */
1634 tcbtabsize = argc; /* Surely enough for all -p args. */
1635 tcbtab = calloc(tcbtabsize, sizeof(tcbtab[0]));
1637 die_out_of_memory();
1638 tcp = calloc(tcbtabsize, sizeof(*tcp));
1640 die_out_of_memory();
1641 for (c = 0; c < tcbtabsize; c++)
1644 shared_log = stderr;
1645 set_sortby(DEFAULT_SORTBY);
1646 set_personality(DEFAULT_PERSONALITY);
1647 qualify("trace=all");
1648 qualify("abbrev=all");
1649 qualify("verbose=all");
1650 #if DEFAULT_QUAL_FLAGS != (QUAL_TRACE | QUAL_ABBREV | QUAL_VERBOSE)
1651 # error Bug in DEFAULT_QUAL_FLAGS
1653 qualify("signal=all");
1654 while ((c = getopt(argc, argv,
1655 "+b:cCdfFhiqrtTvVwxyz"
1657 "a:e:o:O:p:s:S:u:E:P:I:")) != EOF) {
1660 if (strcmp(optarg, "execve") != 0)
1661 error_msg_and_die("Syscall '%s' for -b isn't supported",
1663 detach_on_execve = 1;
1666 if (cflag == CFLAG_BOTH) {
1667 error_msg_and_die("-c and -C are mutually exclusive");
1669 cflag = CFLAG_ONLY_STATS;
1672 if (cflag == CFLAG_ONLY_STATS) {
1673 error_msg_and_die("-c and -C are mutually exclusive");
1681 daemonized_tracer = 1;
1700 /* fall through to tflag++ */
1708 count_wallclock = 1;
1717 qualify("abbrev=none");
1720 printf("%s -- version %s\n", PACKAGE_NAME, VERSION);
1724 not_failing_only = 1;
1727 acolumn = string_to_uint(optarg);
1729 error_opt_arg(c, optarg);
1735 outfname = strdup(optarg);
1738 i = string_to_uint(optarg);
1740 error_opt_arg(c, optarg);
1744 process_opt_p_list(optarg);
1747 pathtrace_select(optarg);
1750 i = string_to_uint(optarg);
1752 error_opt_arg(c, optarg);
1759 username = strdup(optarg);
1762 if (putenv(optarg) < 0)
1763 die_out_of_memory();
1766 opt_intr = string_to_uint(optarg);
1767 if (opt_intr <= 0 || opt_intr >= NUM_INTR_OPTS)
1768 error_opt_arg(c, optarg);
1776 /* argc -= optind; - no need, argc is not used below */
1778 acolumn_spaces = malloc(acolumn + 1);
1779 if (!acolumn_spaces)
1780 die_out_of_memory();
1781 memset(acolumn_spaces, ' ', acolumn);
1782 acolumn_spaces[acolumn] = '\0';
1784 /* Must have PROG [ARGS], or -p PID. Not both. */
1785 if (!argv[0] == !nprocs)
1788 if (nprocs != 0 && daemonized_tracer) {
1789 error_msg_and_die("-D and -p are mutually exclusive");
1795 if (followfork >= 2 && cflag) {
1796 error_msg_and_die("(-c or -C) and -ff are mutually exclusive");
1799 if (count_wallclock && !cflag) {
1800 error_msg_and_die("-w must be given with (-c or -C)");
1803 /* See if they want to run as another user. */
1804 if (username != NULL) {
1805 struct passwd *pent;
1807 if (getuid() != 0 || geteuid() != 0) {
1808 error_msg_and_die("You must be root to use the -u option");
1810 pent = getpwnam(username);
1812 error_msg_and_die("Cannot find user '%s'", username);
1814 run_uid = pent->pw_uid;
1815 run_gid = pent->pw_gid;
1823 * On any reasonably recent Linux kernel (circa about 2.5.46)
1824 * need_fork_exec_workarounds should stay 0 after these tests:
1826 /*need_fork_exec_workarounds = 0; - already is */
1828 need_fork_exec_workarounds = test_ptrace_setoptions_followfork();
1829 need_fork_exec_workarounds |= test_ptrace_setoptions_for_all();
1830 test_ptrace_seize();
1832 /* Check if they want to redirect the output. */
1834 /* See if they want to pipe the output. */
1835 if (outfname[0] == '|' || outfname[0] == '!') {
1837 * We can't do the <outfname>.PID funny business
1838 * when using popen, so prohibit it.
1840 if (followfork >= 2)
1841 error_msg_and_die("Piping the output and -ff are mutually exclusive");
1842 shared_log = strace_popen(outfname + 1);
1844 else if (followfork < 2)
1845 shared_log = strace_fopen(outfname);
1847 /* -ff without -o FILE is the same as single -f */
1848 if (followfork >= 2)
1852 if (!outfname || outfname[0] == '|' || outfname[0] == '!') {
1853 char *buf = malloc(BUFSIZ);
1855 die_out_of_memory();
1856 setvbuf(shared_log, buf, _IOLBF, BUFSIZ);
1858 if (outfname && argv[0]) {
1860 opt_intr = INTR_NEVER;
1864 opt_intr = INTR_WHILE_WAIT;
1866 /* argv[0] -pPID -oFILE Default interactive setting
1867 * yes 0 0 INTR_WHILE_WAIT
1868 * no 1 0 INTR_WHILE_WAIT
1869 * yes 0 1 INTR_NEVER
1870 * no 1 1 INTR_WHILE_WAIT
1873 sigemptyset(&empty_set);
1874 sigemptyset(&blocked_set);
1876 /* startup_child() must be called before the signal handlers get
1877 * installed below as they are inherited into the spawned process.
1878 * Also we do not need to be protected by them as during interruption
1879 * in the startup_child() mode we kill the spawned process anyway.
1882 if (!NOMMU_SYSTEM || daemonized_tracer)
1883 hide_log_until_execve = 1;
1884 skip_one_b_execve = 1;
1885 startup_child(argv);
1888 sa.sa_handler = SIG_IGN;
1889 sigemptyset(&sa.sa_mask);
1891 sigaction(SIGTTOU, &sa, NULL); /* SIG_IGN */
1892 sigaction(SIGTTIN, &sa, NULL); /* SIG_IGN */
1893 if (opt_intr != INTR_ANYWHERE) {
1894 if (opt_intr == INTR_BLOCK_TSTP_TOO)
1895 sigaction(SIGTSTP, &sa, NULL); /* SIG_IGN */
1897 * In interactive mode (if no -o OUTFILE, or -p PID is used),
1898 * fatal signals are blocked while syscall stop is processed,
1899 * and acted on in between, when waiting for new syscall stops.
1900 * In non-interactive mode, signals are ignored.
1902 if (opt_intr == INTR_WHILE_WAIT) {
1903 sigaddset(&blocked_set, SIGHUP);
1904 sigaddset(&blocked_set, SIGINT);
1905 sigaddset(&blocked_set, SIGQUIT);
1906 sigaddset(&blocked_set, SIGPIPE);
1907 sigaddset(&blocked_set, SIGTERM);
1908 sa.sa_handler = interrupt;
1910 /* SIG_IGN, or set handler for these */
1911 sigaction(SIGHUP, &sa, NULL);
1912 sigaction(SIGINT, &sa, NULL);
1913 sigaction(SIGQUIT, &sa, NULL);
1914 sigaction(SIGPIPE, &sa, NULL);
1915 sigaction(SIGTERM, &sa, NULL);
1917 if (nprocs != 0 || daemonized_tracer)
1920 /* Do we want pids printed in our -o OUTFILE?
1921 * -ff: no (every pid has its own file); or
1922 * -f: yes (there can be more pids in the future); or
1923 * -p PID1,PID2: yes (there are already more than one pid)
1925 print_pid_pfx = (outfname && followfork < 2 && (followfork == 1 || nprocs > 1));
1936 for (i = 0; i < tcbtabsize; i++) {
1937 struct tcb *tcp = tcbtab[i];
1938 if (tcp->pid == pid)
1952 /* 'interrupted' is a volatile object, fetch it only once */
1953 fatal_sig = interrupted;
1955 fatal_sig = SIGTERM;
1957 for (i = 0; i < tcbtabsize; i++) {
1963 "cleanup: looking at pid %u\n", tcp->pid);
1964 if (tcp->pid == strace_child) {
1965 kill(tcp->pid, SIGCONT);
1966 kill(tcp->pid, fatal_sig);
1971 call_summary(shared_log);
1985 /* Used to be "while (nprocs != 0)", but in this testcase:
1986 * int main() { _exit(!!fork()); }
1987 * under strace -f, parent sometimes (rarely) manages
1988 * to exit before we see the first stop of the child,
1989 * and we are losing track of it:
1990 * 19923 clone(...) = 19924
1991 * 19923 exit_group(1) = ?
1992 * 19923 +++ exited with 1 +++
1993 * Waiting for ECHILD works better.
1994 * (However, if -o|logger is in use, we can't do that.
1995 * Can work around that by double-forking the logger,
1996 * but that loses the ability to wait for its completion on exit.
2010 if (popen_pid != 0 && nprocs == 0)
2014 sigprocmask(SIG_SETMASK, &empty_set, NULL);
2015 pid = wait4(-1, &status, __WALL, (cflag ? &ru : NULL));
2018 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
2021 if (wait_errno == EINTR)
2023 if (nprocs == 0 && wait_errno == ECHILD)
2025 /* If nprocs > 0, ECHILD is not expected,
2026 * treat it as any other error here:
2029 perror_msg_and_die("wait4(__WALL)");
2032 if (pid == popen_pid) {
2033 if (!WIFSTOPPED(status))
2038 event = ((unsigned)status >> 16);
2040 char buf[sizeof("WIFEXITED,exitcode=%u") + sizeof(int)*3 /*paranoia:*/ + 16];
2041 char evbuf[sizeof(",EVENT_VFORK_DONE (%u)") + sizeof(int)*3 /*paranoia:*/ + 16];
2043 if (WIFSIGNALED(status))
2045 sprintf(buf, "WIFSIGNALED,%ssig=%s",
2046 WCOREDUMP(status) ? "core," : "",
2047 signame(WTERMSIG(status)));
2049 sprintf(buf, "WIFSIGNALED,sig=%s",
2050 signame(WTERMSIG(status)));
2052 if (WIFEXITED(status))
2053 sprintf(buf, "WIFEXITED,exitcode=%u", WEXITSTATUS(status));
2054 if (WIFSTOPPED(status))
2055 sprintf(buf, "WIFSTOPPED,sig=%s", signame(WSTOPSIG(status)));
2057 /* Should never be seen */
2058 if (WIFCONTINUED(status))
2059 strcpy(buf, "WIFCONTINUED");
2063 static const char *const event_names[] = {
2064 [PTRACE_EVENT_CLONE] = "CLONE",
2065 [PTRACE_EVENT_FORK] = "FORK",
2066 [PTRACE_EVENT_VFORK] = "VFORK",
2067 [PTRACE_EVENT_VFORK_DONE] = "VFORK_DONE",
2068 [PTRACE_EVENT_EXEC] = "EXEC",
2069 [PTRACE_EVENT_EXIT] = "EXIT",
2070 /* [PTRACE_EVENT_STOP (=128)] would make biggish array */
2072 const char *e = "??";
2073 if (event < ARRAY_SIZE(event_names))
2074 e = event_names[event];
2075 else if (event == PTRACE_EVENT_STOP)
2077 sprintf(evbuf, ",EVENT_%s (%u)", e, event);
2079 fprintf(stderr, " [wait(0x%06x) = %u] %s%s\n", status, pid, buf, evbuf);
2082 /* Look up 'pid' in our table. */
2086 if (!WIFSTOPPED(status)) {
2087 /* This can happen if we inherited
2088 * an unknown child. Example:
2089 * (sleep 1 & exec strace sleep 2)
2091 error_msg("Exit of unknown pid %u seen", pid);
2095 /* We assume it's a fork/vfork/clone child */
2096 tcp = alloctcb(pid);
2097 tcp->flags |= TCB_ATTACHED | TCB_STARTUP | post_attach_sigstop;
2100 fprintf(stderr, "Process %d attached\n",
2103 /* This can happen if a clone call used
2104 * CLONE_PTRACE itself.
2106 ptrace(PTRACE_CONT, pid, (char *) 0, 0);
2107 error_msg("Stop of unknown pid %u seen, PTRACE_CONTed it", pid);
2113 if (WIFSTOPPED(status))
2116 /* Under Linux, execve changes pid to thread leader's pid,
2117 * and we see this changed pid on EVENT_EXEC and later,
2118 * execve sysexit. Leader "disappears" without exit
2119 * notification. Let user know that, drop leader's tcb,
2120 * and fix up pid in execve thread's tcb.
2121 * Effectively, execve thread's tcb replaces leader's tcb.
2123 * BTW, leader is 'stuck undead' (doesn't report WIFEXITED
2124 * on exit syscall) in multithreaded programs exactly
2125 * in order to handle this case.
2127 * PTRACE_GETEVENTMSG returns old pid starting from Linux 3.0.
2128 * On 2.6 and earlier, it can return garbage.
2130 if (event == PTRACE_EVENT_EXEC && os_release >= KERNEL_VERSION(3,0,0)) {
2132 struct tcb *execve_thread;
2135 if (ptrace(PTRACE_GETEVENTMSG, pid, NULL, (long) &old_pid) < 0)
2136 goto dont_switch_tcbs;
2137 /* Avoid truncation in pid2tcb() param passing */
2138 if (old_pid > UINT_MAX)
2139 goto dont_switch_tcbs;
2140 if (old_pid <= 0 || old_pid == pid)
2141 goto dont_switch_tcbs;
2142 execve_thread = pid2tcb(old_pid);
2143 /* It should be !NULL, but I feel paranoid */
2145 goto dont_switch_tcbs;
2147 if (execve_thread->curcol != 0) {
2149 * One case we are here is -ff:
2150 * try "strace -oLOG -ff test/threaded_execve"
2152 fprintf(execve_thread->outf, " <pid changed to %d ...>\n", pid);
2153 /*execve_thread->curcol = 0; - no need, see code below */
2155 /* Swap output FILEs (needed for -ff) */
2156 fp = execve_thread->outf;
2157 execve_thread->outf = tcp->outf;
2159 /* And their column positions */
2160 execve_thread->curcol = tcp->curcol;
2162 /* Drop leader, but close execve'd thread outfile (if -ff) */
2164 /* Switch to the thread, reusing leader's outfile and pid */
2165 tcp = execve_thread;
2167 if (cflag != CFLAG_ONLY_STATS) {
2169 tprintf("+++ superseded by execve in pid %lu +++\n", old_pid);
2171 tcp->flags |= TCB_REPRINT;
2176 if (event == PTRACE_EVENT_EXEC) {
2177 if (detach_on_execve && !skip_one_b_execve)
2178 detach(tcp); /* do "-b execve" thingy */
2179 skip_one_b_execve = 0;
2182 /* Set current output file */
2186 tv_sub(&tcp->dtime, &ru.ru_stime, &tcp->stime);
2187 tcp->stime = ru.ru_stime;
2190 if (WIFSIGNALED(status)) {
2191 if (pid == strace_child)
2192 exit_code = 0x100 | WTERMSIG(status);
2193 if (cflag != CFLAG_ONLY_STATS
2194 && (qual_flags[WTERMSIG(status)] & QUAL_SIGNAL)
2198 tprintf("+++ killed by %s %s+++\n",
2199 signame(WTERMSIG(status)),
2200 WCOREDUMP(status) ? "(core dumped) " : "");
2202 tprintf("+++ killed by %s +++\n",
2203 signame(WTERMSIG(status)));
2210 if (WIFEXITED(status)) {
2211 if (pid == strace_child)
2212 exit_code = WEXITSTATUS(status);
2213 if (cflag != CFLAG_ONLY_STATS &&
2216 tprintf("+++ exited with %d +++\n", WEXITSTATUS(status));
2222 if (!WIFSTOPPED(status)) {
2223 fprintf(stderr, "PANIC: pid %u not stopped\n", pid);
2228 /* Is this the very first time we see this tracee stopped? */
2229 if (tcp->flags & TCB_STARTUP) {
2231 fprintf(stderr, "pid %d has TCB_STARTUP, initializing it\n", tcp->pid);
2232 tcp->flags &= ~TCB_STARTUP;
2233 if (tcp->flags & TCB_BPTSET) {
2235 * One example is a breakpoint inherited from
2236 * parent through fork().
2238 if (clearbpt(tcp) < 0) {
2245 if (!use_seize && ptrace_setoptions) {
2247 fprintf(stderr, "setting opts 0x%x on pid %d\n", ptrace_setoptions, tcp->pid);
2248 if (ptrace(PTRACE_SETOPTIONS, tcp->pid, NULL, ptrace_setoptions) < 0) {
2249 if (errno != ESRCH) {
2250 /* Should never happen, really */
2251 perror_msg_and_die("PTRACE_SETOPTIONS");
2257 sig = WSTOPSIG(status);
2262 if (event == PTRACE_EVENT_STOP) {
2264 * PTRACE_INTERRUPT-stop or group-stop.
2265 * PTRACE_INTERRUPT-stop has sig == SIGTRAP here.
2277 goto restart_tracee_with_sig_0;
2280 /* Is this post-attach SIGSTOP?
2281 * Interestingly, the process may stop
2282 * with STOPSIG equal to some other signal
2283 * than SIGSTOP if we happend to attach
2284 * just before the process takes a signal.
2286 if (sig == SIGSTOP && (tcp->flags & TCB_IGNORE_ONE_SIGSTOP)) {
2288 fprintf(stderr, "ignored SIGSTOP on pid %d\n", tcp->pid);
2289 tcp->flags &= ~TCB_IGNORE_ONE_SIGSTOP;
2290 goto restart_tracee_with_sig_0;
2293 if (sig != syscall_trap_sig) {
2296 /* Nonzero (true) if tracee is stopped by signal
2297 * (as opposed to "tracee received signal").
2298 * TODO: shouldn't we check for errno == EINVAL too?
2299 * We can get ESRCH instead, you know...
2301 stopped = (ptrace(PTRACE_GETSIGINFO, pid, 0, (long) &si) < 0);
2305 if (cflag != CFLAG_ONLY_STATS
2306 && !hide_log_until_execve
2307 && (qual_flags[sig] & QUAL_SIGNAL)
2311 tprintf("--- %s ", signame(sig));
2312 printsiginfo(&si, verbose(tcp));
2315 tprintf("--- stopped by %s ---\n",
2321 /* It's signal-delivery-stop. Inject the signal */
2322 goto restart_tracee;
2324 /* It's group-stop */
2327 * This ends ptrace-stop, but does *not* end group-stop.
2328 * This makes stopping signals work properly on straced process
2329 * (that is, process really stops. It used to continue to run).
2331 if (ptrace_restart(PTRACE_LISTEN, tcp, 0) < 0) {
2332 /* Note: ptrace_restart emitted error message */
2338 /* We don't have PTRACE_LISTEN support... */
2339 goto restart_tracee;
2342 /* We handled quick cases, we are permitted to interrupt now. */
2346 /* This should be syscall entry or exit.
2347 * (Or it still can be that pesky post-execve SIGTRAP!)
2350 if (trace_syscall(tcp) < 0) {
2351 /* ptrace() failed in trace_syscall().
2352 * Likely a result of process disappearing mid-flight.
2353 * Observed case: exit_group() or SIGKILL terminating
2354 * all processes in thread group.
2355 * We assume that ptrace error was caused by process death.
2356 * We used to detach(tcp) here, but since we no longer
2357 * implement "detach before death" policy/hack,
2358 * we can let this process to report its death to us
2359 * normally, via WIFEXITED or WIFSIGNALED wait status.
2363 restart_tracee_with_sig_0:
2366 if (ptrace_restart(PTRACE_SYSCALL, tcp, sig) < 0) {
2367 /* Note: ptrace_restart emitted error message */
2375 main(int argc, char *argv[])
2379 /* Run main tracing loop */
2384 if (shared_log != stderr)
2387 while (waitpid(popen_pid, NULL, 0) < 0 && errno == EINTR)
2390 if (exit_code > 0xff) {
2391 /* Avoid potential core file clobbering. */
2392 struct_rlimit rlim = {0, 0};
2393 set_rlimit(RLIMIT_CORE, &rlim);
2395 /* Child was killed by a signal, mimic that. */
2397 signal(exit_code, SIG_DFL);
2399 /* Paranoia - what if this signal is not fatal?
2400 Exit with 128 + signo then. */