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;
80 unsigned int qflag = 0;
81 /* Which WSTOPSIG(status) value marks syscall traps? */
82 static unsigned int syscall_trap_sig = SIGTRAP;
83 static unsigned int tflag = 0;
84 static bool iflag = 0;
85 static bool rflag = 0;
86 static bool print_pid_pfx = 0;
91 INTR_ANYWHERE = 1, /* don't block/ignore any signals */
92 INTR_WHILE_WAIT = 2, /* block fatal signals while decoding syscall. default */
93 INTR_NEVER = 3, /* block fatal signals. default if '-o FILE PROG' */
94 INTR_BLOCK_TSTP_TOO = 4, /* block fatal signals and SIGTSTP (^Z) */
98 /* We play with signal mask only if this mode is active: */
99 #define interactive (opt_intr == INTR_WHILE_WAIT)
102 * daemonized_tracer supports -D option.
103 * With this option, strace forks twice.
104 * Unlike normal case, with -D *grandparent* process exec's,
105 * becoming a traced process. Child exits (this prevents traced process
106 * from having children it doesn't expect to have), and grandchild
107 * attaches to grandparent similarly to strace -p PID.
108 * This allows for more transparent interaction in cases
109 * when process and its parent are communicating via signals,
110 * wait() etc. Without -D, strace process gets lodged in between,
111 * disrupting parent<->child link.
113 static bool daemonized_tracer = 0;
116 static int post_attach_sigstop = TCB_IGNORE_ONE_SIGSTOP;
117 # define use_seize (post_attach_sigstop == 0)
119 # define post_attach_sigstop TCB_IGNORE_ONE_SIGSTOP
123 /* Sometimes we want to print only succeeding syscalls. */
124 bool not_failing_only = 0;
126 /* Show path associated with fd arguments */
127 bool show_fd_path = 0;
129 static bool detach_on_execve = 0;
130 /* Are we "strace PROG" and need to skip detach on first execve? */
131 static bool skip_one_b_execve = 0;
132 /* Are we "strace PROG" and need to hide everything until execve? */
133 bool hide_log_until_execve = 0;
135 static int exit_code = 0;
136 static int strace_child = 0;
137 static int strace_tracer_pid = 0;
139 static char *username = NULL;
140 static uid_t run_uid;
141 static gid_t run_gid;
143 unsigned int max_strlen = DEFAULT_STRLEN;
144 static int acolumn = DEFAULT_ACOLUMN;
145 static char *acolumn_spaces;
147 static char *outfname = NULL;
148 /* If -ff, points to stderr. Else, it's our common output log */
149 static FILE *shared_log;
151 struct tcb *printing_tcp = NULL;
152 static struct tcb *current_tcp;
154 static struct tcb **tcbtab;
155 static unsigned int nprocs, tcbtabsize;
156 static const char *progname;
158 unsigned os_release; /* generated from uname()'s u.release */
160 static int detach(struct tcb *tcp);
161 static int trace(void);
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 -d -- enable debug output to stderr\n\
205 -D -- run tracer process as a detached grandchild, not as parent\n\
206 -f -- follow forks, -ff -- with output into separate files\n\
207 -i -- print instruction pointer at time of syscall\n\
208 -q -- suppress messages about attaching, detaching, etc.\n\
209 -r -- print relative timestamp, -t -- absolute timestamp, -tt -- with usecs\n\
210 -T -- print time spent in each syscall\n\
211 -v -- verbose mode: print unabbreviated argv, stat, termios, etc. args\n\
212 -x -- print non-ascii strings in hex, -xx -- print all strings in hex\n\
213 -y -- print paths associated with file descriptor arguments\n\
214 -h -- print help message, -V -- print version\n\
215 -a column -- alignment COLUMN for printing syscall results (default %d)\n\
216 -b execve -- detach on this syscall\n\
217 -e expr -- a qualifying expression: option=[!]all or option=[!]val1[,val2]...\n\
218 options: trace, abbrev, verbose, raw, signal, read, write\n\
219 -I interruptible --\n\
220 1: no signals are blocked\n\
221 2: fatal signals are blocked while decoding syscall (default)\n\
222 3: fatal signals are always blocked (default if '-o FILE PROG')\n\
223 4: fatal signals and SIGTSTP (^Z) are always blocked\n\
224 (useful to make 'strace -o FILE PROG' not stop on ^Z)\n\
225 -o file -- send trace output to FILE instead of stderr\n\
226 -O overhead -- set overhead for tracing syscalls to OVERHEAD usecs\n\
227 -p pid -- trace process with process id PID, may be repeated\n\
228 -s strsize -- limit length of print strings to STRSIZE chars (default %d)\n\
229 -S sortby -- sort syscall counts by: time, calls, name, nothing (default %s)\n\
230 -u username -- run command as username handling setuid and/or setgid\n\
231 -E var=val -- put var=val in the environment for command\n\
232 -E var -- remove var from the environment for command\n\
233 -P path -- trace accesses to path\n\
235 /* ancient, no one should use it
236 -F -- attempt to follow vforks (deprecated, use -f)\n\
238 /* this is broken, so don't document it
239 -z -- print only succeeding syscalls\n\
241 , DEFAULT_ACOLUMN, DEFAULT_STRLEN, DEFAULT_SORTBY);
245 static void die(void) __attribute__ ((noreturn));
246 static void die(void)
248 if (strace_tracer_pid == getpid()) {
255 static void verror_msg(int err_no, const char *fmt, va_list p)
261 /* We want to print entire message with single fprintf to ensure
262 * message integrity if stderr is shared with other programs.
263 * Thus we use vasprintf + single fprintf.
266 if (vasprintf(&msg, fmt, p) >= 0) {
268 fprintf(stderr, "%s: %s: %s\n", progname, msg, strerror(err_no));
270 fprintf(stderr, "%s: %s\n", progname, msg);
273 /* malloc in vasprintf failed, try it without malloc */
274 fprintf(stderr, "%s: ", progname);
275 vfprintf(stderr, fmt, p);
277 fprintf(stderr, ": %s\n", strerror(err_no));
281 /* We don't switch stderr to buffered, thus fprintf(stderr)
282 * always flushes its output and this is not necessary: */
283 /* fflush(stderr); */
286 void error_msg(const char *fmt, ...)
290 verror_msg(0, fmt, p);
294 void error_msg_and_die(const char *fmt, ...)
298 verror_msg(0, fmt, p);
302 void perror_msg(const char *fmt, ...)
306 verror_msg(errno, fmt, p);
310 void perror_msg_and_die(const char *fmt, ...)
314 verror_msg(errno, fmt, p);
318 void die_out_of_memory(void)
320 static bool recursed = 0;
324 error_msg_and_die("Out of memory");
328 error_opt_arg(int opt, const char *arg)
330 error_msg_and_die("Invalid -%c argument: '%s'", opt, arg);
335 ptrace_attach_or_seize(int pid)
339 return ptrace(PTRACE_ATTACH, pid, 0, 0);
340 r = ptrace(PTRACE_SEIZE, pid, 0, 0);
343 r = ptrace(PTRACE_INTERRUPT, pid, 0, 0);
347 # define ptrace_attach_or_seize(pid) ptrace(PTRACE_ATTACH, (pid), 0, 0)
351 * Used when we want to unblock stopped traced process.
352 * Should be only used with PTRACE_CONT, PTRACE_DETACH and PTRACE_SYSCALL.
353 * Returns 0 on success or if error was ESRCH
354 * (presumably process was killed while we talk to it).
355 * Otherwise prints error message and returns -1.
358 ptrace_restart(int op, struct tcb *tcp, int sig)
364 ptrace(op, tcp->pid, (void *) 0, (long) sig);
370 if (op == PTRACE_CONT)
372 if (op == PTRACE_DETACH)
375 if (op == PTRACE_LISTEN)
379 * Why curcol != 0? Otherwise sometimes we get this:
381 * 10252 kill(10253, SIGKILL) = 0
382 * <ptrace(SYSCALL,10252):No such process>10253 ...next decode...
384 * 10252 died after we retrieved syscall exit data,
385 * but before we tried to restart it. Log looks ugly.
387 if (current_tcp && current_tcp->curcol != 0) {
388 tprintf(" <ptrace(%s):%s>\n", msg, strerror(err));
394 perror_msg("ptrace(PTRACE_%s,pid:%d,sig:%d)", msg, tcp->pid, sig);
399 set_cloexec_flag(int fd)
403 flags = fcntl(fd, F_GETFD);
405 /* Can happen only if fd is bad.
406 * Should never happen: if it does, we have a bug
407 * in the caller. Therefore we just abort
408 * instead of propagating the error.
410 perror_msg_and_die("fcntl(%d, F_GETFD)", fd);
413 newflags = flags | FD_CLOEXEC;
414 if (flags == newflags)
417 fcntl(fd, F_SETFD, newflags); /* never fails */
420 static void kill_save_errno(pid_t pid, int sig)
422 int saved_errno = errno;
424 (void) kill(pid, sig);
429 * When strace is setuid executable, we have to swap uids
430 * before and after filesystem and process management operations.
435 int euid = geteuid(), uid = getuid();
437 if (euid != uid && setreuid(euid, uid) < 0) {
438 perror_msg_and_die("setreuid");
443 # define fopen_for_output fopen64
444 # define struct_stat struct stat64
445 # define stat_file stat64
446 # define struct_dirent struct dirent64
447 # define read_dir readdir64
448 # define struct_rlimit struct rlimit64
449 # define set_rlimit setrlimit64
451 # define fopen_for_output fopen
452 # define struct_stat struct stat
453 # define stat_file stat
454 # define struct_dirent struct dirent
455 # define read_dir readdir
456 # define struct_rlimit struct rlimit
457 # define set_rlimit setrlimit
461 strace_fopen(const char *path)
466 fp = fopen_for_output(path, "w");
468 perror_msg_and_die("Can't fopen '%s'", path);
470 set_cloexec_flag(fileno(fp));
474 static int popen_pid = 0;
477 # define _PATH_BSHELL "/bin/sh"
481 * We cannot use standard popen(3) here because we have to distinguish
482 * popen child process from other processes we trace, and standard popen(3)
483 * does not export its child's pid.
486 strace_popen(const char *command)
493 perror_msg_and_die("pipe");
495 set_cloexec_flag(fds[1]); /* never fails */
499 perror_msg_and_die("vfork");
501 if (popen_pid == 0) {
506 perror_msg_and_die("dup2");
509 execl(_PATH_BSHELL, "sh", "-c", command, NULL);
510 perror_msg_and_die("Can't execute '%s'", _PATH_BSHELL);
516 fp = fdopen(fds[1], "w");
523 tprintf(const char *fmt, ...)
529 int n = strace_vfprintf(current_tcp->outf, fmt, args);
531 if (current_tcp->outf != stderr)
532 perror_msg("%s", outfname);
534 current_tcp->curcol += n;
540 tprints(const char *str)
543 int n = fputs_unlocked(str, current_tcp->outf);
545 current_tcp->curcol += strlen(str);
548 if (current_tcp->outf != stderr)
549 perror_msg("%s", outfname);
557 current_tcp->curcol = 0;
558 fflush(current_tcp->outf);
561 printing_tcp->curcol = 0;
567 printleader(struct tcb *tcp)
569 /* If -ff, "previous tcb we printed" is always the same as current,
570 * because we have per-tcb output files.
576 current_tcp = printing_tcp;
577 if (printing_tcp->curcol != 0 && (followfork < 2 || printing_tcp == tcp)) {
579 * case 1: we have a shared log (i.e. not -ff), and last line
580 * wasn't finished (same or different tcb, doesn't matter).
581 * case 2: split log, we are the same tcb, but our last line
582 * didn't finish ("SIGKILL nuked us after syscall entry" etc).
584 tprints(" <unfinished ...>\n");
585 printing_tcp->curcol = 0;
591 current_tcp->curcol = 0;
594 tprintf("%-5d ", tcp->pid);
595 else if (nprocs > 1 && !outfname)
596 tprintf("[pid %5u] ", tcp->pid);
599 char str[sizeof("HH:MM:SS")];
600 struct timeval tv, dtv;
601 static struct timeval otv;
603 gettimeofday(&tv, NULL);
607 tv_sub(&dtv, &tv, &otv);
608 tprintf("%6ld.%06ld ",
609 (long) dtv.tv_sec, (long) dtv.tv_usec);
612 else if (tflag > 2) {
613 tprintf("%ld.%06ld ",
614 (long) tv.tv_sec, (long) tv.tv_usec);
617 time_t local = tv.tv_sec;
618 strftime(str, sizeof(str), "%T", localtime(&local));
620 tprintf("%s.%06ld ", str, (long) tv.tv_usec);
632 if (current_tcp->curcol < acolumn)
633 tprints(acolumn_spaces + current_tcp->curcol);
636 /* Should be only called directly *after successful attach* to a tracee.
637 * Otherwise, "strace -oFILE -ff -p<nonexistant_pid>"
638 * may create bogus empty FILE.<nonexistant_pid>, and then die.
641 newoutf(struct tcb *tcp)
643 tcp->outf = shared_log; /* if not -ff mode, the same file is for all */
644 if (followfork >= 2) {
645 char name[520 + sizeof(int) * 3];
646 sprintf(name, "%.512s.%u", outfname, tcp->pid);
647 tcp->outf = strace_fopen(name);
654 /* Allocate some more TCBs and expand the table.
655 We don't want to relocate the TCBs because our
656 callers have pointers and it would be a pain.
657 So tcbtab is a table of pointers. Since we never
658 free the TCBs, we allocate a single chunk of many. */
660 struct tcb *newtcbs = calloc(tcbtabsize, sizeof(newtcbs[0]));
661 struct tcb **newtab = realloc(tcbtab, tcbtabsize * 2 * sizeof(tcbtab[0]));
662 if (!newtab || !newtcbs)
666 while (i < tcbtabsize)
667 tcbtab[i++] = newtcbs++;
676 if (nprocs == tcbtabsize)
679 for (i = 0; i < tcbtabsize; i++) {
681 if ((tcp->flags & TCB_INUSE) == 0) {
682 memset(tcp, 0, sizeof(*tcp));
684 tcp->flags = TCB_INUSE;
685 #if SUPPORTED_PERSONALITIES > 1
686 tcp->currpers = current_personality;
690 fprintf(stderr, "new tcb for pid %d, active tcbs:%d\n", tcp->pid, nprocs);
694 error_msg_and_die("bug in alloctcb");
698 droptcb(struct tcb *tcp)
705 fprintf(stderr, "dropped tcb for pid %d, %d remain\n", tcp->pid, nprocs);
708 if (followfork >= 2) {
709 if (tcp->curcol != 0)
710 fprintf(tcp->outf, " <detached ...>\n");
713 if (printing_tcp == tcp && tcp->curcol != 0)
714 fprintf(tcp->outf, " <detached ...>\n");
719 if (current_tcp == tcp)
721 if (printing_tcp == tcp)
724 memset(tcp, 0, sizeof(*tcp));
727 /* Detach traced process.
728 * Never call DETACH twice on the same process as both unattached and
729 * attached-unstopped processes give the same ESRCH. For unattached process we
730 * would SIGSTOP it and wait for its SIGSTOP notification forever.
733 detach(struct tcb *tcp)
736 int status, sigstop_expected, interrupt_done;
738 if (tcp->flags & TCB_BPTSET)
742 * Linux wrongly insists the child be stopped
743 * before detaching. Arghh. We go through hoops
744 * to make a clean break of things.
747 # undef PTRACE_DETACH
748 # define PTRACE_DETACH PTRACE_SUNDETACH
752 sigstop_expected = 0;
754 if (tcp->flags & TCB_ATTACHED) {
756 * We attached but possibly didn't see the expected SIGSTOP.
757 * We must catch exactly one as otherwise the detached process
758 * would be left stopped (process state T).
760 sigstop_expected = (tcp->flags & TCB_IGNORE_ONE_SIGSTOP);
761 error = ptrace(PTRACE_DETACH, tcp->pid, 0, 0);
763 /* On a clear day, you can see forever. */
765 else if (errno != ESRCH) {
766 /* Shouldn't happen. */
767 perror_msg("detach: ptrace(PTRACE_DETACH, ...)");
770 /* ESRCH: process is either not stopped or doesn't exist. */
771 if (my_tkill(tcp->pid, 0) < 0) {
773 /* Shouldn't happen. */
774 perror_msg("detach: checking sanity");
775 /* else: process doesn't exist. */
778 /* Process is not stopped. */
779 if (!sigstop_expected) {
780 /* We need to stop it. */
783 * With SEIZE, tracee can be in group-stop already.
784 * In this state sending it another SIGSTOP does nothing.
785 * Need to use INTERRUPT.
786 * Testcase: trying to ^C a "strace -p <stopped_process>".
788 error = ptrace(PTRACE_INTERRUPT, tcp->pid, 0, 0);
793 error = my_tkill(tcp->pid, SIGSTOP);
795 sigstop_expected = 1;
797 if (error && errno != ESRCH) {
799 perror_msg("detach: ptrace(PTRACE_INTERRUPT, ...)");
801 perror_msg("detach: stopping child");
806 if (sigstop_expected || interrupt_done) {
809 if (waitpid(tcp->pid, &status, __WALL) < 0) {
812 if (errno == ECHILD) /* Already gone. */
814 perror_msg("detach: waiting");
817 if (!WIFSTOPPED(status)) {
818 /* Au revoir, mon ami. */
821 sig = WSTOPSIG(status);
823 fprintf(stderr, "detach wait: event:%d sig:%d\n",
824 (unsigned)status >> 16, sig);
825 if (sigstop_expected && sig == SIGSTOP) {
826 /* Detach, suppressing SIGSTOP */
827 ptrace_restart(PTRACE_DETACH, tcp, 0);
830 if (interrupt_done) {
831 unsigned event = (unsigned)status >> 16;
832 if (event == PTRACE_EVENT_STOP /*&& sig == SIGTRAP*/) {
834 * sig == SIGTRAP: PTRACE_INTERRUPT stop.
835 * sig == other: process was already stopped
836 * with this stopping sig (see tests/detach-stopped).
837 * Looks like re-injecting this sig is not necessary
838 * in DETACH for the tracee to remain stopped.
843 * PTRACE_INTERRUPT is not guaranteed to produce
844 * the above event if other ptrace-stop is pending.
845 * See tests/detach-sleeping testcase:
846 * strace got SIGINT while tracee is sleeping.
847 * We sent PTRACE_INTERRUPT.
848 * We see syscall exit, not PTRACE_INTERRUPT stop.
849 * We won't get PTRACE_INTERRUPT stop
850 * if we would CONT now. Need to DETACH.
852 if (sig == syscall_trap_sig)
854 /* else: not sure in which case we can be here.
855 * Signal stop? Inject it while detaching.
857 ptrace_restart(PTRACE_DETACH, tcp, sig);
860 if (sig == syscall_trap_sig)
862 /* Can't detach just yet, may need to wait for SIGSTOP */
863 error = ptrace_restart(PTRACE_CONT, tcp, sig);
869 if (!qflag && (tcp->flags & TCB_ATTACHED))
870 fprintf(stderr, "Process %u detached\n", tcp->pid);
878 process_opt_p_list(char *opt)
882 * We accept -p PID,PID; -p "`pidof PROG`"; -p "`pgrep PROG`".
883 * pidof uses space as delim, pgrep uses newline. :(
886 char *delim = opt + strcspn(opt, ", \n\t");
890 pid = string_to_uint(opt);
892 error_msg_and_die("Invalid process id: '%s'", opt);
894 if (pid == strace_tracer_pid) {
895 error_msg_and_die("I'm sorry, I can't let you do that, Dave.");
912 * Block user interruptions as we would leave the traced
913 * process stopped (process state T) if we would terminate in
914 * between PTRACE_ATTACH and wait4() on SIGSTOP.
915 * We rely on cleanup() from this point on.
918 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
920 if (daemonized_tracer) {
923 perror_msg_and_die("fork");
925 if (pid) { /* parent */
927 * Wait for grandchild to attach to straced process
928 * (grandparent). Grandchild SIGKILLs us after it attached.
929 * Grandparent's wait() is unblocked by our death,
930 * it proceeds to exec the straced program.
933 _exit(0); /* paranoia */
936 /* We will be the tracer process. Remember our new pid: */
937 strace_tracer_pid = getpid();
940 for (tcbi = 0; tcbi < tcbtabsize; tcbi++) {
943 if (!(tcp->flags & TCB_INUSE))
946 /* Is this a process we should attach to, but not yet attached? */
947 if (tcp->flags & TCB_ATTACHED)
948 continue; /* no, we already attached it */
950 if (followfork && !daemonized_tracer) {
951 char procdir[sizeof("/proc/%d/task") + sizeof(int) * 3];
954 sprintf(procdir, "/proc/%d/task", tcp->pid);
955 dir = opendir(procdir);
957 unsigned int ntid = 0, nerr = 0;
960 while ((de = read_dir(dir)) != NULL) {
964 if (de->d_fileno == 0)
966 /* we trust /proc filesystem */
967 tid = atoi(de->d_name);
971 if (ptrace_attach_or_seize(tid) < 0) {
974 fprintf(stderr, "attach to pid %d failed\n", tid);
978 fprintf(stderr, "attach to pid %d succeeded\n", tid);
981 cur_tcp = alloctcb(tid);
982 cur_tcp->flags |= TCB_ATTACHED | TCB_STARTUP | post_attach_sigstop;
987 sigprocmask(SIG_SETMASK, &empty_set, NULL);
990 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
994 perror_msg("attach: ptrace(PTRACE_ATTACH, ...)");
999 fprintf(stderr, ntid > 1
1000 ? "Process %u attached with %u threads\n"
1001 : "Process %u attached\n",
1004 if (!(tcp->flags & TCB_ATTACHED)) {
1005 /* -p PID, we failed to attach to PID itself
1006 * but did attach to some of its sibling threads.
1012 } /* if (opendir worked) */
1014 if (ptrace_attach_or_seize(tcp->pid) < 0) {
1015 perror_msg("attach: ptrace(PTRACE_ATTACH, ...)");
1019 tcp->flags |= TCB_ATTACHED | TCB_STARTUP | post_attach_sigstop;
1022 fprintf(stderr, "attach to pid %d (main) succeeded\n", tcp->pid);
1024 if (daemonized_tracer) {
1026 * Make parent go away.
1027 * Also makes grandparent's wait() unblock.
1029 kill(getppid(), SIGKILL);
1034 "Process %u attached\n",
1036 } /* for each tcbtab[] */
1040 sigprocmask(SIG_SETMASK, &empty_set, NULL);
1043 /* Stack-o-phobic exec helper, in the hope to work around
1044 * NOMMU + "daemonized tracer" difficulty.
1046 struct exec_params {
1053 static struct exec_params params_for_tracee;
1054 static void __attribute__ ((noinline, noreturn))
1057 struct exec_params *params = ¶ms_for_tracee;
1059 if (params->fd_to_close >= 0)
1060 close(params->fd_to_close);
1061 if (!daemonized_tracer && !use_seize) {
1062 if (ptrace(PTRACE_TRACEME, 0L, 0L, 0L) < 0) {
1063 perror_msg_and_die("ptrace(PTRACE_TRACEME, ...)");
1067 if (username != NULL) {
1069 * It is important to set groups before we
1070 * lose privileges on setuid.
1072 if (initgroups(username, run_gid) < 0) {
1073 perror_msg_and_die("initgroups");
1075 if (setregid(run_gid, params->run_egid) < 0) {
1076 perror_msg_and_die("setregid");
1078 if (setreuid(run_uid, params->run_euid) < 0) {
1079 perror_msg_and_die("setreuid");
1082 else if (geteuid() != 0)
1083 if (setreuid(run_uid, run_uid) < 0) {
1084 perror_msg_and_die("setreuid");
1087 if (!daemonized_tracer) {
1089 * Induce a ptrace stop. Tracer (our parent)
1090 * will resume us with PTRACE_SYSCALL and display
1091 * the immediately following execve syscall.
1092 * Can't do this on NOMMU systems, we are after
1093 * vfork: parent is blocked, stopping would deadlock.
1096 kill(getpid(), SIGSTOP);
1099 /* we depend on SIGCHLD set to SIG_DFL by init code */
1100 /* if it happens to be SIG_IGN'ed, wait won't block */
1105 execv(params->pathname, params->argv);
1106 perror_msg_and_die("exec");
1110 startup_child(char **argv)
1112 struct_stat statbuf;
1113 const char *filename;
1114 char pathname[MAXPATHLEN];
1119 if (strchr(filename, '/')) {
1120 if (strlen(filename) > sizeof pathname - 1) {
1121 errno = ENAMETOOLONG;
1122 perror_msg_and_die("exec");
1124 strcpy(pathname, filename);
1126 #ifdef USE_DEBUGGING_EXEC
1128 * Debuggers customarily check the current directory
1129 * first regardless of the path but doing that gives
1130 * security geeks a panic attack.
1132 else if (stat_file(filename, &statbuf) == 0)
1133 strcpy(pathname, filename);
1134 #endif /* USE_DEBUGGING_EXEC */
1139 for (path = getenv("PATH"); path && *path; path += m) {
1140 const char *colon = strchr(path, ':');
1146 m = n = strlen(path);
1148 if (!getcwd(pathname, MAXPATHLEN))
1150 len = strlen(pathname);
1152 else if (n > sizeof pathname - 1)
1155 strncpy(pathname, path, n);
1158 if (len && pathname[len - 1] != '/')
1159 pathname[len++] = '/';
1160 strcpy(pathname + len, filename);
1161 if (stat_file(pathname, &statbuf) == 0 &&
1162 /* Accept only regular files
1163 with some execute bits set.
1164 XXX not perfect, might still fail */
1165 S_ISREG(statbuf.st_mode) &&
1166 (statbuf.st_mode & 0111))
1170 if (stat_file(pathname, &statbuf) < 0) {
1171 perror_msg_and_die("Can't stat '%s'", filename);
1174 params_for_tracee.fd_to_close = (shared_log != stderr) ? fileno(shared_log) : -1;
1175 params_for_tracee.run_euid = (statbuf.st_mode & S_ISUID) ? statbuf.st_uid : run_uid;
1176 params_for_tracee.run_egid = (statbuf.st_mode & S_ISGID) ? statbuf.st_gid : run_gid;
1177 params_for_tracee.argv = argv;
1179 * On NOMMU, can be safely freed only after execve in tracee.
1180 * It's hard to know when that happens, so we just leak it.
1182 params_for_tracee.pathname = NOMMU_SYSTEM ? strdup(pathname) : pathname;
1184 #if defined HAVE_PRCTL && defined PR_SET_PTRACER && defined PR_SET_PTRACER_ANY
1185 if (daemonized_tracer)
1186 prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY);
1189 strace_child = pid = fork();
1191 perror_msg_and_die("fork");
1193 if ((pid != 0 && daemonized_tracer)
1194 || (pid == 0 && !daemonized_tracer)
1196 /* We are to become the tracee. Two cases:
1198 * not -D: we are child
1203 /* We are the tracer */
1205 if (!daemonized_tracer) {
1207 /* child did PTRACE_TRACEME, nothing to do in parent */
1209 if (!NOMMU_SYSTEM) {
1210 /* Wait until child stopped itself */
1212 while (waitpid(pid, &status, WSTOPPED) < 0) {
1215 perror_msg_and_die("waitpid");
1217 if (!WIFSTOPPED(status) || WSTOPSIG(status) != SIGSTOP) {
1218 kill_save_errno(pid, SIGKILL);
1219 perror_msg_and_die("Unexpected wait status %x", status);
1222 /* Else: NOMMU case, we have no way to sync.
1223 * Just attach to it as soon as possible.
1224 * This means that we may miss a few first syscalls...
1227 if (ptrace_attach_or_seize(pid)) {
1228 kill_save_errno(pid, SIGKILL);
1229 perror_msg_and_die("Can't attach to %d", pid);
1234 tcp = alloctcb(pid);
1236 tcp->flags |= TCB_ATTACHED | TCB_STRACE_CHILD | TCB_STARTUP | post_attach_sigstop;
1238 tcp->flags |= TCB_ATTACHED | TCB_STRACE_CHILD | TCB_STARTUP;
1242 /* With -D, we are *child* here, IOW: different pid. Fetch it: */
1243 strace_tracer_pid = getpid();
1244 /* The tracee is our parent: */
1247 /* attaching will be done later, by startup_attach */
1248 /* note: we don't do newoutf(tcp) here either! */
1250 /* NOMMU BUG! -D mode is active, we (child) return,
1251 * and we will scribble over parent's stack!
1252 * When parent later unpauses, it segfaults.
1255 * (1) by declaring exec_or_die() NORETURN,
1256 * hopefully compiler will just jump to it
1257 * instead of call (won't push anything to stack),
1258 * (2) by trying very hard in exec_or_die()
1259 * to not use any stack,
1260 * (3) having a really big (MAXPATHLEN) stack object
1261 * in this function, which creates a "buffer" between
1262 * child's and parent's stack pointers.
1263 * This may save us if (1) and (2) failed
1264 * and compiler decided to use stack in exec_or_die() anyway
1265 * (happens on i386 because of stack parameter passing).
1267 * A cleaner solution is to use makecontext + setcontext
1268 * to create a genuine separate stack and execute on it.
1274 * Test whether the kernel support PTRACE_O_TRACECLONE et al options.
1275 * First fork a new child, call ptrace with PTRACE_SETOPTIONS on it,
1276 * and then see which options are supported by the kernel.
1279 test_ptrace_setoptions_followfork(void)
1281 int pid, expected_grandchild = 0, found_grandchild = 0;
1282 const unsigned int test_options = PTRACE_O_TRACECLONE |
1283 PTRACE_O_TRACEFORK |
1284 PTRACE_O_TRACEVFORK;
1286 /* Need fork for test. NOMMU has no forks */
1288 goto worked; /* be bold, and pretend that test succeeded */
1292 perror_msg_and_die("fork");
1295 if (ptrace(PTRACE_TRACEME, 0L, 0L, 0L) < 0)
1296 perror_msg_and_die("%s: PTRACE_TRACEME doesn't work",
1298 kill_save_errno(pid, SIGSTOP);
1300 perror_msg_and_die("fork");
1305 int status, tracee_pid;
1308 tracee_pid = wait(&status);
1309 if (tracee_pid <= 0) {
1312 if (errno == ECHILD)
1314 kill_save_errno(pid, SIGKILL);
1315 perror_msg_and_die("%s: unexpected wait result %d",
1316 __func__, tracee_pid);
1318 if (WIFEXITED(status)) {
1319 if (WEXITSTATUS(status)) {
1320 if (tracee_pid != pid)
1321 kill_save_errno(pid, SIGKILL);
1322 error_msg_and_die("%s: unexpected exit status %u",
1323 __func__, WEXITSTATUS(status));
1327 if (WIFSIGNALED(status)) {
1328 if (tracee_pid != pid)
1329 kill_save_errno(pid, SIGKILL);
1330 error_msg_and_die("%s: unexpected signal %u",
1331 __func__, WTERMSIG(status));
1333 if (!WIFSTOPPED(status)) {
1334 if (tracee_pid != pid)
1335 kill_save_errno(tracee_pid, SIGKILL);
1336 kill_save_errno(pid, SIGKILL);
1337 error_msg_and_die("%s: unexpected wait status %x",
1340 if (tracee_pid != pid) {
1341 found_grandchild = tracee_pid;
1342 if (ptrace(PTRACE_CONT, tracee_pid, 0, 0) < 0) {
1343 kill_save_errno(tracee_pid, SIGKILL);
1344 kill_save_errno(pid, SIGKILL);
1345 perror_msg_and_die("PTRACE_CONT doesn't work");
1349 switch (WSTOPSIG(status)) {
1351 if (ptrace(PTRACE_SETOPTIONS, pid, 0, test_options) < 0
1352 && errno != EINVAL && errno != EIO)
1353 perror_msg("PTRACE_SETOPTIONS");
1356 if (status >> 16 == PTRACE_EVENT_FORK) {
1359 if (ptrace(PTRACE_GETEVENTMSG, pid,
1360 NULL, (long) &msg) == 0)
1361 expected_grandchild = msg;
1365 if (ptrace(PTRACE_SYSCALL, pid, 0, 0) < 0) {
1366 kill_save_errno(pid, SIGKILL);
1367 perror_msg_and_die("PTRACE_SYSCALL doesn't work");
1370 if (expected_grandchild && expected_grandchild == found_grandchild) {
1372 ptrace_setoptions |= test_options;
1374 fprintf(stderr, "ptrace_setoptions = %#x\n",
1378 error_msg("Test for PTRACE_O_TRACECLONE failed, "
1379 "giving up using this feature.");
1384 * Test whether the kernel support PTRACE_O_TRACESYSGOOD.
1385 * First fork a new child, call ptrace(PTRACE_SETOPTIONS) on it,
1386 * and then see whether it will stop with (SIGTRAP | 0x80).
1388 * Use of this option enables correct handling of user-generated SIGTRAPs,
1389 * and SIGTRAPs generated by special instructions such as int3 on x86:
1390 * _start: .globl _start
1395 * (compile with: "gcc -nostartfiles -nostdlib -o int3 int3.S")
1398 test_ptrace_setoptions_for_all(void)
1400 const unsigned int test_options = PTRACE_O_TRACESYSGOOD |
1405 /* Need fork for test. NOMMU has no forks */
1407 goto worked; /* be bold, and pretend that test succeeded */
1411 perror_msg_and_die("fork");
1415 if (ptrace(PTRACE_TRACEME, 0L, 0L, 0L) < 0)
1416 /* Note: exits with exitcode 1 */
1417 perror_msg_and_die("%s: PTRACE_TRACEME doesn't work",
1420 _exit(0); /* parent should see entry into this syscall */
1424 int status, tracee_pid;
1427 tracee_pid = wait(&status);
1428 if (tracee_pid <= 0) {
1431 kill_save_errno(pid, SIGKILL);
1432 perror_msg_and_die("%s: unexpected wait result %d",
1433 __func__, tracee_pid);
1435 if (WIFEXITED(status)) {
1436 if (WEXITSTATUS(status) == 0)
1438 error_msg_and_die("%s: unexpected exit status %u",
1439 __func__, WEXITSTATUS(status));
1441 if (WIFSIGNALED(status)) {
1442 error_msg_and_die("%s: unexpected signal %u",
1443 __func__, WTERMSIG(status));
1445 if (!WIFSTOPPED(status)) {
1447 error_msg_and_die("%s: unexpected wait status %x",
1450 if (WSTOPSIG(status) == SIGSTOP) {
1452 * We don't check "options aren't accepted" error.
1453 * If it happens, we'll never get (SIGTRAP | 0x80),
1454 * and thus will decide to not use the option.
1455 * IOW: the outcome of the test will be correct.
1457 if (ptrace(PTRACE_SETOPTIONS, pid, 0L, test_options) < 0
1458 && errno != EINVAL && errno != EIO)
1459 perror_msg("PTRACE_SETOPTIONS");
1461 if (WSTOPSIG(status) == (SIGTRAP | 0x80)) {
1464 if (ptrace(PTRACE_SYSCALL, pid, 0L, 0L) < 0) {
1465 kill_save_errno(pid, SIGKILL);
1466 perror_msg_and_die("PTRACE_SYSCALL doesn't work");
1472 syscall_trap_sig = (SIGTRAP | 0x80);
1473 ptrace_setoptions |= test_options;
1475 fprintf(stderr, "ptrace_setoptions = %#x\n",
1480 error_msg("Test for PTRACE_O_TRACESYSGOOD failed, "
1481 "giving up using this feature.");
1487 test_ptrace_seize(void)
1491 /* Need fork for test. NOMMU has no forks */
1493 post_attach_sigstop = 0; /* this sets use_seize to 1 */
1499 perror_msg_and_die("fork");
1506 /* PTRACE_SEIZE, unlike ATTACH, doesn't force tracee to trap. After
1507 * attaching tracee continues to run unless a trap condition occurs.
1508 * PTRACE_SEIZE doesn't affect signal or group stop state.
1510 if (ptrace(PTRACE_SEIZE, pid, 0, 0) == 0) {
1511 post_attach_sigstop = 0; /* this sets use_seize to 1 */
1512 } else if (debug_flag) {
1513 fprintf(stderr, "PTRACE_SEIZE doesn't work\n");
1519 int status, tracee_pid;
1522 tracee_pid = waitpid(pid, &status, 0);
1523 if (tracee_pid <= 0) {
1526 perror_msg_and_die("%s: unexpected wait result %d",
1527 __func__, tracee_pid);
1529 if (WIFSIGNALED(status)) {
1532 error_msg_and_die("%s: unexpected wait status %x",
1536 #else /* !USE_SEIZE */
1537 # define test_ptrace_seize() ((void)0)
1541 get_os_release(void)
1547 perror_msg_and_die("uname");
1548 /* u.release has this form: "3.2.9[-some-garbage]" */
1552 if (!(*p >= '0' && *p <= '9'))
1553 error_msg_and_die("Bad OS release string: '%s'", u.release);
1554 /* Note: this open-codes KERNEL_VERSION(): */
1555 rel = (rel << 8) | atoi(p);
1556 if (rel >= KERNEL_VERSION(1,0,0))
1558 while (*p >= '0' && *p <= '9')
1561 if (rel >= KERNEL_VERSION(0,1,0)) {
1562 /* "X.Y-something" means "X.Y.0" */
1566 error_msg_and_die("Bad OS release string: '%s'", u.release);
1574 * Initialization part of main() was eating much stack (~0.5k),
1575 * which was unused after init.
1576 * We can reuse it if we move init code into a separate function.
1578 * Don't want main() to inline us and defeat the reason
1579 * we have a separate function.
1581 static void __attribute__ ((noinline))
1582 init(int argc, char *argv[])
1587 struct sigaction sa;
1589 progname = argv[0] ? argv[0] : "strace";
1591 /* Make sure SIGCHLD has the default action so that waitpid
1592 definitely works without losing track of children. The user
1593 should not have given us a bogus state to inherit, but he might
1594 have. Arguably we should detect SIG_IGN here and pass it on
1595 to children, but probably noone really needs that. */
1596 signal(SIGCHLD, SIG_DFL);
1598 strace_tracer_pid = getpid();
1600 os_release = get_os_release();
1602 /* Allocate the initial tcbtab. */
1603 tcbtabsize = argc; /* Surely enough for all -p args. */
1604 tcbtab = calloc(tcbtabsize, sizeof(tcbtab[0]));
1606 die_out_of_memory();
1607 tcp = calloc(tcbtabsize, sizeof(*tcp));
1609 die_out_of_memory();
1610 for (c = 0; c < tcbtabsize; c++)
1613 shared_log = stderr;
1614 set_sortby(DEFAULT_SORTBY);
1615 set_personality(DEFAULT_PERSONALITY);
1616 qualify("trace=all");
1617 qualify("abbrev=all");
1618 qualify("verbose=all");
1619 #if DEFAULT_QUAL_FLAGS != (QUAL_TRACE | QUAL_ABBREV | QUAL_VERBOSE)
1620 # error Bug in DEFAULT_QUAL_FLAGS
1622 qualify("signal=all");
1623 while ((c = getopt(argc, argv,
1624 "+b:cCdfFhiqrtTvVxyz"
1626 "a:e:o:O:p:s:S:u:E:P:I:")) != EOF) {
1629 if (strcmp(optarg, "execve") != 0)
1630 error_msg_and_die("Syscall '%s' for -b isn't supported",
1632 detach_on_execve = 1;
1635 if (cflag == CFLAG_BOTH) {
1636 error_msg_and_die("-c and -C are mutually exclusive");
1638 cflag = CFLAG_ONLY_STATS;
1641 if (cflag == CFLAG_ONLY_STATS) {
1642 error_msg_and_die("-c and -C are mutually exclusive");
1650 daemonized_tracer = 1;
1669 /* fall through to tflag++ */
1683 qualify("abbrev=none");
1686 printf("%s -- version %s\n", PACKAGE_NAME, VERSION);
1690 not_failing_only = 1;
1693 acolumn = string_to_uint(optarg);
1695 error_opt_arg(c, optarg);
1701 outfname = strdup(optarg);
1704 i = string_to_uint(optarg);
1706 error_opt_arg(c, optarg);
1710 process_opt_p_list(optarg);
1713 pathtrace_select(optarg);
1716 i = string_to_uint(optarg);
1718 error_opt_arg(c, optarg);
1725 username = strdup(optarg);
1728 if (putenv(optarg) < 0)
1729 die_out_of_memory();
1732 opt_intr = string_to_uint(optarg);
1733 if (opt_intr <= 0 || opt_intr >= NUM_INTR_OPTS)
1734 error_opt_arg(c, optarg);
1742 /* argc -= optind; - no need, argc is not used below */
1744 acolumn_spaces = malloc(acolumn + 1);
1745 if (!acolumn_spaces)
1746 die_out_of_memory();
1747 memset(acolumn_spaces, ' ', acolumn);
1748 acolumn_spaces[acolumn] = '\0';
1750 /* Must have PROG [ARGS], or -p PID. Not both. */
1751 if (!argv[0] == !nprocs)
1754 if (nprocs != 0 && daemonized_tracer) {
1755 error_msg_and_die("-D and -p are mutually exclusive");
1761 if (followfork >= 2 && cflag) {
1762 error_msg_and_die("(-c or -C) and -ff are mutually exclusive");
1765 /* See if they want to run as another user. */
1766 if (username != NULL) {
1767 struct passwd *pent;
1769 if (getuid() != 0 || geteuid() != 0) {
1770 error_msg_and_die("You must be root to use the -u option");
1772 pent = getpwnam(username);
1774 error_msg_and_die("Cannot find user '%s'", username);
1776 run_uid = pent->pw_uid;
1777 run_gid = pent->pw_gid;
1785 * On any reasonably recent Linux kernel (circa about 2.5.46)
1786 * need_fork_exec_workarounds should stay 0 after these tests:
1788 /*need_fork_exec_workarounds = 0; - already is */
1790 need_fork_exec_workarounds = test_ptrace_setoptions_followfork();
1791 need_fork_exec_workarounds |= test_ptrace_setoptions_for_all();
1792 test_ptrace_seize();
1794 /* Check if they want to redirect the output. */
1796 /* See if they want to pipe the output. */
1797 if (outfname[0] == '|' || outfname[0] == '!') {
1799 * We can't do the <outfname>.PID funny business
1800 * when using popen, so prohibit it.
1802 if (followfork >= 2)
1803 error_msg_and_die("Piping the output and -ff are mutually exclusive");
1804 shared_log = strace_popen(outfname + 1);
1806 else if (followfork < 2)
1807 shared_log = strace_fopen(outfname);
1809 /* -ff without -o FILE is the same as single -f */
1810 if (followfork >= 2)
1814 if (!outfname || outfname[0] == '|' || outfname[0] == '!') {
1815 char *buf = malloc(BUFSIZ);
1817 die_out_of_memory();
1818 setvbuf(shared_log, buf, _IOLBF, BUFSIZ);
1820 if (outfname && argv[0]) {
1822 opt_intr = INTR_NEVER;
1826 opt_intr = INTR_WHILE_WAIT;
1828 /* argv[0] -pPID -oFILE Default interactive setting
1829 * yes 0 0 INTR_WHILE_WAIT
1830 * no 1 0 INTR_WHILE_WAIT
1831 * yes 0 1 INTR_NEVER
1832 * no 1 1 INTR_WHILE_WAIT
1835 sigemptyset(&empty_set);
1836 sigemptyset(&blocked_set);
1838 /* startup_child() must be called before the signal handlers get
1839 * installed below as they are inherited into the spawned process.
1840 * Also we do not need to be protected by them as during interruption
1841 * in the startup_child() mode we kill the spawned process anyway.
1844 if (!NOMMU_SYSTEM || daemonized_tracer)
1845 hide_log_until_execve = 1;
1846 skip_one_b_execve = 1;
1847 startup_child(argv);
1850 sa.sa_handler = SIG_IGN;
1851 sigemptyset(&sa.sa_mask);
1853 sigaction(SIGTTOU, &sa, NULL); /* SIG_IGN */
1854 sigaction(SIGTTIN, &sa, NULL); /* SIG_IGN */
1855 if (opt_intr != INTR_ANYWHERE) {
1856 if (opt_intr == INTR_BLOCK_TSTP_TOO)
1857 sigaction(SIGTSTP, &sa, NULL); /* SIG_IGN */
1859 * In interactive mode (if no -o OUTFILE, or -p PID is used),
1860 * fatal signals are blocked while syscall stop is processed,
1861 * and acted on in between, when waiting for new syscall stops.
1862 * In non-interactive mode, signals are ignored.
1864 if (opt_intr == INTR_WHILE_WAIT) {
1865 sigaddset(&blocked_set, SIGHUP);
1866 sigaddset(&blocked_set, SIGINT);
1867 sigaddset(&blocked_set, SIGQUIT);
1868 sigaddset(&blocked_set, SIGPIPE);
1869 sigaddset(&blocked_set, SIGTERM);
1870 sa.sa_handler = interrupt;
1872 /* SIG_IGN, or set handler for these */
1873 sigaction(SIGHUP, &sa, NULL);
1874 sigaction(SIGINT, &sa, NULL);
1875 sigaction(SIGQUIT, &sa, NULL);
1876 sigaction(SIGPIPE, &sa, NULL);
1877 sigaction(SIGTERM, &sa, NULL);
1879 if (nprocs != 0 || daemonized_tracer)
1882 /* Do we want pids printed in our -o OUTFILE?
1883 * -ff: no (every pid has its own file); or
1884 * -f: yes (there can be more pids in the future); or
1885 * -p PID1,PID2: yes (there are already more than one pid)
1887 print_pid_pfx = (outfname && followfork < 2 && (followfork == 1 || nprocs > 1));
1898 for (i = 0; i < tcbtabsize; i++) {
1899 struct tcb *tcp = tcbtab[i];
1900 if (tcp->pid == pid && (tcp->flags & TCB_INUSE))
1914 /* 'interrupted' is a volatile object, fetch it only once */
1915 fatal_sig = interrupted;
1917 fatal_sig = SIGTERM;
1919 for (i = 0; i < tcbtabsize; i++) {
1921 if (!(tcp->flags & TCB_INUSE))
1925 "cleanup: looking at pid %u\n", tcp->pid);
1926 if (tcp->flags & TCB_STRACE_CHILD) {
1927 kill(tcp->pid, SIGCONT);
1928 kill(tcp->pid, fatal_sig);
1933 call_summary(shared_log);
1947 while (nprocs != 0) {
1959 sigprocmask(SIG_SETMASK, &empty_set, NULL);
1960 pid = wait4(-1, &status, __WALL, (cflag ? &ru : NULL));
1963 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
1966 if (wait_errno == EINTR)
1968 if (wait_errno == ECHILD)
1969 /* Should not happen since nprocs > 0 */
1972 perror_msg("wait4(__WALL)");
1976 if (pid == popen_pid) {
1977 if (WIFEXITED(status) || WIFSIGNALED(status))
1982 event = ((unsigned)status >> 16);
1984 char buf[sizeof("WIFEXITED,exitcode=%u") + sizeof(int)*3 /*paranoia:*/ + 16];
1985 char evbuf[sizeof(",PTRACE_EVENT_?? (%u)") + sizeof(int)*3 /*paranoia:*/ + 16];
1987 if (WIFSIGNALED(status))
1989 sprintf(buf, "WIFSIGNALED,%ssig=%s",
1990 WCOREDUMP(status) ? "core," : "",
1991 signame(WTERMSIG(status)));
1993 sprintf(buf, "WIFSIGNALED,sig=%s",
1994 signame(WTERMSIG(status)));
1996 if (WIFEXITED(status))
1997 sprintf(buf, "WIFEXITED,exitcode=%u", WEXITSTATUS(status));
1998 if (WIFSTOPPED(status))
1999 sprintf(buf, "WIFSTOPPED,sig=%s", signame(WSTOPSIG(status)));
2001 if (WIFCONTINUED(status))
2002 strcpy(buf, "WIFCONTINUED");
2006 static const char *const event_names[] = {
2007 [PTRACE_EVENT_CLONE] = "CLONE",
2008 [PTRACE_EVENT_FORK] = "FORK",
2009 [PTRACE_EVENT_VFORK] = "VFORK",
2010 [PTRACE_EVENT_VFORK_DONE] = "VFORK_DONE",
2011 [PTRACE_EVENT_EXEC] = "EXEC",
2012 [PTRACE_EVENT_EXIT] = "EXIT",
2015 if (event < ARRAY_SIZE(event_names))
2016 e = event_names[event];
2018 sprintf(buf, "?? (%u)", event);
2021 sprintf(evbuf, ",PTRACE_EVENT_%s", e);
2023 fprintf(stderr, " [wait(0x%04x) = %u] %s%s\n", status, pid, buf, evbuf);
2026 /* Look up 'pid' in our table. */
2031 tcp = alloctcb(pid);
2032 tcp->flags |= TCB_ATTACHED | TCB_STARTUP | post_attach_sigstop;
2035 fprintf(stderr, "Process %d attached\n",
2038 /* This can happen if a clone call used
2039 CLONE_PTRACE itself. */
2040 if (WIFSTOPPED(status))
2041 ptrace(PTRACE_CONT, pid, (char *) 0, 0);
2042 error_msg_and_die("Unknown pid: %u", pid);
2047 if (WIFSTOPPED(status))
2050 /* Under Linux, execve changes pid to thread leader's pid,
2051 * and we see this changed pid on EVENT_EXEC and later,
2052 * execve sysexit. Leader "disappears" without exit
2053 * notification. Let user know that, drop leader's tcb,
2054 * and fix up pid in execve thread's tcb.
2055 * Effectively, execve thread's tcb replaces leader's tcb.
2057 * BTW, leader is 'stuck undead' (doesn't report WIFEXITED
2058 * on exit syscall) in multithreaded programs exactly
2059 * in order to handle this case.
2061 * PTRACE_GETEVENTMSG returns old pid starting from Linux 3.0.
2062 * On 2.6 and earlier, it can return garbage.
2064 if (event == PTRACE_EVENT_EXEC && os_release >= KERNEL_VERSION(3,0,0)) {
2066 struct tcb *execve_thread;
2069 if (ptrace(PTRACE_GETEVENTMSG, pid, NULL, (long) &old_pid) < 0)
2070 goto dont_switch_tcbs;
2071 if (old_pid <= 0 || old_pid == pid)
2072 goto dont_switch_tcbs;
2073 execve_thread = pid2tcb(old_pid);
2074 /* It should be !NULL, but I feel paranoid */
2076 goto dont_switch_tcbs;
2078 if (execve_thread->curcol != 0) {
2080 * One case we are here is -ff:
2081 * try "strace -oLOG -ff test/threaded_execve"
2083 fprintf(execve_thread->outf, " <pid changed to %d ...>\n", pid);
2084 /*execve_thread->curcol = 0; - no need, see code below */
2086 /* Swap output FILEs (needed for -ff) */
2087 fp = execve_thread->outf;
2088 execve_thread->outf = tcp->outf;
2090 /* And their column positions */
2091 execve_thread->curcol = tcp->curcol;
2093 /* Drop leader, but close execve'd thread outfile (if -ff) */
2095 /* Switch to the thread, reusing leader's outfile and pid */
2096 tcp = execve_thread;
2098 if (cflag != CFLAG_ONLY_STATS) {
2100 tprintf("+++ superseded by execve in pid %lu +++\n", old_pid);
2102 tcp->flags |= TCB_REPRINT;
2107 if (event == PTRACE_EVENT_EXEC) {
2108 if (detach_on_execve && !skip_one_b_execve)
2109 detach(tcp); /* do "-b execve" thingy */
2110 skip_one_b_execve = 0;
2113 /* Set current output file */
2117 tv_sub(&tcp->dtime, &ru.ru_stime, &tcp->stime);
2118 tcp->stime = ru.ru_stime;
2121 if (WIFSIGNALED(status)) {
2122 if (pid == strace_child)
2123 exit_code = 0x100 | WTERMSIG(status);
2124 if (cflag != CFLAG_ONLY_STATS
2125 && (qual_flags[WTERMSIG(status)] & QUAL_SIGNAL)
2129 tprintf("+++ killed by %s %s+++\n",
2130 signame(WTERMSIG(status)),
2131 WCOREDUMP(status) ? "(core dumped) " : "");
2133 tprintf("+++ killed by %s +++\n",
2134 signame(WTERMSIG(status)));
2141 if (WIFEXITED(status)) {
2142 if (pid == strace_child)
2143 exit_code = WEXITSTATUS(status);
2144 if (cflag != CFLAG_ONLY_STATS &&
2147 tprintf("+++ exited with %d +++\n", WEXITSTATUS(status));
2153 if (!WIFSTOPPED(status)) {
2154 fprintf(stderr, "PANIC: pid %u not stopped\n", pid);
2159 /* Is this the very first time we see this tracee stopped? */
2160 if (tcp->flags & TCB_STARTUP) {
2162 fprintf(stderr, "pid %d has TCB_STARTUP, initializing it\n", tcp->pid);
2163 tcp->flags &= ~TCB_STARTUP;
2164 if (tcp->flags & TCB_BPTSET) {
2166 * One example is a breakpoint inherited from
2167 * parent through fork().
2169 if (clearbpt(tcp) < 0) {
2176 if (ptrace_setoptions) {
2178 fprintf(stderr, "setting opts %x on pid %d\n", ptrace_setoptions, tcp->pid);
2179 if (ptrace(PTRACE_SETOPTIONS, tcp->pid, NULL, ptrace_setoptions) < 0) {
2180 if (errno != ESRCH) {
2181 /* Should never happen, really */
2182 perror_msg_and_die("PTRACE_SETOPTIONS");
2188 sig = WSTOPSIG(status);
2193 if (event == PTRACE_EVENT_STOP) {
2195 * PTRACE_INTERRUPT-stop or group-stop.
2196 * PTRACE_INTERRUPT-stop has sig == SIGTRAP here.
2208 goto restart_tracee_with_sig_0;
2211 /* Is this post-attach SIGSTOP?
2212 * Interestingly, the process may stop
2213 * with STOPSIG equal to some other signal
2214 * than SIGSTOP if we happend to attach
2215 * just before the process takes a signal.
2217 if (sig == SIGSTOP && (tcp->flags & TCB_IGNORE_ONE_SIGSTOP)) {
2219 fprintf(stderr, "ignored SIGSTOP on pid %d\n", tcp->pid);
2220 tcp->flags &= ~TCB_IGNORE_ONE_SIGSTOP;
2221 goto restart_tracee_with_sig_0;
2224 if (sig != syscall_trap_sig) {
2227 /* Nonzero (true) if tracee is stopped by signal
2228 * (as opposed to "tracee received signal").
2229 * TODO: shouldn't we check for errno == EINVAL too?
2230 * We can get ESRCH instead, you know...
2232 stopped = (ptrace(PTRACE_GETSIGINFO, pid, 0, (long) &si) < 0);
2236 if (cflag != CFLAG_ONLY_STATS
2237 && !hide_log_until_execve
2238 && (qual_flags[sig] & QUAL_SIGNAL)
2240 #if defined(PT_CR_IPSR) && defined(PT_CR_IIP)
2244 upeek(tcp, PT_CR_IPSR, &psr);
2245 upeek(tcp, PT_CR_IIP, &pc);
2248 pc += (psr >> PSR_RI) & 0x3;
2249 # define PC_FORMAT_STR " @ %lx"
2250 # define PC_FORMAT_ARG , pc
2252 # define PC_FORMAT_STR ""
2253 # define PC_FORMAT_ARG /* nothing */
2257 tprintf("--- %s ", signame(sig));
2258 printsiginfo(&si, verbose(tcp));
2259 tprintf(PC_FORMAT_STR " ---\n"
2262 tprintf("--- stopped by %s" PC_FORMAT_STR " ---\n",
2269 /* It's signal-delivery-stop. Inject the signal */
2270 goto restart_tracee;
2272 /* It's group-stop */
2275 * This ends ptrace-stop, but does *not* end group-stop.
2276 * This makes stopping signals work properly on straced process
2277 * (that is, process really stops. It used to continue to run).
2279 if (ptrace_restart(PTRACE_LISTEN, tcp, 0) < 0) {
2285 /* We don't have PTRACE_LISTEN support... */
2286 goto restart_tracee;
2289 /* We handled quick cases, we are permitted to interrupt now. */
2293 /* This should be syscall entry or exit.
2294 * (Or it still can be that pesky post-execve SIGTRAP!)
2297 if (trace_syscall(tcp) < 0) {
2298 /* ptrace() failed in trace_syscall().
2299 * Likely a result of process disappearing mid-flight.
2300 * Observed case: exit_group() or SIGKILL terminating
2301 * all processes in thread group.
2302 * We assume that ptrace error was caused by process death.
2303 * We used to detach(tcp) here, but since we no longer
2304 * implement "detach before death" policy/hack,
2305 * we can let this process to report its death to us
2306 * normally, via WIFEXITED or WIFSIGNALED wait status.
2310 restart_tracee_with_sig_0:
2313 if (ptrace_restart(PTRACE_SYSCALL, tcp, sig) < 0) {
2322 main(int argc, char *argv[])
2326 /* Run main tracing loop */
2332 if (shared_log != stderr)
2335 while (waitpid(popen_pid, NULL, 0) < 0 && errno == EINTR)
2338 if (exit_code > 0xff) {
2339 /* Avoid potential core file clobbering. */
2340 struct_rlimit rlim = {0, 0};
2341 set_rlimit(RLIMIT_CORE, &rlim);
2343 /* Child was killed by a signal, mimic that. */
2345 signal(exit_code, SIG_DFL);
2347 /* Paranoia - what if this signal is not fatal?
2348 Exit with 128 + signo then. */