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.
35 #include <sys/types.h>
39 #include <sys/param.h>
41 #include <sys/resource.h>
48 #include <sys/utsname.h>
50 # include <asm/unistd.h>
51 # if defined __NR_tkill
52 # define my_tkill(tid, sig) syscall(__NR_tkill, (tid), (sig))
54 /* kill() may choose arbitrarily the target task of the process group
55 while we later wait on a that specific TID. PID process waits become
56 TID task specific waits for a process under ptrace(2). */
57 # warning "Neither tkill(2) nor tgkill(2) available, risk of strace hangs!"
58 # define my_tkill(tid, sig) kill((tid), (sig))
62 # include <asm/ptrace_offsets.h>
65 extern char **environ;
69 int debug = 0, followfork = 0;
70 unsigned int ptrace_setoptions = 0;
71 /* Which WSTOPSIG(status) value marks syscall traps? */
72 static unsigned int syscall_trap_sig = SIGTRAP;
73 int dtime = 0, xflag = 0, qflag = 0;
74 cflag_t cflag = CFLAG_NONE;
75 static int iflag = 0, rflag = 0, tflag = 0;
76 static int print_pid_pfx = 0;
81 INTR_ANYWHERE = 1, /* don't block/ignore any signals */
82 INTR_WHILE_WAIT = 2, /* block fatal signals while decoding syscall. default */
83 INTR_NEVER = 3, /* block fatal signals. default if '-o FILE PROG' */
84 INTR_BLOCK_TSTP_TOO = 4, /* block fatal signals and SIGTSTP (^Z) */
88 /* We play with signal mask only if this mode is active: */
89 #define interactive (opt_intr == INTR_WHILE_WAIT)
92 * daemonized_tracer supports -D option.
93 * With this option, strace forks twice.
94 * Unlike normal case, with -D *grandparent* process exec's,
95 * becoming a traced process. Child exits (this prevents traced process
96 * from having children it doesn't expect to have), and grandchild
97 * attaches to grandparent similarly to strace -p PID.
98 * This allows for more transparent interaction in cases
99 * when process and its parent are communicating via signals,
100 * wait() etc. Without -D, strace process gets lodged in between,
101 * disrupting parent<->child link.
103 static bool daemonized_tracer = 0;
106 static int post_attach_sigstop = TCB_IGNORE_ONE_SIGSTOP;
107 # define use_seize (post_attach_sigstop == 0)
109 # define post_attach_sigstop TCB_IGNORE_ONE_SIGSTOP
113 /* Sometimes we want to print only succeeding syscalls. */
114 int not_failing_only = 0;
116 /* Show path associated with fd arguments */
117 int show_fd_path = 0;
119 /* are we filtering traces based on paths? */
120 int tracing_paths = 0;
122 static int exit_code = 0;
123 static int strace_child = 0;
124 static int strace_tracer_pid = 0;
126 static char *username = NULL;
127 static uid_t run_uid;
128 static gid_t run_gid;
130 int max_strlen = DEFAULT_STRLEN;
131 static int acolumn = DEFAULT_ACOLUMN;
132 static char *acolumn_spaces;
133 static char *outfname = NULL;
135 struct tcb *printing_tcp = NULL;
137 static struct tcb **tcbtab;
138 static unsigned int nprocs, tcbtabsize;
139 static const char *progname;
141 static char *os_release; /* from uname() */
143 static int detach(struct tcb *tcp);
144 static int trace(void);
145 static void cleanup(void);
146 static void interrupt(int sig);
147 static sigset_t empty_set, blocked_set;
149 #ifdef HAVE_SIG_ATOMIC_T
150 static volatile sig_atomic_t interrupted;
152 static volatile int interrupted;
156 usage(FILE *ofp, int exitval)
159 usage: strace [-CdDffhiqrtttTvVxxy] [-I n] [-a column] [-e expr]... [-o file]\n\
160 [-p pid]... [-s strsize] [-u username] [-E var=val]...\n\
161 [-P path] [PROG [ARGS]]\n\
162 or: strace -c [-D] [-I n] [-e expr]... [-O overhead] [-S sortby] [-E var=val]...\n\
164 -c -- count time, calls, and errors for each syscall and report summary\n\
165 -C -- like -c but also print regular output while processes are running\n\
166 -D -- run tracer process as a detached grandchild, not as parent\n\
167 -f -- follow forks, -ff -- with output into separate files\n\
168 -F -- attempt to follow vforks\n\
169 -i -- print instruction pointer at time of syscall\n\
171 1: no signals are blocked\n\
172 2: fatal signals are blocked while decoding syscall (default)\n\
173 3: fatal signals are always blocked (default if '-o FILE PROG')\n\
174 4: fatal signals and SIGTSTP (^Z) are always blocked\n\
175 (useful to make 'strace -o FILE PROG' not stop on ^Z)\n\
176 -q -- suppress messages about attaching, detaching, etc.\n\
177 -r -- print relative timestamp, -t -- absolute timestamp, -tt -- with usecs\n\
178 -T -- print time spent in each syscall\n\
179 -v -- verbose mode: print unabbreviated argv, stat, termios, etc. args\n\
180 -x -- print non-ascii strings in hex, -xx -- print all strings in hex\n\
181 -y -- print paths associated with file descriptor arguments\n\
182 -h -- print help message\n\
183 -V -- print version\n\
184 -a column -- alignment COLUMN for printing syscall results (default %d)\n\
185 -e expr -- a qualifying expression: option=[!]all or option=[!]val1[,val2]...\n\
186 options: trace, abbrev, verbose, raw, signal, read, or write\n\
187 -o file -- send trace output to FILE instead of stderr\n\
188 -O overhead -- set overhead for tracing syscalls to OVERHEAD usecs\n\
189 -p pid -- trace process with process id PID, may be repeated\n\
190 -s strsize -- limit length of print strings to STRSIZE chars (default %d)\n\
191 -S sortby -- sort syscall counts by: time, calls, name, nothing (default %s)\n\
192 -u username -- run command as username handling setuid and/or setgid\n\
193 -E var=val -- put var=val in the environment for command\n\
194 -E var -- remove var from the environment for command\n\
195 -P path -- trace accesses to path\n\
196 " /* this is broken, so don't document it
197 -z -- print only succeeding syscalls\n\
199 , DEFAULT_ACOLUMN, DEFAULT_STRLEN, DEFAULT_SORTBY);
203 static void die(void) __attribute__ ((noreturn));
204 static void die(void)
206 if (strace_tracer_pid == getpid()) {
213 static void verror_msg(int err_no, const char *fmt, va_list p)
219 /* We want to print entire message with single fprintf to ensure
220 * message integrity if stderr is shared with other programs.
221 * Thus we use vasprintf + single fprintf.
224 if (vasprintf(&msg, fmt, p) >= 0) {
226 fprintf(stderr, "%s: %s: %s\n", progname, msg, strerror(err_no));
228 fprintf(stderr, "%s: %s\n", progname, msg);
231 /* malloc in vasprintf failed, try it without malloc */
232 fprintf(stderr, "%s: ", progname);
233 vfprintf(stderr, fmt, p);
235 fprintf(stderr, ": %s\n", strerror(err_no));
239 /* We don't switch stderr to buffered, thus fprintf(stderr)
240 * always flushes its output and this is not necessary: */
241 /* fflush(stderr); */
244 void error_msg(const char *fmt, ...)
248 verror_msg(0, fmt, p);
252 void error_msg_and_die(const char *fmt, ...)
256 verror_msg(0, fmt, p);
260 void perror_msg(const char *fmt, ...)
264 verror_msg(errno, fmt, p);
268 void perror_msg_and_die(const char *fmt, ...)
272 verror_msg(errno, fmt, p);
276 void die_out_of_memory(void)
278 static bool recursed = 0;
282 error_msg_and_die("Out of memory");
285 /* Glue for systems without a MMU that cannot provide fork() */
287 # define strace_vforked 0
289 # define strace_vforked 1
290 # define fork() vfork()
295 ptrace_attach_or_seize(int pid)
299 return ptrace(PTRACE_ATTACH, pid, 0, 0);
300 r = ptrace(PTRACE_SEIZE, pid, 0, PTRACE_SEIZE_DEVEL);
303 r = ptrace(PTRACE_INTERRUPT, pid, 0, 0);
307 # define ptrace_attach_or_seize(pid) ptrace(PTRACE_ATTACH, (pid), 0, 0)
311 set_cloexec_flag(int fd)
315 flags = fcntl(fd, F_GETFD);
317 /* Can happen only if fd is bad.
318 * Should never happen: if it does, we have a bug
319 * in the caller. Therefore we just abort
320 * instead of propagating the error.
322 perror_msg_and_die("fcntl(%d, F_GETFD)", fd);
325 newflags = flags | FD_CLOEXEC;
326 if (flags == newflags)
329 fcntl(fd, F_SETFD, newflags); /* never fails */
332 static void kill_save_errno(pid_t pid, int sig)
334 int saved_errno = errno;
336 (void) kill(pid, sig);
341 tprintf(const char *fmt, ...)
347 int n = vfprintf(outf, fmt, args);
350 perror(outfname == NULL
351 ? "<writing to pipe>" : outfname);
359 tprints(const char *str)
362 int n = fputs(str, outf);
364 curcol += strlen(str);
368 perror(outfname == NULL
369 ? "<writing to pipe>" : outfname);
374 printleader(struct tcb *tcp)
377 if (printing_tcp->ptrace_errno) {
378 if (printing_tcp->flags & TCB_INSYSCALL) {
379 tprints(" <unavailable>) ");
382 tprints("= ? <unavailable>\n");
383 printing_tcp->ptrace_errno = 0;
384 } else if (!outfname || followfork < 2 || printing_tcp == tcp) {
385 printing_tcp->flags |= TCB_REPRINT;
386 tprints(" <unfinished ...>\n");
394 tprintf("%-5d ", tcp->pid);
395 else if (nprocs > 1 && !outfname)
396 tprintf("[pid %5u] ", tcp->pid);
399 char str[sizeof("HH:MM:SS")];
400 struct timeval tv, dtv;
401 static struct timeval otv;
403 gettimeofday(&tv, NULL);
407 tv_sub(&dtv, &tv, &otv);
408 tprintf("%6ld.%06ld ",
409 (long) dtv.tv_sec, (long) dtv.tv_usec);
412 else if (tflag > 2) {
413 tprintf("%ld.%06ld ",
414 (long) tv.tv_sec, (long) tv.tv_usec);
417 time_t local = tv.tv_sec;
418 strftime(str, sizeof(str), "%T", localtime(&local));
420 tprintf("%s.%06ld ", str, (long) tv.tv_usec);
432 if (curcol < acolumn)
433 tprints(acolumn_spaces + curcol);
437 * When strace is setuid executable, we have to swap uids
438 * before and after filesystem and process management operations.
443 int euid = geteuid(), uid = getuid();
445 if (euid != uid && setreuid(euid, uid) < 0) {
446 perror_msg_and_die("setreuid");
451 # define fopen_for_output fopen64
453 # define fopen_for_output fopen
457 strace_fopen(const char *path)
462 fp = fopen_for_output(path, "w");
464 perror_msg_and_die("Can't fopen '%s'", path);
466 set_cloexec_flag(fileno(fp));
470 static int popen_pid = 0;
473 # define _PATH_BSHELL "/bin/sh"
477 * We cannot use standard popen(3) here because we have to distinguish
478 * popen child process from other processes we trace, and standard popen(3)
479 * does not export its child's pid.
482 strace_popen(const char *command)
489 perror_msg_and_die("pipe");
491 set_cloexec_flag(fds[1]); /* never fails */
495 perror_msg_and_die("vfork");
497 if (popen_pid == 0) {
502 perror_msg_and_die("dup2");
505 execl(_PATH_BSHELL, "sh", "-c", command, NULL);
506 perror_msg_and_die("Can't execute '%s'", _PATH_BSHELL);
512 fp = fdopen(fds[1], "w");
519 newoutf(struct tcb *tcp)
521 if (outfname && followfork > 1) {
522 char name[520 + sizeof(int) * 3];
523 sprintf(name, "%.512s.%u", outfname, tcp->pid);
524 tcp->outf = strace_fopen(name);
529 process_opt_p_list(char *opt)
533 * We accept -p PID,PID; -p "`pidof PROG`"; -p "`pgrep PROG`".
534 * pidof uses space as delim, pgrep uses newline. :(
537 char *delim = opt + strcspn(opt, ", \n\t");
541 pid = atoi(opt); /* TODO: stricter parsing of the number? */
543 error_msg("Invalid process id: '%s'", opt);
547 if (pid == strace_tracer_pid) {
548 error_msg("I'm sorry, I can't let you do that, Dave.");
567 * Block user interruptions as we would leave the traced
568 * process stopped (process state T) if we would terminate in
569 * between PTRACE_ATTACH and wait4() on SIGSTOP.
570 * We rely on cleanup() from this point on.
573 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
575 if (daemonized_tracer) {
578 perror_msg_and_die("fork");
580 if (pid) { /* parent */
582 * Wait for grandchild to attach to straced process
583 * (grandparent). Grandchild SIGKILLs us after it attached.
584 * Grandparent's wait() is unblocked by our death,
585 * it proceeds to exec the straced program.
588 _exit(0); /* paranoia */
591 /* We will be the tracer process. Remember our new pid: */
592 strace_tracer_pid = getpid();
595 for (tcbi = 0; tcbi < tcbtabsize; tcbi++) {
598 if (!(tcp->flags & TCB_INUSE))
601 /* Is this a process we should attach to, but not yet attached? */
602 if (tcp->flags & TCB_ATTACHED)
603 continue; /* no, we already attached it */
605 /* Reinitialize the output since it may have changed */
609 if (followfork && !daemonized_tracer) {
610 char procdir[sizeof("/proc/%d/task") + sizeof(int) * 3];
613 sprintf(procdir, "/proc/%d/task", tcp->pid);
614 dir = opendir(procdir);
616 unsigned int ntid = 0, nerr = 0;
619 while ((de = readdir(dir)) != NULL) {
623 if (de->d_fileno == 0)
625 tid = atoi(de->d_name);
629 if (ptrace_attach_or_seize(tid) < 0) {
632 fprintf(stderr, "attach to pid %d failed\n", tid);
636 fprintf(stderr, "attach to pid %d succeeded\n", tid);
639 cur_tcp = alloctcb(tid);
640 cur_tcp->flags |= TCB_ATTACHED | TCB_STARTUP | post_attach_sigstop;
644 sigprocmask(SIG_SETMASK, &empty_set, NULL);
647 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
651 perror("attach: ptrace(PTRACE_ATTACH, ...)");
656 fprintf(stderr, ntid > 1
657 ? "Process %u attached with %u threads - interrupt to quit\n"
658 : "Process %u attached - interrupt to quit\n",
661 if (!(tcp->flags & TCB_ATTACHED)) {
662 /* -p PID, we failed to attach to PID itself
663 * but did attach to some of its sibling threads.
669 } /* if (opendir worked) */
671 if (ptrace_attach_or_seize(tcp->pid) < 0) {
672 perror("attach: ptrace(PTRACE_ATTACH, ...)");
676 tcp->flags |= TCB_ATTACHED | TCB_STARTUP | post_attach_sigstop;
678 fprintf(stderr, "attach to pid %d (main) succeeded\n", tcp->pid);
680 if (daemonized_tracer) {
682 * Make parent go away.
683 * Also makes grandparent's wait() unblock.
685 kill(getppid(), SIGKILL);
690 "Process %u attached - interrupt to quit\n",
692 } /* for each tcbtab[] */
696 sigprocmask(SIG_SETMASK, &empty_set, NULL);
700 startup_child(char **argv)
703 const char *filename;
704 char pathname[MAXPATHLEN];
709 if (strchr(filename, '/')) {
710 if (strlen(filename) > sizeof pathname - 1) {
711 errno = ENAMETOOLONG;
712 perror_msg_and_die("exec");
714 strcpy(pathname, filename);
716 #ifdef USE_DEBUGGING_EXEC
718 * Debuggers customarily check the current directory
719 * first regardless of the path but doing that gives
720 * security geeks a panic attack.
722 else if (stat(filename, &statbuf) == 0)
723 strcpy(pathname, filename);
724 #endif /* USE_DEBUGGING_EXEC */
729 for (path = getenv("PATH"); path && *path; path += m) {
730 const char *colon = strchr(path, ':');
736 m = n = strlen(path);
738 if (!getcwd(pathname, MAXPATHLEN))
740 len = strlen(pathname);
742 else if (n > sizeof pathname - 1)
745 strncpy(pathname, path, n);
748 if (len && pathname[len - 1] != '/')
749 pathname[len++] = '/';
750 strcpy(pathname + len, filename);
751 if (stat(pathname, &statbuf) == 0 &&
752 /* Accept only regular files
753 with some execute bits set.
754 XXX not perfect, might still fail */
755 S_ISREG(statbuf.st_mode) &&
756 (statbuf.st_mode & 0111))
760 if (stat(pathname, &statbuf) < 0) {
761 perror_msg_and_die("Can't stat '%s'", filename);
763 strace_child = pid = fork();
765 perror_msg_and_die("fork");
767 if ((pid != 0 && daemonized_tracer) /* -D: parent to become a traced process */
768 || (pid == 0 && !daemonized_tracer) /* not -D: child to become a traced process */
773 if (!daemonized_tracer && !use_seize) {
774 if (ptrace(PTRACE_TRACEME, 0L, 0L, 0L) < 0) {
775 perror_msg_and_die("ptrace(PTRACE_TRACEME, ...)");
779 if (username != NULL) {
780 uid_t run_euid = run_uid;
781 gid_t run_egid = run_gid;
783 if (statbuf.st_mode & S_ISUID)
784 run_euid = statbuf.st_uid;
785 if (statbuf.st_mode & S_ISGID)
786 run_egid = statbuf.st_gid;
788 * It is important to set groups before we
789 * lose privileges on setuid.
791 if (initgroups(username, run_gid) < 0) {
792 perror_msg_and_die("initgroups");
794 if (setregid(run_gid, run_egid) < 0) {
795 perror_msg_and_die("setregid");
797 if (setreuid(run_uid, run_euid) < 0) {
798 perror_msg_and_die("setreuid");
801 else if (geteuid() != 0)
802 setreuid(run_uid, run_uid);
804 if (!daemonized_tracer) {
806 * Induce a ptrace stop. Tracer (our parent)
807 * will resume us with PTRACE_SYSCALL and display
808 * the immediately following execve syscall.
809 * Can't do this on NOMMU systems, we are after
810 * vfork: parent is blocked, stopping would deadlock.
815 struct sigaction sv_sigchld;
816 sigaction(SIGCHLD, NULL, &sv_sigchld);
818 * Make sure it is not SIG_IGN, otherwise wait
821 signal(SIGCHLD, SIG_DFL);
823 * Wait for grandchild to attach to us.
824 * It kills child after that, and wait() unblocks.
829 sigaction(SIGCHLD, &sv_sigchld, NULL);
832 execv(pathname, argv);
833 perror_msg_and_die("exec");
836 /* We are the tracer */
838 if (!daemonized_tracer) {
840 /* child did PTRACE_TRACEME, nothing to do in parent */
842 if (!strace_vforked) {
843 /* Wait until child stopped itself */
845 while (waitpid(pid, &status, WSTOPPED) < 0) {
848 perror_msg_and_die("waitpid");
850 if (!WIFSTOPPED(status) || WSTOPSIG(status) != SIGSTOP) {
851 kill_save_errno(pid, SIGKILL);
852 perror_msg_and_die("Unexpected wait status %x", status);
855 /* Else: vforked case, we have no way to sync.
856 * Just attach to it as soon as possible.
857 * This means that we may miss a few first syscalls...
860 if (ptrace_attach_or_seize(pid)) {
861 kill_save_errno(pid, SIGKILL);
862 perror_msg_and_die("Can't attach to %d", pid);
869 tcp->flags |= TCB_ATTACHED | TCB_STRACE_CHILD | TCB_STARTUP | post_attach_sigstop;
871 tcp->flags |= TCB_ATTACHED | TCB_STRACE_CHILD | TCB_STARTUP;
874 /* With -D, *we* are child here, IOW: different pid. Fetch it: */
875 strace_tracer_pid = getpid();
876 /* The tracee is our parent: */
879 /* attaching will be done later, by startup_attach */
884 * Test whether the kernel support PTRACE_O_TRACECLONE et al options.
885 * First fork a new child, call ptrace with PTRACE_SETOPTIONS on it,
886 * and then see which options are supported by the kernel.
889 test_ptrace_setoptions_followfork(void)
891 int pid, expected_grandchild = 0, found_grandchild = 0;
892 const unsigned int test_options = PTRACE_O_TRACECLONE |
898 perror_msg_and_die("fork");
901 if (ptrace(PTRACE_TRACEME, 0L, 0L, 0L) < 0)
902 perror_msg_and_die("%s: PTRACE_TRACEME doesn't work",
904 kill_save_errno(pid, SIGSTOP);
906 perror_msg_and_die("fork");
911 int status, tracee_pid;
914 tracee_pid = wait(&status);
915 if (tracee_pid <= 0) {
920 kill_save_errno(pid, SIGKILL);
921 perror_msg_and_die("%s: unexpected wait result %d",
922 __func__, tracee_pid);
924 if (WIFEXITED(status)) {
925 if (WEXITSTATUS(status)) {
926 if (tracee_pid != pid)
927 kill_save_errno(pid, SIGKILL);
928 error_msg_and_die("%s: unexpected exit status %u",
929 __func__, WEXITSTATUS(status));
933 if (WIFSIGNALED(status)) {
934 if (tracee_pid != pid)
935 kill_save_errno(pid, SIGKILL);
936 error_msg_and_die("%s: unexpected signal %u",
937 __func__, WTERMSIG(status));
939 if (!WIFSTOPPED(status)) {
940 if (tracee_pid != pid)
941 kill_save_errno(tracee_pid, SIGKILL);
942 kill_save_errno(pid, SIGKILL);
943 error_msg_and_die("%s: unexpected wait status %x",
946 if (tracee_pid != pid) {
947 found_grandchild = tracee_pid;
948 if (ptrace(PTRACE_CONT, tracee_pid, 0, 0) < 0) {
949 kill_save_errno(tracee_pid, SIGKILL);
950 kill_save_errno(pid, SIGKILL);
951 perror_msg_and_die("PTRACE_CONT doesn't work");
955 switch (WSTOPSIG(status)) {
957 if (ptrace(PTRACE_SETOPTIONS, pid, 0, test_options) < 0
958 && errno != EINVAL && errno != EIO)
959 perror_msg("PTRACE_SETOPTIONS");
962 if (status >> 16 == PTRACE_EVENT_FORK) {
965 if (ptrace(PTRACE_GETEVENTMSG, pid,
966 NULL, (long) &msg) == 0)
967 expected_grandchild = msg;
971 if (ptrace(PTRACE_SYSCALL, pid, 0, 0) < 0) {
972 kill_save_errno(pid, SIGKILL);
973 perror_msg_and_die("PTRACE_SYSCALL doesn't work");
976 if (expected_grandchild && expected_grandchild == found_grandchild) {
977 ptrace_setoptions |= test_options;
979 fprintf(stderr, "ptrace_setoptions = %#x\n",
983 error_msg("Test for PTRACE_O_TRACECLONE failed, "
984 "giving up using this feature.");
988 * Test whether the kernel support PTRACE_O_TRACESYSGOOD.
989 * First fork a new child, call ptrace(PTRACE_SETOPTIONS) on it,
990 * and then see whether it will stop with (SIGTRAP | 0x80).
992 * Use of this option enables correct handling of user-generated SIGTRAPs,
993 * and SIGTRAPs generated by special instructions such as int3 on x86:
994 * _start: .globl _start
999 * (compile with: "gcc -nostartfiles -nostdlib -o int3 int3.S")
1002 test_ptrace_setoptions_for_all(void)
1004 const unsigned int test_options = PTRACE_O_TRACESYSGOOD |
1011 perror_msg_and_die("fork");
1015 if (ptrace(PTRACE_TRACEME, 0L, 0L, 0L) < 0)
1016 /* Note: exits with exitcode 1 */
1017 perror_msg_and_die("%s: PTRACE_TRACEME doesn't work",
1020 _exit(0); /* parent should see entry into this syscall */
1024 int status, tracee_pid;
1027 tracee_pid = wait(&status);
1028 if (tracee_pid <= 0) {
1031 kill_save_errno(pid, SIGKILL);
1032 perror_msg_and_die("%s: unexpected wait result %d",
1033 __func__, tracee_pid);
1035 if (WIFEXITED(status)) {
1036 if (WEXITSTATUS(status) == 0)
1038 error_msg_and_die("%s: unexpected exit status %u",
1039 __func__, WEXITSTATUS(status));
1041 if (WIFSIGNALED(status)) {
1042 error_msg_and_die("%s: unexpected signal %u",
1043 __func__, WTERMSIG(status));
1045 if (!WIFSTOPPED(status)) {
1047 error_msg_and_die("%s: unexpected wait status %x",
1050 if (WSTOPSIG(status) == SIGSTOP) {
1052 * We don't check "options aren't accepted" error.
1053 * If it happens, we'll never get (SIGTRAP | 0x80),
1054 * and thus will decide to not use the option.
1055 * IOW: the outcome of the test will be correct.
1057 if (ptrace(PTRACE_SETOPTIONS, pid, 0L, test_options) < 0
1058 && errno != EINVAL && errno != EIO)
1059 perror_msg("PTRACE_SETOPTIONS");
1061 if (WSTOPSIG(status) == (SIGTRAP | 0x80)) {
1064 if (ptrace(PTRACE_SYSCALL, pid, 0L, 0L) < 0) {
1065 kill_save_errno(pid, SIGKILL);
1066 perror_msg_and_die("PTRACE_SYSCALL doesn't work");
1071 syscall_trap_sig = (SIGTRAP | 0x80);
1072 ptrace_setoptions |= test_options;
1074 fprintf(stderr, "ptrace_setoptions = %#x\n",
1079 error_msg("Test for PTRACE_O_TRACESYSGOOD failed, "
1080 "giving up using this feature.");
1085 test_ptrace_seize(void)
1091 perror_msg_and_die("fork");
1098 /* PTRACE_SEIZE, unlike ATTACH, doesn't force tracee to trap. After
1099 * attaching tracee continues to run unless a trap condition occurs.
1100 * PTRACE_SEIZE doesn't affect signal or group stop state.
1102 if (ptrace(PTRACE_SEIZE, pid, 0, PTRACE_SEIZE_DEVEL) == 0) {
1103 post_attach_sigstop = 0; /* this sets use_seize to 1 */
1105 fprintf(stderr, "PTRACE_SEIZE doesn't work\n");
1111 int status, tracee_pid;
1114 tracee_pid = waitpid(pid, &status, 0);
1115 if (tracee_pid <= 0) {
1118 perror_msg_and_die("%s: unexpected wait result %d",
1119 __func__, tracee_pid);
1121 if (WIFSIGNALED(status)) {
1124 error_msg_and_die("%s: unexpected wait status %x",
1128 # else /* !USE_SEIZE */
1129 # define test_ptrace_seize() ((void)0)
1133 get_os_release(void)
1137 perror_msg_and_die("uname");
1138 os_release = strdup(u.release);
1140 die_out_of_memory();
1144 * Initialization part of main() was eating much stack (~0.5k),
1145 * which was unused after init.
1146 * We can reuse it if we move init code into a separate function.
1148 * Don't want main() to inline us and defeat the reason
1149 * we have a separate function.
1151 static void __attribute__ ((noinline))
1152 init(int argc, char *argv[])
1157 struct sigaction sa;
1159 progname = argv[0] ? argv[0] : "strace";
1161 strace_tracer_pid = getpid();
1165 /* Allocate the initial tcbtab. */
1166 tcbtabsize = argc; /* Surely enough for all -p args. */
1167 tcbtab = calloc(tcbtabsize, sizeof(tcbtab[0]));
1169 die_out_of_memory();
1170 tcp = calloc(tcbtabsize, sizeof(*tcp));
1172 die_out_of_memory();
1173 for (c = 0; c < tcbtabsize; c++)
1177 set_sortby(DEFAULT_SORTBY);
1178 set_personality(DEFAULT_PERSONALITY);
1179 qualify("trace=all");
1180 qualify("abbrev=all");
1181 qualify("verbose=all");
1182 qualify("signal=all");
1183 while ((c = getopt(argc, argv,
1186 "a:e:o:O:p:s:S:u:E:P:I:")) != EOF) {
1189 if (cflag == CFLAG_BOTH) {
1190 error_msg_and_die("-c and -C are mutually exclusive options");
1192 cflag = CFLAG_ONLY_STATS;
1195 if (cflag == CFLAG_ONLY_STATS) {
1196 error_msg_and_die("-c and -C are mutually exclusive options");
1204 daemonized_tracer = 1;
1238 qualify("abbrev=none");
1241 printf("%s -- version %s\n", PACKAGE_NAME, VERSION);
1245 not_failing_only = 1;
1248 acolumn = atoi(optarg);
1250 error_msg_and_die("Bad column width '%s'", optarg);
1256 outfname = strdup(optarg);
1259 set_overhead(atoi(optarg));
1262 process_opt_p_list(optarg);
1266 if (pathtrace_select(optarg)) {
1267 error_msg_and_die("Failed to select path '%s'", optarg);
1271 max_strlen = atoi(optarg);
1272 if (max_strlen < 0) {
1273 error_msg_and_die("Invalid -%c argument: '%s'", c, optarg);
1280 username = strdup(optarg);
1283 if (putenv(optarg) < 0)
1284 die_out_of_memory();
1287 opt_intr = atoi(optarg);
1288 if (opt_intr <= 0 || opt_intr >= NUM_INTR_OPTS) {
1289 error_msg_and_die("Invalid -%c argument: '%s'", c, optarg);
1298 /* argc -= optind; - no need, argc is not used below */
1300 acolumn_spaces = malloc(acolumn + 1);
1301 if (!acolumn_spaces)
1302 die_out_of_memory();
1303 memset(acolumn_spaces, ' ', acolumn);
1304 acolumn_spaces[acolumn] = '\0';
1306 /* Must have PROG [ARGS], or -p PID. Not both. */
1307 if (!argv[0] == !nprocs)
1310 if (nprocs != 0 && daemonized_tracer) {
1311 error_msg_and_die("-D and -p are mutually exclusive options");
1317 if (followfork > 1 && cflag) {
1318 error_msg_and_die("(-c or -C) and -ff are mutually exclusive options");
1321 /* See if they want to run as another user. */
1322 if (username != NULL) {
1323 struct passwd *pent;
1325 if (getuid() != 0 || geteuid() != 0) {
1326 error_msg_and_die("You must be root to use the -u option");
1328 pent = getpwnam(username);
1330 error_msg_and_die("Cannot find user '%s'", username);
1332 run_uid = pent->pw_uid;
1333 run_gid = pent->pw_gid;
1341 test_ptrace_setoptions_followfork();
1342 test_ptrace_setoptions_for_all();
1343 test_ptrace_seize();
1345 /* Check if they want to redirect the output. */
1347 /* See if they want to pipe the output. */
1348 if (outfname[0] == '|' || outfname[0] == '!') {
1350 * We can't do the <outfname>.PID funny business
1351 * when using popen, so prohibit it.
1354 error_msg_and_die("Piping the output and -ff are mutually exclusive");
1355 outf = strace_popen(outfname + 1);
1357 else if (followfork <= 1)
1358 outf = strace_fopen(outfname);
1360 /* -ff without -o FILE is the same as single -f */
1365 if (!outfname || outfname[0] == '|' || outfname[0] == '!') {
1366 char *buf = malloc(BUFSIZ);
1368 die_out_of_memory();
1369 setvbuf(outf, buf, _IOLBF, BUFSIZ);
1371 if (outfname && argv[0]) {
1373 opt_intr = INTR_NEVER;
1377 opt_intr = INTR_WHILE_WAIT;
1379 /* argv[0] -pPID -oFILE Default interactive setting
1380 * yes 0 0 INTR_WHILE_WAIT
1381 * no 1 0 INTR_WHILE_WAIT
1382 * yes 0 1 INTR_NEVER
1383 * no 1 1 INTR_WHILE_WAIT
1386 /* STARTUP_CHILD must be called before the signal handlers get
1387 installed below as they are inherited into the spawned process.
1388 Also we do not need to be protected by them as during interruption
1389 in the STARTUP_CHILD mode we kill the spawned process anyway. */
1391 startup_child(argv);
1393 sigemptyset(&empty_set);
1394 sigemptyset(&blocked_set);
1395 sa.sa_handler = SIG_IGN;
1396 sigemptyset(&sa.sa_mask);
1398 sigaction(SIGTTOU, &sa, NULL); /* SIG_IGN */
1399 sigaction(SIGTTIN, &sa, NULL); /* SIG_IGN */
1400 if (opt_intr != INTR_ANYWHERE) {
1401 if (opt_intr == INTR_BLOCK_TSTP_TOO)
1402 sigaction(SIGTSTP, &sa, NULL); /* SIG_IGN */
1404 * In interactive mode (if no -o OUTFILE, or -p PID is used),
1405 * fatal signals are blocked while syscall stop is processed,
1406 * and acted on in between, when waiting for new syscall stops.
1407 * In non-interactive mode, signals are ignored.
1409 if (opt_intr == INTR_WHILE_WAIT) {
1410 sigaddset(&blocked_set, SIGHUP);
1411 sigaddset(&blocked_set, SIGINT);
1412 sigaddset(&blocked_set, SIGQUIT);
1413 sigaddset(&blocked_set, SIGPIPE);
1414 sigaddset(&blocked_set, SIGTERM);
1415 sa.sa_handler = interrupt;
1417 /* SIG_IGN, or set handler for these */
1418 sigaction(SIGHUP, &sa, NULL);
1419 sigaction(SIGINT, &sa, NULL);
1420 sigaction(SIGQUIT, &sa, NULL);
1421 sigaction(SIGPIPE, &sa, NULL);
1422 sigaction(SIGTERM, &sa, NULL);
1424 /* Make sure SIGCHLD has the default action so that waitpid
1425 definitely works without losing track of children. The user
1426 should not have given us a bogus state to inherit, but he might
1427 have. Arguably we should detect SIG_IGN here and pass it on
1428 to children, but probably noone really needs that. */
1429 sa.sa_handler = SIG_DFL;
1430 sigaction(SIGCHLD, &sa, NULL);
1432 if (nprocs != 0 || daemonized_tracer)
1435 /* Do we want pids printed in our -o OUTFILE?
1436 * -ff: no (every pid has its own file); or
1437 * -f: yes (there can be more pids in the future); or
1438 * -p PID1,PID2: yes (there are already more than one pid)
1440 print_pid_pfx = (outfname && followfork < 2 && (followfork == 1 || nprocs > 1));
1446 /* Allocate some more TCBs and expand the table.
1447 We don't want to relocate the TCBs because our
1448 callers have pointers and it would be a pain.
1449 So tcbtab is a table of pointers. Since we never
1450 free the TCBs, we allocate a single chunk of many. */
1452 struct tcb *newtcbs = calloc(tcbtabsize, sizeof(newtcbs[0]));
1453 struct tcb **newtab = realloc(tcbtab, tcbtabsize * 2 * sizeof(tcbtab[0]));
1454 if (!newtab || !newtcbs)
1455 die_out_of_memory();
1458 while (i < tcbtabsize)
1459 tcbtab[i++] = newtcbs++;
1463 alloc_tcb(int pid, int command_options_parsed)
1468 if (nprocs == tcbtabsize)
1471 for (i = 0; i < tcbtabsize; i++) {
1473 if ((tcp->flags & TCB_INUSE) == 0) {
1474 memset(tcp, 0, sizeof(*tcp));
1476 tcp->flags = TCB_INUSE;
1477 tcp->outf = outf; /* Initialise to current out file */
1478 #if SUPPORTED_PERSONALITIES > 1
1479 tcp->currpers = current_personality;
1483 fprintf(stderr, "new tcb for pid %d, active tcbs:%d\n", tcp->pid, nprocs);
1484 if (command_options_parsed)
1489 error_msg_and_die("bug in alloc_tcb");
1500 for (i = 0; i < tcbtabsize; i++) {
1501 struct tcb *tcp = tcbtab[i];
1502 if (tcp->pid == pid && (tcp->flags & TCB_INUSE))
1510 droptcb(struct tcb *tcp)
1517 fprintf(stderr, "dropped tcb for pid %d, %d remain\n", tcp->pid, nprocs);
1519 if (outfname && followfork > 1 && tcp->outf)
1522 memset(tcp, 0, sizeof(*tcp));
1525 /* detach traced process; continue with sig
1526 * Never call DETACH twice on the same process as both unattached and
1527 * attached-unstopped processes give the same ESRCH. For unattached process we
1528 * would SIGSTOP it and wait for its SIGSTOP notification forever.
1531 detach(struct tcb *tcp)
1534 int status, sigstop_expected;
1536 if (tcp->flags & TCB_BPTSET)
1540 * Linux wrongly insists the child be stopped
1541 * before detaching. Arghh. We go through hoops
1542 * to make a clean break of things.
1545 #undef PTRACE_DETACH
1546 #define PTRACE_DETACH PTRACE_SUNDETACH
1549 sigstop_expected = 0;
1550 if (tcp->flags & TCB_ATTACHED) {
1552 * We attached but possibly didn't see the expected SIGSTOP.
1553 * We must catch exactly one as otherwise the detached process
1554 * would be left stopped (process state T).
1556 sigstop_expected = (tcp->flags & TCB_IGNORE_ONE_SIGSTOP);
1557 error = ptrace(PTRACE_DETACH, tcp->pid, (char *) 1, 0);
1559 /* On a clear day, you can see forever. */
1561 else if (errno != ESRCH) {
1562 /* Shouldn't happen. */
1563 perror("detach: ptrace(PTRACE_DETACH, ...)");
1565 else if (my_tkill(tcp->pid, 0) < 0) {
1567 perror("detach: checking sanity");
1569 else if (!sigstop_expected && my_tkill(tcp->pid, SIGSTOP) < 0) {
1571 perror("detach: stopping child");
1574 sigstop_expected = 1;
1577 if (sigstop_expected) {
1580 if (waitpid(tcp->pid, &status, __WALL) < 0) {
1581 if (errno == ECHILD) /* Already gone. */
1583 if (errno != EINVAL) {
1584 perror("detach: waiting");
1588 /* No __WALL here. */
1589 if (waitpid(tcp->pid, &status, 0) < 0) {
1590 if (errno != ECHILD) {
1591 perror("detach: waiting");
1595 /* If no processes, try clones. */
1596 if (waitpid(tcp->pid, &status, __WCLONE) < 0) {
1597 if (errno != ECHILD)
1598 perror("detach: waiting");
1601 #endif /* __WCLONE */
1606 if (!WIFSTOPPED(status)) {
1607 /* Au revoir, mon ami. */
1610 if (WSTOPSIG(status) == SIGSTOP) {
1611 ptrace_restart(PTRACE_DETACH, tcp, 0);
1614 error = ptrace_restart(PTRACE_CONT, tcp,
1615 WSTOPSIG(status) == syscall_trap_sig ? 0
1616 : WSTOPSIG(status));
1622 if (!qflag && (tcp->flags & TCB_ATTACHED))
1623 fprintf(stderr, "Process %u detached\n", tcp->pid);
1637 /* 'interrupted' is a volatile object, fetch it only once */
1638 fatal_sig = interrupted;
1640 fatal_sig = SIGTERM;
1642 for (i = 0; i < tcbtabsize; i++) {
1644 if (!(tcp->flags & TCB_INUSE))
1648 "cleanup: looking at pid %u\n", tcp->pid);
1650 (!outfname || followfork < 2 || printing_tcp == tcp)) {
1651 tprints(" <unfinished ...>\n");
1652 printing_tcp = NULL;
1654 if (!(tcp->flags & TCB_STRACE_CHILD))
1657 kill(tcp->pid, SIGCONT);
1658 kill(tcp->pid, fatal_sig);
1671 #ifndef HAVE_STRERROR
1673 #if !HAVE_DECL_SYS_ERRLIST
1674 extern int sys_nerr;
1675 extern char *sys_errlist[];
1676 #endif /* HAVE_DECL_SYS_ERRLIST */
1679 strerror(int err_no)
1681 static char buf[sizeof("Unknown error %d") + sizeof(int)*3];
1683 if (err_no < 1 || err_no >= sys_nerr) {
1684 sprintf(buf, "Unknown error %d", err_no);
1687 return sys_errlist[err_no];
1690 #endif /* HAVE_STERRROR */
1692 #ifndef HAVE_STRSIGNAL
1694 #if defined HAVE_SYS_SIGLIST && !defined HAVE_DECL_SYS_SIGLIST
1695 extern char *sys_siglist[];
1697 #if defined HAVE_SYS__SIGLIST && !defined HAVE_DECL__SYS_SIGLIST
1698 extern char *_sys_siglist[];
1704 static char buf[sizeof("Unknown signal %d") + sizeof(int)*3];
1706 if (sig < 1 || sig >= NSIG) {
1707 sprintf(buf, "Unknown signal %d", sig);
1710 #ifdef HAVE__SYS_SIGLIST
1711 return _sys_siglist[sig];
1713 return sys_siglist[sig];
1717 #endif /* HAVE_STRSIGNAL */
1723 struct rusage *rup = cflag ? &ru : NULL;
1725 static int wait4_options = __WALL;
1728 while (nprocs != 0) {
1739 sigprocmask(SIG_SETMASK, &empty_set, NULL);
1741 pid = wait4(-1, &status, wait4_options, rup);
1742 if (pid < 0 && (wait4_options & __WALL) && errno == EINVAL) {
1743 /* this kernel does not support __WALL */
1744 wait4_options &= ~__WALL;
1745 pid = wait4(-1, &status, wait4_options, rup);
1747 if (pid < 0 && !(wait4_options & __WALL) && errno == ECHILD) {
1748 /* most likely a "cloned" process */
1749 pid = wait4(-1, &status, __WCLONE, rup);
1751 perror_msg("wait4(__WCLONE) failed");
1755 pid = wait4(-1, &status, 0, rup);
1756 # endif /* __WALL */
1759 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
1762 switch (wait_errno) {
1767 * We would like to verify this case
1768 * but sometimes a race in Solbourne's
1769 * version of SunOS sometimes reports
1770 * ECHILD before sending us SIGCHILD.
1779 if (pid == popen_pid) {
1780 if (WIFEXITED(status) || WIFSIGNALED(status))
1785 event = ((unsigned)status >> 16);
1787 char buf[sizeof("WIFEXITED,exitcode=%u") + sizeof(int)*3 /*paranoia:*/ + 16];
1789 static const char *const event_names[] = {
1790 [PTRACE_EVENT_CLONE] = "CLONE",
1791 [PTRACE_EVENT_FORK] = "FORK",
1792 [PTRACE_EVENT_VFORK] = "VFORK",
1793 [PTRACE_EVENT_VFORK_DONE] = "VFORK_DONE",
1794 [PTRACE_EVENT_EXEC] = "EXEC",
1795 [PTRACE_EVENT_EXIT] = "EXIT",
1798 if (event < ARRAY_SIZE(event_names))
1799 e = event_names[event];
1801 sprintf(buf, "?? (%u)", event);
1804 fprintf(stderr, " PTRACE_EVENT_%s", e);
1807 if (WIFSIGNALED(status))
1809 sprintf(buf, "WIFSIGNALED,%ssig=%s",
1810 WCOREDUMP(status) ? "core," : "",
1811 signame(WTERMSIG(status)));
1813 sprintf(buf, "WIFSIGNALED,sig=%s",
1814 signame(WTERMSIG(status)));
1816 if (WIFEXITED(status))
1817 sprintf(buf, "WIFEXITED,exitcode=%u", WEXITSTATUS(status));
1818 if (WIFSTOPPED(status))
1819 sprintf(buf, "WIFSTOPPED,sig=%s", signame(WSTOPSIG(status)));
1821 if (WIFCONTINUED(status))
1822 strcpy(buf, "WIFCONTINUED");
1824 fprintf(stderr, " [wait(0x%04x) = %u] %s\n", status, pid, buf);
1827 /* Look up 'pid' in our table. */
1830 /* Under Linux, execve changes pid to thread leader's pid,
1831 * and we see this changed pid on EVENT_EXEC and later,
1832 * execve sysexit. Leader "disappears" without exit
1833 * notification. Let user know that, drop leader's tcb,
1834 * and fix up pid in execve thread's tcb.
1835 * Effectively, execve thread's tcb replaces leader's tcb.
1837 * BTW, leader is 'stuck undead' (doesn't report WIFEXITED
1838 * on exit syscall) in multithreaded programs exactly
1839 * in order to handle this case.
1841 * PTRACE_GETEVENTMSG returns old pid starting from Linux 3.0.
1842 * On 2.6 and earlier, it can return garbage.
1844 if (event == PTRACE_EVENT_EXEC && os_release[0] >= '3') {
1846 if (ptrace(PTRACE_GETEVENTMSG, pid, NULL, (long) &old_pid) >= 0
1850 struct tcb *execve_thread = pid2tcb(old_pid);
1853 curcol = tcp->curcol;
1856 tprints(" <unfinished ...>\n");
1858 tprintf("+++ superseded by execve in pid %lu +++\n", old_pid);
1859 printing_tcp = NULL;
1862 if (execve_thread) {
1863 /* swap output FILEs (needed for -ff) */
1864 tcp->outf = execve_thread->outf;
1865 execve_thread->outf = outf;
1869 tcp = execve_thread;
1872 tcp->flags |= TCB_REPRINT;
1879 /* This is needed to go with the CLONE_PTRACE
1880 changes in process.c/util.c: we might see
1881 the child's initial trap before we see the
1882 parent return from the clone syscall.
1883 Leave the child suspended until the parent
1884 returns from its system call. Only then
1885 will we have the association of parent and
1886 child so that we know how to do clearbpt
1888 tcp = alloctcb(pid);
1889 tcp->flags |= TCB_ATTACHED | TCB_STARTUP | post_attach_sigstop;
1891 fprintf(stderr, "Process %d attached\n",
1895 /* This can happen if a clone call used
1896 CLONE_PTRACE itself. */
1898 if (WIFSTOPPED(status))
1899 ptrace(PTRACE_CONT, pid, (char *) 0, 0);
1900 error_msg_and_die("Unknown pid: %u", pid);
1903 /* set current output file */
1905 curcol = tcp->curcol;
1907 tv_sub(&tcp->dtime, &ru.ru_stime, &tcp->stime);
1908 tcp->stime = ru.ru_stime;
1911 if (WIFSIGNALED(status)) {
1912 if (pid == strace_child)
1913 exit_code = 0x100 | WTERMSIG(status);
1914 if (cflag != CFLAG_ONLY_STATS
1915 && (qual_flags[WTERMSIG(status)] & QUAL_SIGNAL)) {
1918 tprintf("+++ killed by %s %s+++\n",
1919 signame(WTERMSIG(status)),
1920 WCOREDUMP(status) ? "(core dumped) " : "");
1922 tprintf("+++ killed by %s +++\n",
1923 signame(WTERMSIG(status)));
1925 printing_tcp = NULL;
1931 if (WIFEXITED(status)) {
1932 if (pid == strace_child)
1933 exit_code = WEXITSTATUS(status);
1934 if (tcp == printing_tcp) {
1935 tprints(" <unfinished ...>\n");
1936 printing_tcp = NULL;
1938 if (!cflag /* && (qual_flags[WTERMSIG(status)] & QUAL_SIGNAL) */ ) {
1940 tprintf("+++ exited with %d +++\n", WEXITSTATUS(status));
1941 printing_tcp = NULL;
1947 if (!WIFSTOPPED(status)) {
1948 fprintf(stderr, "PANIC: pid %u not stopped\n", pid);
1953 /* Is this the very first time we see this tracee stopped? */
1954 if (tcp->flags & TCB_STARTUP) {
1956 fprintf(stderr, "pid %d has TCB_STARTUP, initializing it\n", tcp->pid);
1957 tcp->flags &= ~TCB_STARTUP;
1958 if (tcp->flags & TCB_BPTSET) {
1960 * One example is a breakpoint inherited from
1961 * parent through fork().
1963 if (clearbpt(tcp) < 0) {
1970 if (ptrace_setoptions) {
1972 fprintf(stderr, "setting opts %x on pid %d\n", ptrace_setoptions, tcp->pid);
1973 if (ptrace(PTRACE_SETOPTIONS, tcp->pid, NULL, ptrace_setoptions) < 0) {
1974 if (errno != ESRCH) {
1975 /* Should never happen, really */
1976 perror_msg_and_die("PTRACE_SETOPTIONS");
1982 sig = WSTOPSIG(status);
1987 if (event == PTRACE_EVENT_STOP || event == PTRACE_EVENT_STOP1) {
1989 * PTRACE_INTERRUPT-stop or group-stop.
1990 * PTRACE_INTERRUPT-stop has sig == SIGTRAP here.
2002 goto restart_tracee_with_sig_0;
2005 /* Is this post-attach SIGSTOP?
2006 * Interestingly, the process may stop
2007 * with STOPSIG equal to some other signal
2008 * than SIGSTOP if we happend to attach
2009 * just before the process takes a signal.
2011 if (sig == SIGSTOP && (tcp->flags & TCB_IGNORE_ONE_SIGSTOP)) {
2013 fprintf(stderr, "ignored SIGSTOP on pid %d\n", tcp->pid);
2014 tcp->flags &= ~TCB_IGNORE_ONE_SIGSTOP;
2015 goto restart_tracee_with_sig_0;
2018 if (sig != syscall_trap_sig) {
2021 /* Nonzero (true) if tracee is stopped by signal
2022 * (as opposed to "tracee received signal").
2024 stopped = (ptrace(PTRACE_GETSIGINFO, pid, 0, (long) &si) < 0);
2028 if (cflag != CFLAG_ONLY_STATS
2029 && (qual_flags[sig] & QUAL_SIGNAL)) {
2030 #if defined(PT_CR_IPSR) && defined(PT_CR_IIP)
2034 upeek(tcp, PT_CR_IPSR, &psr);
2035 upeek(tcp, PT_CR_IIP, &pc);
2038 pc += (psr >> PSR_RI) & 0x3;
2039 # define PC_FORMAT_STR " @ %lx"
2040 # define PC_FORMAT_ARG , pc
2042 # define PC_FORMAT_STR ""
2043 # define PC_FORMAT_ARG /* nothing */
2048 printsiginfo(&si, verbose(tcp));
2049 tprintf(" (%s)" PC_FORMAT_STR " ---\n",
2053 tprintf("--- %s by %s" PC_FORMAT_STR " ---\n",
2057 printing_tcp = NULL;
2062 /* It's signal-delivery-stop. Inject the signal */
2063 goto restart_tracee;
2065 /* It's group-stop */
2069 * This ends ptrace-stop, but does *not* end group-stop.
2070 * This makes stopping signals work properly on straced process
2071 * (that is, process really stops. It used to continue to run).
2073 if (ptrace_restart(PTRACE_LISTEN, tcp, 0) < 0) {
2079 /* We don't have PTRACE_LISTEN support... */
2081 goto restart_tracee;
2084 /* We handled quick cases, we are permitted to interrupt now. */
2088 /* This should be syscall entry or exit.
2089 * (Or it still can be that pesky post-execve SIGTRAP!)
2092 if (trace_syscall(tcp) < 0 && !tcp->ptrace_errno) {
2093 /* ptrace() failed in trace_syscall() with ESRCH.
2094 * Likely a result of process disappearing mid-flight.
2095 * Observed case: exit_group() terminating
2096 * all processes in thread group.
2099 /* Do we have dangling line "syscall(param, param"?
2100 * Finish the line then.
2102 printing_tcp->flags |= TCB_REPRINT;
2103 tprints(" <unfinished ...>\n");
2104 printing_tcp = NULL;
2107 /* We assume that ptrace error was caused by process death.
2108 * We used to detach(tcp) here, but since we no longer
2109 * implement "detach before death" policy/hack,
2110 * we can let this process to report its death to us
2111 * normally, via WIFEXITED or WIFSIGNALED wait status.
2115 restart_tracee_with_sig_0:
2118 /* Remember current print column before continuing. */
2119 tcp->curcol = curcol;
2120 if (ptrace_restart(PTRACE_SYSCALL, tcp, sig) < 0) {
2129 main(int argc, char *argv[])
2133 /* Run main tracing loop */
2139 if (exit_code > 0xff) {
2140 /* Avoid potential core file clobbering. */
2141 struct rlimit rlim = {0, 0};
2142 setrlimit(RLIMIT_CORE, &rlim);
2144 /* Child was killed by a signal, mimic that. */
2146 signal(exit_code, SIG_DFL);
2148 /* Paranoia - what if this signal is not fatal?
2149 Exit with 128 + signo then. */