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 <asm/ptrace_offsets.h>
45 /* In some libc, these aren't declared. Do it ourself: */
46 extern char **environ;
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 "tkill(2) not available, risk of strace hangs!"
58 # define my_tkill(tid, sig) kill((tid), (sig))
61 /* Glue for systems without a MMU that cannot provide fork() */
62 #if !defined(HAVE_FORK)
64 # define NOMMU_SYSTEM 1
67 # define fork() vfork()
70 cflag_t cflag = CFLAG_NONE;
71 unsigned int followfork = 0;
72 unsigned int ptrace_setoptions = 0;
73 unsigned int xflag = 0;
74 bool need_fork_exec_workarounds = 0;
78 /* Which WSTOPSIG(status) value marks syscall traps? */
79 static unsigned int syscall_trap_sig = SIGTRAP;
80 static unsigned int tflag = 0;
81 static bool iflag = 0;
82 static bool rflag = 0;
83 static bool print_pid_pfx = 0;
88 INTR_ANYWHERE = 1, /* don't block/ignore any signals */
89 INTR_WHILE_WAIT = 2, /* block fatal signals while decoding syscall. default */
90 INTR_NEVER = 3, /* block fatal signals. default if '-o FILE PROG' */
91 INTR_BLOCK_TSTP_TOO = 4, /* block fatal signals and SIGTSTP (^Z) */
95 /* We play with signal mask only if this mode is active: */
96 #define interactive (opt_intr == INTR_WHILE_WAIT)
99 * daemonized_tracer supports -D option.
100 * With this option, strace forks twice.
101 * Unlike normal case, with -D *grandparent* process exec's,
102 * becoming a traced process. Child exits (this prevents traced process
103 * from having children it doesn't expect to have), and grandchild
104 * attaches to grandparent similarly to strace -p PID.
105 * This allows for more transparent interaction in cases
106 * when process and its parent are communicating via signals,
107 * wait() etc. Without -D, strace process gets lodged in between,
108 * disrupting parent<->child link.
110 static bool daemonized_tracer = 0;
113 static int post_attach_sigstop = TCB_IGNORE_ONE_SIGSTOP;
114 # define use_seize (post_attach_sigstop == 0)
116 # define post_attach_sigstop TCB_IGNORE_ONE_SIGSTOP
120 /* Sometimes we want to print only succeeding syscalls. */
121 bool not_failing_only = 0;
123 /* Show path associated with fd arguments */
124 bool show_fd_path = 0;
126 static bool detach_on_execve = 0;
127 static bool skip_startup_execve = 0;
129 static int exit_code = 0;
130 static int strace_child = 0;
131 static int strace_tracer_pid = 0;
133 static char *username = NULL;
134 static uid_t run_uid;
135 static gid_t run_gid;
137 unsigned int max_strlen = DEFAULT_STRLEN;
138 static int acolumn = DEFAULT_ACOLUMN;
139 static char *acolumn_spaces;
141 static char *outfname = NULL;
142 /* If -ff, points to stderr. Else, it's our common output log */
143 static FILE *shared_log;
145 struct tcb *printing_tcp = NULL;
146 static struct tcb *current_tcp;
148 static struct tcb **tcbtab;
149 static unsigned int nprocs, tcbtabsize;
150 static const char *progname;
152 unsigned os_release; /* generated from uname()'s u.release */
154 static int detach(struct tcb *tcp);
155 static int trace(void);
156 static void cleanup(void);
157 static void interrupt(int sig);
158 static sigset_t empty_set, blocked_set;
160 #ifdef HAVE_SIG_ATOMIC_T
161 static volatile sig_atomic_t interrupted;
163 static volatile int interrupted;
166 #ifndef HAVE_STRERROR
168 #if !HAVE_DECL_SYS_ERRLIST
170 extern char *sys_errlist[];
176 static char buf[sizeof("Unknown error %d") + sizeof(int)*3];
178 if (err_no < 1 || err_no >= sys_nerr) {
179 sprintf(buf, "Unknown error %d", err_no);
182 return sys_errlist[err_no];
185 #endif /* HAVE_STERRROR */
188 usage(FILE *ofp, int exitval)
191 usage: strace [-CdffhiqrtttTvVxxy] [-I n] [-e expr]...\n\
192 [-a column] [-o file] [-s strsize] [-P path]...\n\
193 -p pid... / [-D] [-E var=val]... [-u username] PROG [ARGS]\n\
194 or: strace -c[df] [-I n] [-e expr]... [-O overhead] [-S sortby]\n\
195 -p pid... / [-D] [-E var=val]... [-u username] PROG [ARGS]\n\
196 -c -- count time, calls, and errors for each syscall and report summary\n\
197 -C -- like -c but also print regular output\n\
198 -d -- enable debug output to stderr\n\
199 -D -- run tracer process as a detached grandchild, not as parent\n\
200 -f -- follow forks, -ff -- with output into separate files\n\
201 -i -- print instruction pointer at time of syscall\n\
202 -q -- suppress messages about attaching, detaching, etc.\n\
203 -r -- print relative timestamp, -t -- absolute timestamp, -tt -- with usecs\n\
204 -T -- print time spent in each syscall\n\
205 -v -- verbose mode: print unabbreviated argv, stat, termios, etc. args\n\
206 -x -- print non-ascii strings in hex, -xx -- print all strings in hex\n\
207 -y -- print paths associated with file descriptor arguments\n\
208 -h -- print help message, -V -- print version\n\
209 -a column -- alignment COLUMN for printing syscall results (default %d)\n\
210 -b execve -- detach on this syscall\n\
211 -e expr -- a qualifying expression: option=[!]all or option=[!]val1[,val2]...\n\
212 options: trace, abbrev, verbose, raw, signal, read, write\n\
213 -I interruptible --\n\
214 1: no signals are blocked\n\
215 2: fatal signals are blocked while decoding syscall (default)\n\
216 3: fatal signals are always blocked (default if '-o FILE PROG')\n\
217 4: fatal signals and SIGTSTP (^Z) are always blocked\n\
218 (useful to make 'strace -o FILE PROG' not stop on ^Z)\n\
219 -o file -- send trace output to FILE instead of stderr\n\
220 -O overhead -- set overhead for tracing syscalls to OVERHEAD usecs\n\
221 -p pid -- trace process with process id PID, may be repeated\n\
222 -s strsize -- limit length of print strings to STRSIZE chars (default %d)\n\
223 -S sortby -- sort syscall counts by: time, calls, name, nothing (default %s)\n\
224 -u username -- run command as username handling setuid and/or setgid\n\
225 -E var=val -- put var=val in the environment for command\n\
226 -E var -- remove var from the environment for command\n\
227 -P path -- trace accesses to path\n\
229 /* ancient, no one should use it
230 -F -- attempt to follow vforks (deprecated, use -f)\n\
232 /* this is broken, so don't document it
233 -z -- print only succeeding syscalls\n\
235 , DEFAULT_ACOLUMN, DEFAULT_STRLEN, DEFAULT_SORTBY);
239 static void die(void) __attribute__ ((noreturn));
240 static void die(void)
242 if (strace_tracer_pid == getpid()) {
249 static void verror_msg(int err_no, const char *fmt, va_list p)
255 /* We want to print entire message with single fprintf to ensure
256 * message integrity if stderr is shared with other programs.
257 * Thus we use vasprintf + single fprintf.
260 if (vasprintf(&msg, fmt, p) >= 0) {
262 fprintf(stderr, "%s: %s: %s\n", progname, msg, strerror(err_no));
264 fprintf(stderr, "%s: %s\n", progname, msg);
267 /* malloc in vasprintf failed, try it without malloc */
268 fprintf(stderr, "%s: ", progname);
269 vfprintf(stderr, fmt, p);
271 fprintf(stderr, ": %s\n", strerror(err_no));
275 /* We don't switch stderr to buffered, thus fprintf(stderr)
276 * always flushes its output and this is not necessary: */
277 /* fflush(stderr); */
280 void error_msg(const char *fmt, ...)
284 verror_msg(0, fmt, p);
288 void error_msg_and_die(const char *fmt, ...)
292 verror_msg(0, fmt, p);
296 void perror_msg(const char *fmt, ...)
300 verror_msg(errno, fmt, p);
304 void perror_msg_and_die(const char *fmt, ...)
308 verror_msg(errno, fmt, p);
312 void die_out_of_memory(void)
314 static bool recursed = 0;
318 error_msg_and_die("Out of memory");
322 error_opt_arg(int opt, const char *arg)
324 error_msg_and_die("Invalid -%c argument: '%s'", opt, arg);
329 ptrace_attach_or_seize(int pid)
333 return ptrace(PTRACE_ATTACH, pid, 0, 0);
334 r = ptrace(PTRACE_SEIZE, pid, 0, 0);
337 r = ptrace(PTRACE_INTERRUPT, pid, 0, 0);
341 # define ptrace_attach_or_seize(pid) ptrace(PTRACE_ATTACH, (pid), 0, 0)
345 * Used when we want to unblock stopped traced process.
346 * Should be only used with PTRACE_CONT, PTRACE_DETACH and PTRACE_SYSCALL.
347 * Returns 0 on success or if error was ESRCH
348 * (presumably process was killed while we talk to it).
349 * Otherwise prints error message and returns -1.
352 ptrace_restart(int op, struct tcb *tcp, int sig)
358 ptrace(op, tcp->pid, (void *) 0, (long) sig);
364 if (op == PTRACE_CONT)
366 if (op == PTRACE_DETACH)
369 if (op == PTRACE_LISTEN)
373 * Why curcol != 0? Otherwise sometimes we get this:
375 * 10252 kill(10253, SIGKILL) = 0
376 * <ptrace(SYSCALL,10252):No such process>10253 ...next decode...
378 * 10252 died after we retrieved syscall exit data,
379 * but before we tried to restart it. Log looks ugly.
381 if (current_tcp && current_tcp->curcol != 0) {
382 tprintf(" <ptrace(%s):%s>\n", msg, strerror(err));
388 perror_msg("ptrace(PTRACE_%s,pid:%d,sig:%d)", msg, tcp->pid, sig);
393 set_cloexec_flag(int fd)
397 flags = fcntl(fd, F_GETFD);
399 /* Can happen only if fd is bad.
400 * Should never happen: if it does, we have a bug
401 * in the caller. Therefore we just abort
402 * instead of propagating the error.
404 perror_msg_and_die("fcntl(%d, F_GETFD)", fd);
407 newflags = flags | FD_CLOEXEC;
408 if (flags == newflags)
411 fcntl(fd, F_SETFD, newflags); /* never fails */
414 static void kill_save_errno(pid_t pid, int sig)
416 int saved_errno = errno;
418 (void) kill(pid, sig);
423 * When strace is setuid executable, we have to swap uids
424 * before and after filesystem and process management operations.
429 int euid = geteuid(), uid = getuid();
431 if (euid != uid && setreuid(euid, uid) < 0) {
432 perror_msg_and_die("setreuid");
437 # define fopen_for_output fopen64
439 # define fopen_for_output fopen
443 strace_fopen(const char *path)
448 fp = fopen_for_output(path, "w");
450 perror_msg_and_die("Can't fopen '%s'", path);
452 set_cloexec_flag(fileno(fp));
456 static int popen_pid = 0;
459 # define _PATH_BSHELL "/bin/sh"
463 * We cannot use standard popen(3) here because we have to distinguish
464 * popen child process from other processes we trace, and standard popen(3)
465 * does not export its child's pid.
468 strace_popen(const char *command)
475 perror_msg_and_die("pipe");
477 set_cloexec_flag(fds[1]); /* never fails */
481 perror_msg_and_die("vfork");
483 if (popen_pid == 0) {
488 perror_msg_and_die("dup2");
491 execl(_PATH_BSHELL, "sh", "-c", command, NULL);
492 perror_msg_and_die("Can't execute '%s'", _PATH_BSHELL);
498 fp = fdopen(fds[1], "w");
505 tprintf(const char *fmt, ...)
511 int n = strace_vfprintf(current_tcp->outf, fmt, args);
513 if (current_tcp->outf != stderr)
514 perror_msg("%s", outfname);
516 current_tcp->curcol += n;
522 tprints(const char *str)
525 int n = fputs_unlocked(str, current_tcp->outf);
527 current_tcp->curcol += strlen(str);
530 if (current_tcp->outf != stderr)
531 perror_msg("%s", outfname);
539 current_tcp->curcol = 0;
540 fflush(current_tcp->outf);
543 printing_tcp->curcol = 0;
549 printleader(struct tcb *tcp)
551 /* If -ff, "previous tcb we printed" is always the same as current,
552 * because we have per-tcb output files.
558 current_tcp = printing_tcp;
559 if (printing_tcp->curcol != 0 && (followfork < 2 || printing_tcp == tcp)) {
561 * case 1: we have a shared log (i.e. not -ff), and last line
562 * wasn't finished (same or different tcb, doesn't matter).
563 * case 2: split log, we are the same tcb, but our last line
564 * didn't finish ("SIGKILL nuked us after syscall entry" etc).
566 tprints(" <unfinished ...>\n");
567 printing_tcp->curcol = 0;
573 current_tcp->curcol = 0;
576 tprintf("%-5d ", tcp->pid);
577 else if (nprocs > 1 && !outfname)
578 tprintf("[pid %5u] ", tcp->pid);
581 char str[sizeof("HH:MM:SS")];
582 struct timeval tv, dtv;
583 static struct timeval otv;
585 gettimeofday(&tv, NULL);
589 tv_sub(&dtv, &tv, &otv);
590 tprintf("%6ld.%06ld ",
591 (long) dtv.tv_sec, (long) dtv.tv_usec);
594 else if (tflag > 2) {
595 tprintf("%ld.%06ld ",
596 (long) tv.tv_sec, (long) tv.tv_usec);
599 time_t local = tv.tv_sec;
600 strftime(str, sizeof(str), "%T", localtime(&local));
602 tprintf("%s.%06ld ", str, (long) tv.tv_usec);
614 if (current_tcp->curcol < acolumn)
615 tprints(acolumn_spaces + current_tcp->curcol);
618 /* Should be only called directly *after successful attach* to a tracee.
619 * Otherwise, "strace -oFILE -ff -p<nonexistant_pid>"
620 * may create bogus empty FILE.<nonexistant_pid>, and then die.
623 newoutf(struct tcb *tcp)
625 tcp->outf = shared_log; /* if not -ff mode, the same file is for all */
626 if (followfork >= 2) {
627 char name[520 + sizeof(int) * 3];
628 sprintf(name, "%.512s.%u", outfname, tcp->pid);
629 tcp->outf = strace_fopen(name);
636 /* Allocate some more TCBs and expand the table.
637 We don't want to relocate the TCBs because our
638 callers have pointers and it would be a pain.
639 So tcbtab is a table of pointers. Since we never
640 free the TCBs, we allocate a single chunk of many. */
642 struct tcb *newtcbs = calloc(tcbtabsize, sizeof(newtcbs[0]));
643 struct tcb **newtab = realloc(tcbtab, tcbtabsize * 2 * sizeof(tcbtab[0]));
644 if (!newtab || !newtcbs)
648 while (i < tcbtabsize)
649 tcbtab[i++] = newtcbs++;
658 if (nprocs == tcbtabsize)
661 for (i = 0; i < tcbtabsize; i++) {
663 if ((tcp->flags & TCB_INUSE) == 0) {
664 memset(tcp, 0, sizeof(*tcp));
666 tcp->flags = TCB_INUSE;
667 #if SUPPORTED_PERSONALITIES > 1
668 tcp->currpers = current_personality;
672 fprintf(stderr, "new tcb for pid %d, active tcbs:%d\n", tcp->pid, nprocs);
676 error_msg_and_die("bug in alloctcb");
680 droptcb(struct tcb *tcp)
687 fprintf(stderr, "dropped tcb for pid %d, %d remain\n", tcp->pid, nprocs);
690 if (followfork >= 2) {
691 if (tcp->curcol != 0)
692 fprintf(tcp->outf, " <detached ...>\n");
695 if (printing_tcp == tcp && tcp->curcol != 0)
696 fprintf(tcp->outf, " <detached ...>\n");
701 if (current_tcp == tcp)
703 if (printing_tcp == tcp)
706 memset(tcp, 0, sizeof(*tcp));
709 /* detach traced process; continue with sig
710 * Never call DETACH twice on the same process as both unattached and
711 * attached-unstopped processes give the same ESRCH. For unattached process we
712 * would SIGSTOP it and wait for its SIGSTOP notification forever.
715 detach(struct tcb *tcp)
718 int status, sigstop_expected;
720 if (tcp->flags & TCB_BPTSET)
724 * Linux wrongly insists the child be stopped
725 * before detaching. Arghh. We go through hoops
726 * to make a clean break of things.
729 # undef PTRACE_DETACH
730 # define PTRACE_DETACH PTRACE_SUNDETACH
734 sigstop_expected = 0;
735 if (tcp->flags & TCB_ATTACHED) {
737 * We attached but possibly didn't see the expected SIGSTOP.
738 * We must catch exactly one as otherwise the detached process
739 * would be left stopped (process state T).
741 sigstop_expected = (tcp->flags & TCB_IGNORE_ONE_SIGSTOP);
742 error = ptrace(PTRACE_DETACH, tcp->pid, (char *) 1, 0);
744 /* On a clear day, you can see forever. */
746 else if (errno != ESRCH) {
747 /* Shouldn't happen. */
748 perror_msg("detach: ptrace(PTRACE_DETACH, ...)");
750 else if (my_tkill(tcp->pid, 0) < 0) {
752 perror_msg("detach: checking sanity");
754 else if (!sigstop_expected && my_tkill(tcp->pid, SIGSTOP) < 0) {
756 perror_msg("detach: stopping child");
759 sigstop_expected = 1;
762 if (sigstop_expected) {
765 if (waitpid(tcp->pid, &status, __WALL) < 0) {
766 if (errno == ECHILD) /* Already gone. */
768 if (errno != EINVAL) {
769 perror_msg("detach: waiting");
773 /* No __WALL here. */
774 if (waitpid(tcp->pid, &status, 0) < 0) {
775 if (errno != ECHILD) {
776 perror_msg("detach: waiting");
780 /* If no processes, try clones. */
781 if (waitpid(tcp->pid, &status, __WCLONE) < 0) {
783 perror_msg("detach: waiting");
786 #endif /* __WCLONE */
791 if (!WIFSTOPPED(status)) {
792 /* Au revoir, mon ami. */
795 if (WSTOPSIG(status) == SIGSTOP) {
796 ptrace_restart(PTRACE_DETACH, tcp, 0);
799 error = ptrace_restart(PTRACE_CONT, tcp,
800 WSTOPSIG(status) == syscall_trap_sig ? 0
807 if (!qflag && (tcp->flags & TCB_ATTACHED))
808 fprintf(stderr, "Process %u detached\n", tcp->pid);
816 process_opt_p_list(char *opt)
820 * We accept -p PID,PID; -p "`pidof PROG`"; -p "`pgrep PROG`".
821 * pidof uses space as delim, pgrep uses newline. :(
824 char *delim = opt + strcspn(opt, ", \n\t");
828 pid = string_to_uint(opt);
830 error_msg_and_die("Invalid process id: '%s'", opt);
832 if (pid == strace_tracer_pid) {
833 error_msg_and_die("I'm sorry, I can't let you do that, Dave.");
850 * Block user interruptions as we would leave the traced
851 * process stopped (process state T) if we would terminate in
852 * between PTRACE_ATTACH and wait4() on SIGSTOP.
853 * We rely on cleanup() from this point on.
856 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
858 if (daemonized_tracer) {
861 perror_msg_and_die("fork");
863 if (pid) { /* parent */
865 * Wait for grandchild to attach to straced process
866 * (grandparent). Grandchild SIGKILLs us after it attached.
867 * Grandparent's wait() is unblocked by our death,
868 * it proceeds to exec the straced program.
871 _exit(0); /* paranoia */
874 /* We will be the tracer process. Remember our new pid: */
875 strace_tracer_pid = getpid();
878 for (tcbi = 0; tcbi < tcbtabsize; tcbi++) {
881 if (!(tcp->flags & TCB_INUSE))
884 /* Is this a process we should attach to, but not yet attached? */
885 if (tcp->flags & TCB_ATTACHED)
886 continue; /* no, we already attached it */
888 if (followfork && !daemonized_tracer) {
889 char procdir[sizeof("/proc/%d/task") + sizeof(int) * 3];
892 sprintf(procdir, "/proc/%d/task", tcp->pid);
893 dir = opendir(procdir);
895 unsigned int ntid = 0, nerr = 0;
898 while ((de = readdir(dir)) != NULL) {
902 if (de->d_fileno == 0)
904 /* we trust /proc filesystem */
905 tid = atoi(de->d_name);
909 if (ptrace_attach_or_seize(tid) < 0) {
912 fprintf(stderr, "attach to pid %d failed\n", tid);
916 fprintf(stderr, "attach to pid %d succeeded\n", tid);
919 cur_tcp = alloctcb(tid);
920 cur_tcp->flags |= TCB_ATTACHED | TCB_STARTUP | post_attach_sigstop;
925 sigprocmask(SIG_SETMASK, &empty_set, NULL);
928 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
932 perror_msg("attach: ptrace(PTRACE_ATTACH, ...)");
937 fprintf(stderr, ntid > 1
938 ? "Process %u attached with %u threads\n"
939 : "Process %u attached\n",
942 if (!(tcp->flags & TCB_ATTACHED)) {
943 /* -p PID, we failed to attach to PID itself
944 * but did attach to some of its sibling threads.
950 } /* if (opendir worked) */
952 if (ptrace_attach_or_seize(tcp->pid) < 0) {
953 perror_msg("attach: ptrace(PTRACE_ATTACH, ...)");
957 tcp->flags |= TCB_ATTACHED | TCB_STARTUP | post_attach_sigstop;
960 fprintf(stderr, "attach to pid %d (main) succeeded\n", tcp->pid);
962 if (daemonized_tracer) {
964 * Make parent go away.
965 * Also makes grandparent's wait() unblock.
967 kill(getppid(), SIGKILL);
972 "Process %u attached\n",
974 } /* for each tcbtab[] */
978 sigprocmask(SIG_SETMASK, &empty_set, NULL);
981 /* Stack-o-phobic exec helper, in the hope to work around
982 * NOMMU + "daemonized tracer" difficulty.
991 static struct exec_params params_for_tracee;
992 static void __attribute__ ((noinline, noreturn))
995 struct exec_params *params = ¶ms_for_tracee;
997 if (params->fd_to_close >= 0)
998 close(params->fd_to_close);
999 if (!daemonized_tracer && !use_seize) {
1000 if (ptrace(PTRACE_TRACEME, 0L, 0L, 0L) < 0) {
1001 perror_msg_and_die("ptrace(PTRACE_TRACEME, ...)");
1005 if (username != NULL) {
1007 * It is important to set groups before we
1008 * lose privileges on setuid.
1010 if (initgroups(username, run_gid) < 0) {
1011 perror_msg_and_die("initgroups");
1013 if (setregid(run_gid, params->run_egid) < 0) {
1014 perror_msg_and_die("setregid");
1016 if (setreuid(run_uid, params->run_euid) < 0) {
1017 perror_msg_and_die("setreuid");
1020 else if (geteuid() != 0)
1021 if (setreuid(run_uid, run_uid) < 0) {
1022 perror_msg_and_die("setreuid");
1025 if (!daemonized_tracer) {
1027 * Induce a ptrace stop. Tracer (our parent)
1028 * will resume us with PTRACE_SYSCALL and display
1029 * the immediately following execve syscall.
1030 * Can't do this on NOMMU systems, we are after
1031 * vfork: parent is blocked, stopping would deadlock.
1034 kill(getpid(), SIGSTOP);
1037 /* we depend on SIGCHLD set to SIG_DFL by init code */
1038 /* if it happens to be SIG_IGN'ed, wait won't block */
1043 execv(params->pathname, params->argv);
1044 perror_msg_and_die("exec");
1048 startup_child(char **argv)
1050 struct stat statbuf;
1051 const char *filename;
1052 char pathname[MAXPATHLEN];
1057 if (strchr(filename, '/')) {
1058 if (strlen(filename) > sizeof pathname - 1) {
1059 errno = ENAMETOOLONG;
1060 perror_msg_and_die("exec");
1062 strcpy(pathname, filename);
1064 #ifdef USE_DEBUGGING_EXEC
1066 * Debuggers customarily check the current directory
1067 * first regardless of the path but doing that gives
1068 * security geeks a panic attack.
1070 else if (stat(filename, &statbuf) == 0)
1071 strcpy(pathname, filename);
1072 #endif /* USE_DEBUGGING_EXEC */
1077 for (path = getenv("PATH"); path && *path; path += m) {
1078 const char *colon = strchr(path, ':');
1084 m = n = strlen(path);
1086 if (!getcwd(pathname, MAXPATHLEN))
1088 len = strlen(pathname);
1090 else if (n > sizeof pathname - 1)
1093 strncpy(pathname, path, n);
1096 if (len && pathname[len - 1] != '/')
1097 pathname[len++] = '/';
1098 strcpy(pathname + len, filename);
1099 if (stat(pathname, &statbuf) == 0 &&
1100 /* Accept only regular files
1101 with some execute bits set.
1102 XXX not perfect, might still fail */
1103 S_ISREG(statbuf.st_mode) &&
1104 (statbuf.st_mode & 0111))
1108 if (stat(pathname, &statbuf) < 0) {
1109 perror_msg_and_die("Can't stat '%s'", filename);
1112 params_for_tracee.fd_to_close = (shared_log != stderr) ? fileno(shared_log) : -1;
1113 params_for_tracee.run_euid = (statbuf.st_mode & S_ISUID) ? statbuf.st_uid : run_uid;
1114 params_for_tracee.run_egid = (statbuf.st_mode & S_ISGID) ? statbuf.st_gid : run_gid;
1115 params_for_tracee.argv = argv;
1117 * On NOMMU, can be safely freed only after execve in tracee.
1118 * It's hard to know when that happens, so we just leak it.
1120 params_for_tracee.pathname = NOMMU_SYSTEM ? strdup(pathname) : pathname;
1122 strace_child = pid = fork();
1124 perror_msg_and_die("fork");
1126 if ((pid != 0 && daemonized_tracer)
1127 || (pid == 0 && !daemonized_tracer)
1129 /* We are to become the tracee. Two cases:
1131 * not -D: we are child
1136 /* We are the tracer */
1138 if (!daemonized_tracer) {
1140 /* child did PTRACE_TRACEME, nothing to do in parent */
1142 if (!NOMMU_SYSTEM) {
1143 /* Wait until child stopped itself */
1145 while (waitpid(pid, &status, WSTOPPED) < 0) {
1148 perror_msg_and_die("waitpid");
1150 if (!WIFSTOPPED(status) || WSTOPSIG(status) != SIGSTOP) {
1151 kill_save_errno(pid, SIGKILL);
1152 perror_msg_and_die("Unexpected wait status %x", status);
1154 skip_startup_execve = 1;
1156 /* Else: NOMMU case, we have no way to sync.
1157 * Just attach to it as soon as possible.
1158 * This means that we may miss a few first syscalls...
1161 if (ptrace_attach_or_seize(pid)) {
1162 kill_save_errno(pid, SIGKILL);
1163 perror_msg_and_die("Can't attach to %d", pid);
1168 tcp = alloctcb(pid);
1170 tcp->flags |= TCB_ATTACHED | TCB_STRACE_CHILD | TCB_STARTUP | post_attach_sigstop;
1172 tcp->flags |= TCB_ATTACHED | TCB_STRACE_CHILD | TCB_STARTUP;
1176 /* With -D, we are *child* here, IOW: different pid. Fetch it: */
1177 strace_tracer_pid = getpid();
1178 /* The tracee is our parent: */
1181 /* attaching will be done later, by startup_attach */
1182 /* note: we don't do newoutf(tcp) here either! */
1183 skip_startup_execve = 1;
1185 /* NOMMU BUG! -D mode is active, we (child) return,
1186 * and we will scribble over parent's stack!
1187 * When parent later unpauses, it segfaults.
1190 * (1) by declaring exec_or_die() NORETURN,
1191 * hopefully compiler will just jump to it
1192 * instead of call (won't push anything to stack),
1193 * (2) by trying very hard in exec_or_die()
1194 * to not use any stack,
1195 * (3) having a really big (MAXPATHLEN) stack object
1196 * in this function, which creates a "buffer" between
1197 * child's and parent's stack pointers.
1198 * This may save us if (1) and (2) failed
1199 * and compiler decided to use stack in exec_or_die() anyway
1200 * (happens on i386 because of stack parameter passing).
1202 * A cleaner solution is to use makecontext + setcontext
1203 * to create a genuine separate stack and execute on it.
1209 * Test whether the kernel support PTRACE_O_TRACECLONE et al options.
1210 * First fork a new child, call ptrace with PTRACE_SETOPTIONS on it,
1211 * and then see which options are supported by the kernel.
1214 test_ptrace_setoptions_followfork(void)
1216 int pid, expected_grandchild = 0, found_grandchild = 0;
1217 const unsigned int test_options = PTRACE_O_TRACECLONE |
1218 PTRACE_O_TRACEFORK |
1219 PTRACE_O_TRACEVFORK;
1221 /* Need fork for test. NOMMU has no forks */
1223 goto worked; /* be bold, and pretend that test succeeded */
1227 perror_msg_and_die("fork");
1230 if (ptrace(PTRACE_TRACEME, 0L, 0L, 0L) < 0)
1231 perror_msg_and_die("%s: PTRACE_TRACEME doesn't work",
1233 kill_save_errno(pid, SIGSTOP);
1235 perror_msg_and_die("fork");
1240 int status, tracee_pid;
1243 tracee_pid = wait(&status);
1244 if (tracee_pid <= 0) {
1247 if (errno == ECHILD)
1249 kill_save_errno(pid, SIGKILL);
1250 perror_msg_and_die("%s: unexpected wait result %d",
1251 __func__, tracee_pid);
1253 if (WIFEXITED(status)) {
1254 if (WEXITSTATUS(status)) {
1255 if (tracee_pid != pid)
1256 kill_save_errno(pid, SIGKILL);
1257 error_msg_and_die("%s: unexpected exit status %u",
1258 __func__, WEXITSTATUS(status));
1262 if (WIFSIGNALED(status)) {
1263 if (tracee_pid != pid)
1264 kill_save_errno(pid, SIGKILL);
1265 error_msg_and_die("%s: unexpected signal %u",
1266 __func__, WTERMSIG(status));
1268 if (!WIFSTOPPED(status)) {
1269 if (tracee_pid != pid)
1270 kill_save_errno(tracee_pid, SIGKILL);
1271 kill_save_errno(pid, SIGKILL);
1272 error_msg_and_die("%s: unexpected wait status %x",
1275 if (tracee_pid != pid) {
1276 found_grandchild = tracee_pid;
1277 if (ptrace(PTRACE_CONT, tracee_pid, 0, 0) < 0) {
1278 kill_save_errno(tracee_pid, SIGKILL);
1279 kill_save_errno(pid, SIGKILL);
1280 perror_msg_and_die("PTRACE_CONT doesn't work");
1284 switch (WSTOPSIG(status)) {
1286 if (ptrace(PTRACE_SETOPTIONS, pid, 0, test_options) < 0
1287 && errno != EINVAL && errno != EIO)
1288 perror_msg("PTRACE_SETOPTIONS");
1291 if (status >> 16 == PTRACE_EVENT_FORK) {
1294 if (ptrace(PTRACE_GETEVENTMSG, pid,
1295 NULL, (long) &msg) == 0)
1296 expected_grandchild = msg;
1300 if (ptrace(PTRACE_SYSCALL, pid, 0, 0) < 0) {
1301 kill_save_errno(pid, SIGKILL);
1302 perror_msg_and_die("PTRACE_SYSCALL doesn't work");
1305 if (expected_grandchild && expected_grandchild == found_grandchild) {
1307 ptrace_setoptions |= test_options;
1309 fprintf(stderr, "ptrace_setoptions = %#x\n",
1313 error_msg("Test for PTRACE_O_TRACECLONE failed, "
1314 "giving up using this feature.");
1319 * Test whether the kernel support PTRACE_O_TRACESYSGOOD.
1320 * First fork a new child, call ptrace(PTRACE_SETOPTIONS) on it,
1321 * and then see whether it will stop with (SIGTRAP | 0x80).
1323 * Use of this option enables correct handling of user-generated SIGTRAPs,
1324 * and SIGTRAPs generated by special instructions such as int3 on x86:
1325 * _start: .globl _start
1330 * (compile with: "gcc -nostartfiles -nostdlib -o int3 int3.S")
1333 test_ptrace_setoptions_for_all(void)
1335 const unsigned int test_options = PTRACE_O_TRACESYSGOOD |
1340 /* Need fork for test. NOMMU has no forks */
1342 goto worked; /* be bold, and pretend that test succeeded */
1346 perror_msg_and_die("fork");
1350 if (ptrace(PTRACE_TRACEME, 0L, 0L, 0L) < 0)
1351 /* Note: exits with exitcode 1 */
1352 perror_msg_and_die("%s: PTRACE_TRACEME doesn't work",
1355 _exit(0); /* parent should see entry into this syscall */
1359 int status, tracee_pid;
1362 tracee_pid = wait(&status);
1363 if (tracee_pid <= 0) {
1366 kill_save_errno(pid, SIGKILL);
1367 perror_msg_and_die("%s: unexpected wait result %d",
1368 __func__, tracee_pid);
1370 if (WIFEXITED(status)) {
1371 if (WEXITSTATUS(status) == 0)
1373 error_msg_and_die("%s: unexpected exit status %u",
1374 __func__, WEXITSTATUS(status));
1376 if (WIFSIGNALED(status)) {
1377 error_msg_and_die("%s: unexpected signal %u",
1378 __func__, WTERMSIG(status));
1380 if (!WIFSTOPPED(status)) {
1382 error_msg_and_die("%s: unexpected wait status %x",
1385 if (WSTOPSIG(status) == SIGSTOP) {
1387 * We don't check "options aren't accepted" error.
1388 * If it happens, we'll never get (SIGTRAP | 0x80),
1389 * and thus will decide to not use the option.
1390 * IOW: the outcome of the test will be correct.
1392 if (ptrace(PTRACE_SETOPTIONS, pid, 0L, test_options) < 0
1393 && errno != EINVAL && errno != EIO)
1394 perror_msg("PTRACE_SETOPTIONS");
1396 if (WSTOPSIG(status) == (SIGTRAP | 0x80)) {
1399 if (ptrace(PTRACE_SYSCALL, pid, 0L, 0L) < 0) {
1400 kill_save_errno(pid, SIGKILL);
1401 perror_msg_and_die("PTRACE_SYSCALL doesn't work");
1407 syscall_trap_sig = (SIGTRAP | 0x80);
1408 ptrace_setoptions |= test_options;
1410 fprintf(stderr, "ptrace_setoptions = %#x\n",
1415 error_msg("Test for PTRACE_O_TRACESYSGOOD failed, "
1416 "giving up using this feature.");
1422 test_ptrace_seize(void)
1426 /* Need fork for test. NOMMU has no forks */
1428 post_attach_sigstop = 0; /* this sets use_seize to 1 */
1434 perror_msg_and_die("fork");
1441 /* PTRACE_SEIZE, unlike ATTACH, doesn't force tracee to trap. After
1442 * attaching tracee continues to run unless a trap condition occurs.
1443 * PTRACE_SEIZE doesn't affect signal or group stop state.
1445 if (ptrace(PTRACE_SEIZE, pid, 0, 0) == 0) {
1446 post_attach_sigstop = 0; /* this sets use_seize to 1 */
1447 } else if (debug_flag) {
1448 fprintf(stderr, "PTRACE_SEIZE doesn't work\n");
1454 int status, tracee_pid;
1457 tracee_pid = waitpid(pid, &status, 0);
1458 if (tracee_pid <= 0) {
1461 perror_msg_and_die("%s: unexpected wait result %d",
1462 __func__, tracee_pid);
1464 if (WIFSIGNALED(status)) {
1467 error_msg_and_die("%s: unexpected wait status %x",
1471 #else /* !USE_SEIZE */
1472 # define test_ptrace_seize() ((void)0)
1476 get_os_release(void)
1482 perror_msg_and_die("uname");
1483 /* u.release has this form: "3.2.9[-some-garbage]" */
1487 if (!(*p >= '0' && *p <= '9'))
1488 error_msg_and_die("Bad OS release string: '%s'", u.release);
1489 /* Note: this open-codes KERNEL_VERSION(): */
1490 rel = (rel << 8) | atoi(p);
1491 if (rel >= KERNEL_VERSION(1,0,0))
1493 while (*p >= '0' && *p <= '9')
1496 if (rel >= KERNEL_VERSION(0,1,0)) {
1497 /* "X.Y-something" means "X.Y.0" */
1501 error_msg_and_die("Bad OS release string: '%s'", u.release);
1509 * Initialization part of main() was eating much stack (~0.5k),
1510 * which was unused after init.
1511 * We can reuse it if we move init code into a separate function.
1513 * Don't want main() to inline us and defeat the reason
1514 * we have a separate function.
1516 static void __attribute__ ((noinline))
1517 init(int argc, char *argv[])
1522 struct sigaction sa;
1524 progname = argv[0] ? argv[0] : "strace";
1526 /* Make sure SIGCHLD has the default action so that waitpid
1527 definitely works without losing track of children. The user
1528 should not have given us a bogus state to inherit, but he might
1529 have. Arguably we should detect SIG_IGN here and pass it on
1530 to children, but probably noone really needs that. */
1531 signal(SIGCHLD, SIG_DFL);
1533 strace_tracer_pid = getpid();
1535 os_release = get_os_release();
1537 /* Allocate the initial tcbtab. */
1538 tcbtabsize = argc; /* Surely enough for all -p args. */
1539 tcbtab = calloc(tcbtabsize, sizeof(tcbtab[0]));
1541 die_out_of_memory();
1542 tcp = calloc(tcbtabsize, sizeof(*tcp));
1544 die_out_of_memory();
1545 for (c = 0; c < tcbtabsize; c++)
1548 shared_log = stderr;
1549 set_sortby(DEFAULT_SORTBY);
1550 set_personality(DEFAULT_PERSONALITY);
1551 qualify("trace=all");
1552 qualify("abbrev=all");
1553 qualify("verbose=all");
1554 #if DEFAULT_QUAL_FLAGS != (QUAL_TRACE | QUAL_ABBREV | QUAL_VERBOSE)
1555 # error Bug in DEFAULT_QUAL_FLAGS
1557 qualify("signal=all");
1558 while ((c = getopt(argc, argv,
1559 "+b:cCdfFhiqrtTvVxyz"
1561 "a:e:o:O:p:s:S:u:E:P:I:")) != EOF) {
1564 if (strcmp(optarg, "execve") != 0)
1565 error_msg_and_die("Syscall '%s' for -b isn't supported",
1567 detach_on_execve = 1;
1570 if (cflag == CFLAG_BOTH) {
1571 error_msg_and_die("-c and -C are mutually exclusive");
1573 cflag = CFLAG_ONLY_STATS;
1576 if (cflag == CFLAG_ONLY_STATS) {
1577 error_msg_and_die("-c and -C are mutually exclusive");
1585 daemonized_tracer = 1;
1604 /* fall through to tflag++ */
1618 qualify("abbrev=none");
1621 printf("%s -- version %s\n", PACKAGE_NAME, VERSION);
1625 not_failing_only = 1;
1628 acolumn = string_to_uint(optarg);
1630 error_opt_arg(c, optarg);
1636 outfname = strdup(optarg);
1639 i = string_to_uint(optarg);
1641 error_opt_arg(c, optarg);
1645 process_opt_p_list(optarg);
1648 pathtrace_select(optarg);
1651 i = string_to_uint(optarg);
1653 error_opt_arg(c, optarg);
1660 username = strdup(optarg);
1663 if (putenv(optarg) < 0)
1664 die_out_of_memory();
1667 opt_intr = string_to_uint(optarg);
1668 if (opt_intr <= 0 || opt_intr >= NUM_INTR_OPTS)
1669 error_opt_arg(c, optarg);
1677 /* argc -= optind; - no need, argc is not used below */
1679 acolumn_spaces = malloc(acolumn + 1);
1680 if (!acolumn_spaces)
1681 die_out_of_memory();
1682 memset(acolumn_spaces, ' ', acolumn);
1683 acolumn_spaces[acolumn] = '\0';
1685 /* Must have PROG [ARGS], or -p PID. Not both. */
1686 if (!argv[0] == !nprocs)
1689 if (nprocs != 0 && daemonized_tracer) {
1690 error_msg_and_die("-D and -p are mutually exclusive");
1696 if (followfork >= 2 && cflag) {
1697 error_msg_and_die("(-c or -C) and -ff are mutually exclusive");
1700 /* See if they want to run as another user. */
1701 if (username != NULL) {
1702 struct passwd *pent;
1704 if (getuid() != 0 || geteuid() != 0) {
1705 error_msg_and_die("You must be root to use the -u option");
1707 pent = getpwnam(username);
1709 error_msg_and_die("Cannot find user '%s'", username);
1711 run_uid = pent->pw_uid;
1712 run_gid = pent->pw_gid;
1720 * On any reasonably recent Linux kernel (circa about 2.5.46)
1721 * need_fork_exec_workarounds should stay 0 after these tests:
1723 /*need_fork_exec_workarounds = 0; - already is */
1725 need_fork_exec_workarounds = test_ptrace_setoptions_followfork();
1726 need_fork_exec_workarounds |= test_ptrace_setoptions_for_all();
1727 test_ptrace_seize();
1729 /* Check if they want to redirect the output. */
1731 /* See if they want to pipe the output. */
1732 if (outfname[0] == '|' || outfname[0] == '!') {
1734 * We can't do the <outfname>.PID funny business
1735 * when using popen, so prohibit it.
1737 if (followfork >= 2)
1738 error_msg_and_die("Piping the output and -ff are mutually exclusive");
1739 shared_log = strace_popen(outfname + 1);
1741 else if (followfork < 2)
1742 shared_log = strace_fopen(outfname);
1744 /* -ff without -o FILE is the same as single -f */
1745 if (followfork >= 2)
1749 if (!outfname || outfname[0] == '|' || outfname[0] == '!') {
1750 char *buf = malloc(BUFSIZ);
1752 die_out_of_memory();
1753 setvbuf(shared_log, buf, _IOLBF, BUFSIZ);
1755 if (outfname && argv[0]) {
1757 opt_intr = INTR_NEVER;
1761 opt_intr = INTR_WHILE_WAIT;
1763 /* argv[0] -pPID -oFILE Default interactive setting
1764 * yes 0 0 INTR_WHILE_WAIT
1765 * no 1 0 INTR_WHILE_WAIT
1766 * yes 0 1 INTR_NEVER
1767 * no 1 1 INTR_WHILE_WAIT
1770 sigemptyset(&empty_set);
1771 sigemptyset(&blocked_set);
1773 /* startup_child() must be called before the signal handlers get
1774 * installed below as they are inherited into the spawned process.
1775 * Also we do not need to be protected by them as during interruption
1776 * in the startup_child() mode we kill the spawned process anyway.
1779 startup_child(argv);
1782 sa.sa_handler = SIG_IGN;
1783 sigemptyset(&sa.sa_mask);
1785 sigaction(SIGTTOU, &sa, NULL); /* SIG_IGN */
1786 sigaction(SIGTTIN, &sa, NULL); /* SIG_IGN */
1787 if (opt_intr != INTR_ANYWHERE) {
1788 if (opt_intr == INTR_BLOCK_TSTP_TOO)
1789 sigaction(SIGTSTP, &sa, NULL); /* SIG_IGN */
1791 * In interactive mode (if no -o OUTFILE, or -p PID is used),
1792 * fatal signals are blocked while syscall stop is processed,
1793 * and acted on in between, when waiting for new syscall stops.
1794 * In non-interactive mode, signals are ignored.
1796 if (opt_intr == INTR_WHILE_WAIT) {
1797 sigaddset(&blocked_set, SIGHUP);
1798 sigaddset(&blocked_set, SIGINT);
1799 sigaddset(&blocked_set, SIGQUIT);
1800 sigaddset(&blocked_set, SIGPIPE);
1801 sigaddset(&blocked_set, SIGTERM);
1802 sa.sa_handler = interrupt;
1804 /* SIG_IGN, or set handler for these */
1805 sigaction(SIGHUP, &sa, NULL);
1806 sigaction(SIGINT, &sa, NULL);
1807 sigaction(SIGQUIT, &sa, NULL);
1808 sigaction(SIGPIPE, &sa, NULL);
1809 sigaction(SIGTERM, &sa, NULL);
1811 if (nprocs != 0 || daemonized_tracer)
1814 /* Do we want pids printed in our -o OUTFILE?
1815 * -ff: no (every pid has its own file); or
1816 * -f: yes (there can be more pids in the future); or
1817 * -p PID1,PID2: yes (there are already more than one pid)
1819 print_pid_pfx = (outfname && followfork < 2 && (followfork == 1 || nprocs > 1));
1830 for (i = 0; i < tcbtabsize; i++) {
1831 struct tcb *tcp = tcbtab[i];
1832 if (tcp->pid == pid && (tcp->flags & TCB_INUSE))
1846 /* 'interrupted' is a volatile object, fetch it only once */
1847 fatal_sig = interrupted;
1849 fatal_sig = SIGTERM;
1851 for (i = 0; i < tcbtabsize; i++) {
1853 if (!(tcp->flags & TCB_INUSE))
1857 "cleanup: looking at pid %u\n", tcp->pid);
1858 if (tcp->flags & TCB_STRACE_CHILD) {
1859 kill(tcp->pid, SIGCONT);
1860 kill(tcp->pid, fatal_sig);
1865 call_summary(shared_log);
1878 struct rusage *rup = cflag ? &ru : NULL;
1880 static int wait4_options = __WALL;
1883 while (nprocs != 0) {
1894 sigprocmask(SIG_SETMASK, &empty_set, NULL);
1896 pid = wait4(-1, &status, wait4_options, rup);
1897 if (pid < 0 && (wait4_options & __WALL) && errno == EINVAL) {
1898 /* this kernel does not support __WALL */
1899 wait4_options &= ~__WALL;
1900 pid = wait4(-1, &status, wait4_options, rup);
1902 if (pid < 0 && !(wait4_options & __WALL) && errno == ECHILD) {
1903 /* most likely a "cloned" process */
1904 pid = wait4(-1, &status, __WCLONE, rup);
1906 perror_msg("wait4(__WCLONE) failed");
1910 pid = wait4(-1, &status, 0, rup);
1914 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
1917 switch (wait_errno) {
1922 * We would like to verify this case
1923 * but sometimes a race in Solbourne's
1924 * version of SunOS sometimes reports
1925 * ECHILD before sending us SIGCHILD.
1934 if (pid == popen_pid) {
1935 if (WIFEXITED(status) || WIFSIGNALED(status))
1940 event = ((unsigned)status >> 16);
1942 char buf[sizeof("WIFEXITED,exitcode=%u") + sizeof(int)*3 /*paranoia:*/ + 16];
1943 char evbuf[sizeof(",PTRACE_EVENT_?? (%u)") + sizeof(int)*3 /*paranoia:*/ + 16];
1945 if (WIFSIGNALED(status))
1947 sprintf(buf, "WIFSIGNALED,%ssig=%s",
1948 WCOREDUMP(status) ? "core," : "",
1949 signame(WTERMSIG(status)));
1951 sprintf(buf, "WIFSIGNALED,sig=%s",
1952 signame(WTERMSIG(status)));
1954 if (WIFEXITED(status))
1955 sprintf(buf, "WIFEXITED,exitcode=%u", WEXITSTATUS(status));
1956 if (WIFSTOPPED(status))
1957 sprintf(buf, "WIFSTOPPED,sig=%s", signame(WSTOPSIG(status)));
1959 if (WIFCONTINUED(status))
1960 strcpy(buf, "WIFCONTINUED");
1964 static const char *const event_names[] = {
1965 [PTRACE_EVENT_CLONE] = "CLONE",
1966 [PTRACE_EVENT_FORK] = "FORK",
1967 [PTRACE_EVENT_VFORK] = "VFORK",
1968 [PTRACE_EVENT_VFORK_DONE] = "VFORK_DONE",
1969 [PTRACE_EVENT_EXEC] = "EXEC",
1970 [PTRACE_EVENT_EXIT] = "EXIT",
1973 if (event < ARRAY_SIZE(event_names))
1974 e = event_names[event];
1976 sprintf(buf, "?? (%u)", event);
1979 sprintf(evbuf, ",PTRACE_EVENT_%s", e);
1981 fprintf(stderr, " [wait(0x%04x) = %u] %s%s\n", status, pid, buf, evbuf);
1984 /* Look up 'pid' in our table. */
1989 tcp = alloctcb(pid);
1990 tcp->flags |= TCB_ATTACHED | TCB_STARTUP | post_attach_sigstop;
1993 fprintf(stderr, "Process %d attached\n",
1996 /* This can happen if a clone call used
1997 CLONE_PTRACE itself. */
1998 if (WIFSTOPPED(status))
1999 ptrace(PTRACE_CONT, pid, (char *) 0, 0);
2000 error_msg_and_die("Unknown pid: %u", pid);
2005 if (WIFSTOPPED(status))
2008 /* Under Linux, execve changes pid to thread leader's pid,
2009 * and we see this changed pid on EVENT_EXEC and later,
2010 * execve sysexit. Leader "disappears" without exit
2011 * notification. Let user know that, drop leader's tcb,
2012 * and fix up pid in execve thread's tcb.
2013 * Effectively, execve thread's tcb replaces leader's tcb.
2015 * BTW, leader is 'stuck undead' (doesn't report WIFEXITED
2016 * on exit syscall) in multithreaded programs exactly
2017 * in order to handle this case.
2019 * PTRACE_GETEVENTMSG returns old pid starting from Linux 3.0.
2020 * On 2.6 and earlier, it can return garbage.
2022 if (event == PTRACE_EVENT_EXEC && os_release >= KERNEL_VERSION(3,0,0)) {
2024 struct tcb *execve_thread;
2027 if (ptrace(PTRACE_GETEVENTMSG, pid, NULL, (long) &old_pid) < 0)
2028 goto dont_switch_tcbs;
2029 if (old_pid <= 0 || old_pid == pid)
2030 goto dont_switch_tcbs;
2031 execve_thread = pid2tcb(old_pid);
2032 /* It should be !NULL, but I feel paranoid */
2034 goto dont_switch_tcbs;
2036 if (execve_thread->curcol != 0) {
2038 * One case we are here is -ff:
2039 * try "strace -oLOG -ff test/threaded_execve"
2041 fprintf(execve_thread->outf, " <pid changed to %d ...>\n", pid);
2042 /*execve_thread->curcol = 0; - no need, see code below */
2044 /* Swap output FILEs (needed for -ff) */
2045 fp = execve_thread->outf;
2046 execve_thread->outf = tcp->outf;
2048 /* And their column positions */
2049 execve_thread->curcol = tcp->curcol;
2051 /* Drop leader, but close execve'd thread outfile (if -ff) */
2053 /* Switch to the thread, reusing leader's outfile and pid */
2054 tcp = execve_thread;
2056 if (cflag != CFLAG_ONLY_STATS) {
2058 tprintf("+++ superseded by execve in pid %lu +++\n", old_pid);
2060 tcp->flags |= TCB_REPRINT;
2065 if (event == PTRACE_EVENT_EXEC && detach_on_execve) {
2066 if (!skip_startup_execve)
2068 /* This was initial execve for "strace PROG". Skip. */
2069 skip_startup_execve = 0;
2072 /* Set current output file */
2076 tv_sub(&tcp->dtime, &ru.ru_stime, &tcp->stime);
2077 tcp->stime = ru.ru_stime;
2080 if (WIFSIGNALED(status)) {
2081 if (pid == strace_child)
2082 exit_code = 0x100 | WTERMSIG(status);
2083 if (cflag != CFLAG_ONLY_STATS
2084 && (qual_flags[WTERMSIG(status)] & QUAL_SIGNAL)
2088 tprintf("+++ killed by %s %s+++\n",
2089 signame(WTERMSIG(status)),
2090 WCOREDUMP(status) ? "(core dumped) " : "");
2092 tprintf("+++ killed by %s +++\n",
2093 signame(WTERMSIG(status)));
2100 if (WIFEXITED(status)) {
2101 if (pid == strace_child)
2102 exit_code = WEXITSTATUS(status);
2103 if (cflag != CFLAG_ONLY_STATS) {
2105 tprintf("+++ exited with %d +++\n", WEXITSTATUS(status));
2111 if (!WIFSTOPPED(status)) {
2112 fprintf(stderr, "PANIC: pid %u not stopped\n", pid);
2117 /* Is this the very first time we see this tracee stopped? */
2118 if (tcp->flags & TCB_STARTUP) {
2120 fprintf(stderr, "pid %d has TCB_STARTUP, initializing it\n", tcp->pid);
2121 tcp->flags &= ~TCB_STARTUP;
2122 if (tcp->flags & TCB_BPTSET) {
2124 * One example is a breakpoint inherited from
2125 * parent through fork().
2127 if (clearbpt(tcp) < 0) {
2134 if (ptrace_setoptions) {
2136 fprintf(stderr, "setting opts %x on pid %d\n", ptrace_setoptions, tcp->pid);
2137 if (ptrace(PTRACE_SETOPTIONS, tcp->pid, NULL, ptrace_setoptions) < 0) {
2138 if (errno != ESRCH) {
2139 /* Should never happen, really */
2140 perror_msg_and_die("PTRACE_SETOPTIONS");
2146 sig = WSTOPSIG(status);
2151 if (event == PTRACE_EVENT_STOP) {
2153 * PTRACE_INTERRUPT-stop or group-stop.
2154 * PTRACE_INTERRUPT-stop has sig == SIGTRAP here.
2166 goto restart_tracee_with_sig_0;
2169 /* Is this post-attach SIGSTOP?
2170 * Interestingly, the process may stop
2171 * with STOPSIG equal to some other signal
2172 * than SIGSTOP if we happend to attach
2173 * just before the process takes a signal.
2175 if (sig == SIGSTOP && (tcp->flags & TCB_IGNORE_ONE_SIGSTOP)) {
2177 fprintf(stderr, "ignored SIGSTOP on pid %d\n", tcp->pid);
2178 tcp->flags &= ~TCB_IGNORE_ONE_SIGSTOP;
2179 goto restart_tracee_with_sig_0;
2182 if (sig != syscall_trap_sig) {
2185 /* Nonzero (true) if tracee is stopped by signal
2186 * (as opposed to "tracee received signal").
2187 * TODO: shouldn't we check for errno == EINVAL too?
2188 * We can get ESRCH instead, you know...
2190 stopped = (ptrace(PTRACE_GETSIGINFO, pid, 0, (long) &si) < 0);
2194 if (cflag != CFLAG_ONLY_STATS
2195 && (qual_flags[sig] & QUAL_SIGNAL)
2197 #if defined(PT_CR_IPSR) && defined(PT_CR_IIP)
2201 upeek(tcp, PT_CR_IPSR, &psr);
2202 upeek(tcp, PT_CR_IIP, &pc);
2205 pc += (psr >> PSR_RI) & 0x3;
2206 # define PC_FORMAT_STR " @ %lx"
2207 # define PC_FORMAT_ARG , pc
2209 # define PC_FORMAT_STR ""
2210 # define PC_FORMAT_ARG /* nothing */
2214 tprintf("--- %s ", signame(sig));
2215 printsiginfo(&si, verbose(tcp));
2216 tprintf(PC_FORMAT_STR " ---\n"
2219 tprintf("--- stopped by %s" PC_FORMAT_STR " ---\n",
2226 /* It's signal-delivery-stop. Inject the signal */
2227 goto restart_tracee;
2229 /* It's group-stop */
2233 * This ends ptrace-stop, but does *not* end group-stop.
2234 * This makes stopping signals work properly on straced process
2235 * (that is, process really stops. It used to continue to run).
2237 if (ptrace_restart(PTRACE_LISTEN, tcp, 0) < 0) {
2243 /* We don't have PTRACE_LISTEN support... */
2245 goto restart_tracee;
2248 /* We handled quick cases, we are permitted to interrupt now. */
2252 /* This should be syscall entry or exit.
2253 * (Or it still can be that pesky post-execve SIGTRAP!)
2256 if (trace_syscall(tcp) < 0) {
2257 /* ptrace() failed in trace_syscall().
2258 * Likely a result of process disappearing mid-flight.
2259 * Observed case: exit_group() or SIGKILL terminating
2260 * all processes in thread group.
2261 * We assume that ptrace error was caused by process death.
2262 * We used to detach(tcp) here, but since we no longer
2263 * implement "detach before death" policy/hack,
2264 * we can let this process to report its death to us
2265 * normally, via WIFEXITED or WIFSIGNALED wait status.
2269 restart_tracee_with_sig_0:
2272 if (ptrace_restart(PTRACE_SYSCALL, tcp, sig) < 0) {
2281 main(int argc, char *argv[])
2285 /* Run main tracing loop */
2291 if (shared_log != stderr)
2294 while (waitpid(popen_pid, NULL, 0) < 0 && errno == EINTR)
2297 if (exit_code > 0xff) {
2298 /* Avoid potential core file clobbering. */
2299 struct rlimit rlim = {0, 0};
2300 setrlimit(RLIMIT_CORE, &rlim);
2302 /* Child was killed by a signal, mimic that. */
2304 signal(exit_code, SIG_DFL);
2306 /* Paranoia - what if this signal is not fatal?
2307 Exit with 128 + signo then. */