2 * Copyright (c) 1991, 1992 Paul Kranenburg <pk@cs.few.eur.nl>
3 * Copyright (c) 1993 Branko Lankester <branko@hacktic.nl>
4 * Copyright (c) 1993, 1994, 1995, 1996 Rick Sladkey <jrs@world.std.com>
5 * Copyright (c) 1996-1999 Wichert Akkerman <wichert@cistron.nl>
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. The name of the author may not be used to endorse or promote products
17 * derived from this software without specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 #include <sys/param.h>
35 #include <sys/resource.h>
41 #include <sys/utsname.h>
43 # include <sys/prctl.h>
46 # include <asm/ptrace_offsets.h>
48 /* In some libc, these aren't declared. Do it ourself: */
49 extern char **environ;
54 /* if this is true do the stack trace for every system call */
55 bool stack_trace_enabled = false;
58 #if defined __NR_tkill
59 # define my_tkill(tid, sig) syscall(__NR_tkill, (tid), (sig))
61 /* kill() may choose arbitrarily the target task of the process group
62 while we later wait on a that specific TID. PID process waits become
63 TID task specific waits for a process under ptrace(2). */
64 # warning "tkill(2) not available, risk of strace hangs!"
65 # define my_tkill(tid, sig) kill((tid), (sig))
68 /* Glue for systems without a MMU that cannot provide fork() */
69 #if !defined(HAVE_FORK)
71 # define NOMMU_SYSTEM 1
74 # define fork() vfork()
77 cflag_t cflag = CFLAG_NONE;
78 unsigned int followfork = 0;
79 unsigned int ptrace_setoptions = 0;
80 unsigned int xflag = 0;
81 bool need_fork_exec_workarounds = 0;
85 bool count_wallclock = 0;
86 unsigned int qflag = 0;
87 /* Which WSTOPSIG(status) value marks syscall traps? */
88 static unsigned int syscall_trap_sig = SIGTRAP;
89 static unsigned int tflag = 0;
90 static bool rflag = 0;
91 static bool print_pid_pfx = 0;
96 INTR_ANYWHERE = 1, /* don't block/ignore any signals */
97 INTR_WHILE_WAIT = 2, /* block fatal signals while decoding syscall. default */
98 INTR_NEVER = 3, /* block fatal signals. default if '-o FILE PROG' */
99 INTR_BLOCK_TSTP_TOO = 4, /* block fatal signals and SIGTSTP (^Z) */
103 /* We play with signal mask only if this mode is active: */
104 #define interactive (opt_intr == INTR_WHILE_WAIT)
107 * daemonized_tracer supports -D option.
108 * With this option, strace forks twice.
109 * Unlike normal case, with -D *grandparent* process exec's,
110 * becoming a traced process. Child exits (this prevents traced process
111 * from having children it doesn't expect to have), and grandchild
112 * attaches to grandparent similarly to strace -p PID.
113 * This allows for more transparent interaction in cases
114 * when process and its parent are communicating via signals,
115 * wait() etc. Without -D, strace process gets lodged in between,
116 * disrupting parent<->child link.
118 static bool daemonized_tracer = 0;
121 static int post_attach_sigstop = TCB_IGNORE_ONE_SIGSTOP;
122 # define use_seize (post_attach_sigstop == 0)
124 # define post_attach_sigstop TCB_IGNORE_ONE_SIGSTOP
128 /* Sometimes we want to print only succeeding syscalls. */
129 bool not_failing_only = 0;
131 /* Show path associated with fd arguments */
132 unsigned int show_fd_path = 0;
134 static bool detach_on_execve = 0;
135 /* Are we "strace PROG" and need to skip detach on first execve? */
136 static bool skip_one_b_execve = 0;
137 /* Are we "strace PROG" and need to hide everything until execve? */
138 bool hide_log_until_execve = 0;
140 static int exit_code = 0;
141 static int strace_child = 0;
142 static int strace_tracer_pid = 0;
144 static char *username = NULL;
145 static uid_t run_uid;
146 static gid_t run_gid;
148 unsigned int max_strlen = DEFAULT_STRLEN;
149 static int acolumn = DEFAULT_ACOLUMN;
150 static char *acolumn_spaces;
152 static char *outfname = NULL;
153 /* If -ff, points to stderr. Else, it's our common output log */
154 static FILE *shared_log;
156 struct tcb *printing_tcp = NULL;
157 static struct tcb *current_tcp;
159 static struct tcb **tcbtab;
160 static unsigned int nprocs, tcbtabsize;
161 static const char *progname;
163 unsigned os_release; /* generated from uname()'s u.release */
165 static void detach(struct tcb *tcp);
166 static void cleanup(void);
167 static void interrupt(int sig);
168 static sigset_t empty_set, blocked_set;
170 #ifdef HAVE_SIG_ATOMIC_T
171 static volatile sig_atomic_t interrupted;
173 static volatile int interrupted;
176 #ifndef HAVE_STRERROR
178 #if !HAVE_DECL_SYS_ERRLIST
180 extern char *sys_errlist[];
186 static char buf[sizeof("Unknown error %d") + sizeof(int)*3];
188 if (err_no < 1 || err_no >= sys_nerr) {
189 sprintf(buf, "Unknown error %d", err_no);
192 return sys_errlist[err_no];
195 #endif /* HAVE_STERRROR */
198 usage(FILE *ofp, int exitval)
201 usage: strace [-CdffhiqrtttTvVxxy] [-I n] [-e expr]...\n\
202 [-a column] [-o file] [-s strsize] [-P path]...\n\
203 -p pid... / [-D] [-E var=val]... [-u username] PROG [ARGS]\n\
204 or: strace -c[df] [-I n] [-e expr]... [-O overhead] [-S sortby]\n\
205 -p pid... / [-D] [-E var=val]... [-u username] PROG [ARGS]\n\
206 -c -- count time, calls, and errors for each syscall and report summary\n\
207 -C -- like -c but also print regular output\n\
208 -w -- summarise syscall latency (default is system time)\n\
209 -d -- enable debug output to stderr\n\
210 -D -- run tracer process as a detached grandchild, not as parent\n\
211 -f -- follow forks, -ff -- with output into separate files\n\
212 -i -- print instruction pointer at time of syscall\n\
213 -q -- suppress messages about attaching, detaching, etc.\n\
214 -r -- print relative timestamp, -t -- absolute timestamp, -tt -- with usecs\n\
215 -T -- print time spent in each syscall\n\
216 -v -- verbose mode: print unabbreviated argv, stat, termios, etc. args\n\
217 -x -- print non-ascii strings in hex, -xx -- print all strings in hex\n\
218 -y -- print paths associated with file descriptor arguments\n\
219 -yy -- print ip:port pairs associated with socket file descriptors\n\
220 -h -- print help message, -V -- print version\n\
221 -a column -- alignment COLUMN for printing syscall results (default %d)\n\
222 -b execve -- detach on this syscall\n\
223 -e expr -- a qualifying expression: option=[!]all or option=[!]val1[,val2]...\n\
224 options: trace, abbrev, verbose, raw, signal, read, write\n\
225 -I interruptible --\n\
226 1: no signals are blocked\n\
227 2: fatal signals are blocked while decoding syscall (default)\n\
228 3: fatal signals are always blocked (default if '-o FILE PROG')\n\
229 4: fatal signals and SIGTSTP (^Z) are always blocked\n\
230 (useful to make 'strace -o FILE PROG' not stop on ^Z)\n\
231 -o file -- send trace output to FILE instead of stderr\n\
232 -O overhead -- set overhead for tracing syscalls to OVERHEAD usecs\n\
233 -p pid -- trace process with process id PID, may be repeated\n\
234 -s strsize -- limit length of print strings to STRSIZE chars (default %d)\n\
235 -S sortby -- sort syscall counts by: time, calls, name, nothing (default %s)\n\
236 -u username -- run command as username handling setuid and/or setgid\n\
237 -E var=val -- put var=val in the environment for command\n\
238 -E var -- remove var from the environment for command\n\
239 -P path -- trace accesses to path\n\
242 "-k obtain stack trace between each syscall (experimental)\n\
245 /* ancient, no one should use it
246 -F -- attempt to follow vforks (deprecated, use -f)\n\
248 /* this is broken, so don't document it
249 -z -- print only succeeding syscalls\n\
251 , DEFAULT_ACOLUMN, DEFAULT_STRLEN, DEFAULT_SORTBY);
255 static void die(void) __attribute__ ((noreturn));
256 static void die(void)
258 if (strace_tracer_pid == getpid()) {
265 static void verror_msg(int err_no, const char *fmt, va_list p)
271 /* We want to print entire message with single fprintf to ensure
272 * message integrity if stderr is shared with other programs.
273 * Thus we use vasprintf + single fprintf.
276 if (vasprintf(&msg, fmt, p) >= 0) {
278 fprintf(stderr, "%s: %s: %s\n", progname, msg, strerror(err_no));
280 fprintf(stderr, "%s: %s\n", progname, msg);
283 /* malloc in vasprintf failed, try it without malloc */
284 fprintf(stderr, "%s: ", progname);
285 vfprintf(stderr, fmt, p);
287 fprintf(stderr, ": %s\n", strerror(err_no));
291 /* We don't switch stderr to buffered, thus fprintf(stderr)
292 * always flushes its output and this is not necessary: */
293 /* fflush(stderr); */
296 void error_msg(const char *fmt, ...)
300 verror_msg(0, fmt, p);
304 void error_msg_and_die(const char *fmt, ...)
308 verror_msg(0, fmt, p);
312 void perror_msg(const char *fmt, ...)
316 verror_msg(errno, fmt, p);
320 void perror_msg_and_die(const char *fmt, ...)
324 verror_msg(errno, fmt, p);
328 void die_out_of_memory(void)
330 static bool recursed = 0;
334 error_msg_and_die("Out of memory");
338 error_opt_arg(int opt, const char *arg)
340 error_msg_and_die("Invalid -%c argument: '%s'", opt, arg);
345 ptrace_attach_or_seize(int pid)
349 return ptrace(PTRACE_ATTACH, pid, 0L, 0L);
350 r = ptrace(PTRACE_SEIZE, pid, 0L, (unsigned long)ptrace_setoptions);
353 r = ptrace(PTRACE_INTERRUPT, pid, 0L, 0L);
357 # define ptrace_attach_or_seize(pid) ptrace(PTRACE_ATTACH, (pid), 0, 0)
361 * Used when we want to unblock stopped traced process.
362 * Should be only used with PTRACE_CONT, PTRACE_DETACH and PTRACE_SYSCALL.
363 * Returns 0 on success or if error was ESRCH
364 * (presumably process was killed while we talk to it).
365 * Otherwise prints error message and returns -1.
368 ptrace_restart(int op, struct tcb *tcp, int sig)
374 ptrace(op, tcp->pid, (void *) 0, (long) sig);
380 if (op == PTRACE_CONT)
382 if (op == PTRACE_DETACH)
385 if (op == PTRACE_LISTEN)
389 * Why curcol != 0? Otherwise sometimes we get this:
391 * 10252 kill(10253, SIGKILL) = 0
392 * <ptrace(SYSCALL,10252):No such process>10253 ...next decode...
394 * 10252 died after we retrieved syscall exit data,
395 * but before we tried to restart it. Log looks ugly.
397 if (current_tcp && current_tcp->curcol != 0) {
398 tprintf(" <ptrace(%s):%s>\n", msg, strerror(err));
404 perror_msg("ptrace(PTRACE_%s,pid:%d,sig:%d)", msg, tcp->pid, sig);
409 set_cloexec_flag(int fd)
413 flags = fcntl(fd, F_GETFD);
415 /* Can happen only if fd is bad.
416 * Should never happen: if it does, we have a bug
417 * in the caller. Therefore we just abort
418 * instead of propagating the error.
420 perror_msg_and_die("fcntl(%d, F_GETFD)", fd);
423 newflags = flags | FD_CLOEXEC;
424 if (flags == newflags)
427 fcntl(fd, F_SETFD, newflags); /* never fails */
430 static void kill_save_errno(pid_t pid, int sig)
432 int saved_errno = errno;
434 (void) kill(pid, sig);
439 * When strace is setuid executable, we have to swap uids
440 * before and after filesystem and process management operations.
445 int euid = geteuid(), uid = getuid();
447 if (euid != uid && setreuid(euid, uid) < 0) {
448 perror_msg_and_die("setreuid");
452 #ifdef _LARGEFILE64_SOURCE
454 # define fopen_for_output fopen64
456 # define fopen_for_output fopen
458 # define struct_stat struct stat64
459 # define stat_file stat64
460 # define struct_dirent struct dirent64
461 # define read_dir readdir64
462 # define struct_rlimit struct rlimit64
463 # define set_rlimit setrlimit64
465 # define fopen_for_output fopen
466 # define struct_stat struct stat
467 # define stat_file stat
468 # define struct_dirent struct dirent
469 # define read_dir readdir
470 # define struct_rlimit struct rlimit
471 # define set_rlimit setrlimit
475 strace_fopen(const char *path)
480 fp = fopen_for_output(path, "w");
482 perror_msg_and_die("Can't fopen '%s'", path);
484 set_cloexec_flag(fileno(fp));
488 static int popen_pid = 0;
491 # define _PATH_BSHELL "/bin/sh"
495 * We cannot use standard popen(3) here because we have to distinguish
496 * popen child process from other processes we trace, and standard popen(3)
497 * does not export its child's pid.
500 strace_popen(const char *command)
508 perror_msg_and_die("pipe");
510 set_cloexec_flag(fds[1]); /* never fails */
514 perror_msg_and_die("vfork");
521 perror_msg_and_die("dup2");
524 execl(_PATH_BSHELL, "sh", "-c", command, NULL);
525 perror_msg_and_die("Can't execute '%s'", _PATH_BSHELL);
532 fp = fdopen(fds[1], "w");
539 tprintf(const char *fmt, ...)
545 int n = strace_vfprintf(current_tcp->outf, fmt, args);
547 if (current_tcp->outf != stderr)
548 perror_msg("%s", outfname);
550 current_tcp->curcol += n;
555 #ifndef HAVE_FPUTS_UNLOCKED
556 # define fputs_unlocked fputs
560 tprints(const char *str)
563 int n = fputs_unlocked(str, current_tcp->outf);
565 current_tcp->curcol += strlen(str);
568 if (current_tcp->outf != stderr)
569 perror_msg("%s", outfname);
577 current_tcp->curcol = 0;
578 fflush(current_tcp->outf);
581 printing_tcp->curcol = 0;
587 printleader(struct tcb *tcp)
589 /* If -ff, "previous tcb we printed" is always the same as current,
590 * because we have per-tcb output files.
596 current_tcp = printing_tcp;
597 if (printing_tcp->curcol != 0 && (followfork < 2 || printing_tcp == tcp)) {
599 * case 1: we have a shared log (i.e. not -ff), and last line
600 * wasn't finished (same or different tcb, doesn't matter).
601 * case 2: split log, we are the same tcb, but our last line
602 * didn't finish ("SIGKILL nuked us after syscall entry" etc).
604 tprints(" <unfinished ...>\n");
605 printing_tcp->curcol = 0;
611 current_tcp->curcol = 0;
614 tprintf("%-5d ", tcp->pid);
615 else if (nprocs > 1 && !outfname)
616 tprintf("[pid %5u] ", tcp->pid);
619 char str[sizeof("HH:MM:SS")];
620 struct timeval tv, dtv;
621 static struct timeval otv;
623 gettimeofday(&tv, NULL);
627 tv_sub(&dtv, &tv, &otv);
628 tprintf("%6ld.%06ld ",
629 (long) dtv.tv_sec, (long) dtv.tv_usec);
632 else if (tflag > 2) {
633 tprintf("%ld.%06ld ",
634 (long) tv.tv_sec, (long) tv.tv_usec);
637 time_t local = tv.tv_sec;
638 strftime(str, sizeof(str), "%T", localtime(&local));
640 tprintf("%s.%06ld ", str, (long) tv.tv_usec);
652 if (current_tcp->curcol < acolumn)
653 tprints(acolumn_spaces + current_tcp->curcol);
656 /* Should be only called directly *after successful attach* to a tracee.
657 * Otherwise, "strace -oFILE -ff -p<nonexistant_pid>"
658 * may create bogus empty FILE.<nonexistant_pid>, and then die.
661 newoutf(struct tcb *tcp)
663 tcp->outf = shared_log; /* if not -ff mode, the same file is for all */
664 if (followfork >= 2) {
665 char name[520 + sizeof(int) * 3];
666 sprintf(name, "%.512s.%u", outfname, tcp->pid);
667 tcp->outf = strace_fopen(name);
674 /* Allocate some more TCBs and expand the table.
675 We don't want to relocate the TCBs because our
676 callers have pointers and it would be a pain.
677 So tcbtab is a table of pointers. Since we never
678 free the TCBs, we allocate a single chunk of many. */
679 unsigned int i = tcbtabsize;
680 struct tcb *newtcbs = calloc(tcbtabsize, sizeof(newtcbs[0]));
681 struct tcb **newtab = realloc(tcbtab, tcbtabsize * 2 * sizeof(tcbtab[0]));
682 if (!newtab || !newtcbs)
686 while (i < tcbtabsize)
687 tcbtab[i++] = newtcbs++;
696 if (nprocs == tcbtabsize)
699 for (i = 0; i < tcbtabsize; i++) {
702 memset(tcp, 0, sizeof(*tcp));
704 #if SUPPORTED_PERSONALITIES > 1
705 tcp->currpers = current_personality;
709 if (stack_trace_enabled)
710 unwind_tcb_init(tcp);
715 fprintf(stderr, "new tcb for pid %d, active tcbs:%d\n", tcp->pid, nprocs);
719 error_msg_and_die("bug in alloctcb");
723 droptcb(struct tcb *tcp)
729 if (stack_trace_enabled) {
736 fprintf(stderr, "dropped tcb for pid %d, %d remain\n", tcp->pid, nprocs);
739 if (followfork >= 2) {
740 if (tcp->curcol != 0)
741 fprintf(tcp->outf, " <detached ...>\n");
744 if (printing_tcp == tcp && tcp->curcol != 0)
745 fprintf(tcp->outf, " <detached ...>\n");
750 if (current_tcp == tcp)
752 if (printing_tcp == tcp)
755 memset(tcp, 0, sizeof(*tcp));
758 /* Detach traced process.
759 * Never call DETACH twice on the same process as both unattached and
760 * attached-unstopped processes give the same ESRCH. For unattached process we
761 * would SIGSTOP it and wait for its SIGSTOP notification forever.
764 detach(struct tcb *tcp)
769 if (tcp->flags & TCB_BPTSET)
773 * Linux wrongly insists the child be stopped
774 * before detaching. Arghh. We go through hoops
775 * to make a clean break of things.
778 # undef PTRACE_DETACH
779 # define PTRACE_DETACH PTRACE_SUNDETACH
782 if (!(tcp->flags & TCB_ATTACHED))
785 /* We attached but possibly didn't see the expected SIGSTOP.
786 * We must catch exactly one as otherwise the detached process
787 * would be left stopped (process state T).
789 if (tcp->flags & TCB_IGNORE_ONE_SIGSTOP)
792 error = ptrace(PTRACE_DETACH, tcp->pid, 0, 0);
794 /* On a clear day, you can see forever. */
797 if (errno != ESRCH) {
798 /* Shouldn't happen. */
799 perror_msg("detach: ptrace(PTRACE_DETACH,%u)", tcp->pid);
802 /* ESRCH: process is either not stopped or doesn't exist. */
803 if (my_tkill(tcp->pid, 0) < 0) {
805 /* Shouldn't happen. */
806 perror_msg("detach: tkill(%u,0)", tcp->pid);
807 /* else: process doesn't exist. */
810 /* Process is not stopped, need to stop it. */
813 * With SEIZE, tracee can be in group-stop already.
814 * In this state sending it another SIGSTOP does nothing.
815 * Need to use INTERRUPT.
816 * Testcase: trying to ^C a "strace -p <stopped_process>".
818 error = ptrace(PTRACE_INTERRUPT, tcp->pid, 0, 0);
822 perror_msg("detach: ptrace(PTRACE_INTERRUPT,%u)", tcp->pid);
825 error = my_tkill(tcp->pid, SIGSTOP);
829 perror_msg("detach: tkill(%u,SIGSTOP)", tcp->pid);
831 /* Either process doesn't exist, or some weird error. */
835 /* We end up here in three cases:
836 * 1. We sent PTRACE_INTERRUPT (use_seize case)
837 * 2. We sent SIGSTOP (!use_seize)
838 * 3. Attach SIGSTOP was already pending (TCB_IGNORE_ONE_SIGSTOP set)
842 if (waitpid(tcp->pid, &status, __WALL) < 0) {
846 * if (errno == ECHILD) break;
847 * ^^^ WRONG! We expect this PID to exist,
848 * and want to emit a message otherwise:
850 perror_msg("detach: waitpid(%u)", tcp->pid);
853 if (!WIFSTOPPED(status)) {
855 * Tracee exited or was killed by signal.
856 * We shouldn't normally reach this place:
857 * we don't want to consume exit status.
858 * Consider "strace -p PID" being ^C-ed:
859 * we want merely to detach from PID.
861 * However, we _can_ end up here if tracee
866 sig = WSTOPSIG(status);
868 fprintf(stderr, "detach wait: event:%d sig:%d\n",
869 (unsigned)status >> 16, sig);
871 unsigned event = (unsigned)status >> 16;
872 if (event == PTRACE_EVENT_STOP /*&& sig == SIGTRAP*/) {
874 * sig == SIGTRAP: PTRACE_INTERRUPT stop.
875 * sig == other: process was already stopped
876 * with this stopping sig (see tests/detach-stopped).
877 * Looks like re-injecting this sig is not necessary
878 * in DETACH for the tracee to remain stopped.
883 * PTRACE_INTERRUPT is not guaranteed to produce
884 * the above event if other ptrace-stop is pending.
885 * See tests/detach-sleeping testcase:
886 * strace got SIGINT while tracee is sleeping.
887 * We sent PTRACE_INTERRUPT.
888 * We see syscall exit, not PTRACE_INTERRUPT stop.
889 * We won't get PTRACE_INTERRUPT stop
890 * if we would CONT now. Need to DETACH.
892 if (sig == syscall_trap_sig)
894 /* else: not sure in which case we can be here.
895 * Signal stop? Inject it while detaching.
897 ptrace_restart(PTRACE_DETACH, tcp, sig);
900 /* Note: this check has to be after use_seize check */
901 /* (else, in use_seize case SIGSTOP will be mistreated) */
902 if (sig == SIGSTOP) {
903 /* Detach, suppressing SIGSTOP */
904 ptrace_restart(PTRACE_DETACH, tcp, 0);
907 if (sig == syscall_trap_sig)
909 /* Can't detach just yet, may need to wait for SIGSTOP */
910 error = ptrace_restart(PTRACE_CONT, tcp, sig);
912 /* Should not happen.
913 * Note: ptrace_restart returns 0 on ESRCH, so it's not it.
914 * ptrace_restart already emitted error message.
921 if (!qflag && (tcp->flags & TCB_ATTACHED))
922 fprintf(stderr, "Process %u detached\n", tcp->pid);
928 process_opt_p_list(char *opt)
932 * We accept -p PID,PID; -p "`pidof PROG`"; -p "`pgrep PROG`".
933 * pidof uses space as delim, pgrep uses newline. :(
936 char *delim = opt + strcspn(opt, ", \n\t");
940 pid = string_to_uint(opt);
942 error_msg_and_die("Invalid process id: '%s'", opt);
944 if (pid == strace_tracer_pid) {
945 error_msg_and_die("I'm sorry, I can't let you do that, Dave.");
962 * Block user interruptions as we would leave the traced
963 * process stopped (process state T) if we would terminate in
964 * between PTRACE_ATTACH and wait4() on SIGSTOP.
965 * We rely on cleanup() from this point on.
968 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
970 if (daemonized_tracer) {
973 perror_msg_and_die("fork");
975 if (pid) { /* parent */
977 * Wait for grandchild to attach to straced process
978 * (grandparent). Grandchild SIGKILLs us after it attached.
979 * Grandparent's wait() is unblocked by our death,
980 * it proceeds to exec the straced program.
983 _exit(0); /* paranoia */
986 /* We will be the tracer process. Remember our new pid: */
987 strace_tracer_pid = getpid();
990 for (tcbi = 0; tcbi < tcbtabsize; tcbi++) {
996 /* Is this a process we should attach to, but not yet attached? */
997 if (tcp->flags & TCB_ATTACHED)
998 continue; /* no, we already attached it */
1000 if (followfork && !daemonized_tracer) {
1001 char procdir[sizeof("/proc/%d/task") + sizeof(int) * 3];
1004 sprintf(procdir, "/proc/%d/task", tcp->pid);
1005 dir = opendir(procdir);
1007 unsigned int ntid = 0, nerr = 0;
1010 while ((de = read_dir(dir)) != NULL) {
1011 struct tcb *cur_tcp;
1014 if (de->d_fileno == 0)
1016 /* we trust /proc filesystem */
1017 tid = atoi(de->d_name);
1021 if (ptrace_attach_or_seize(tid) < 0) {
1024 fprintf(stderr, "attach to pid %d failed\n", tid);
1028 fprintf(stderr, "attach to pid %d succeeded\n", tid);
1030 if (tid != tcp->pid)
1031 cur_tcp = alloctcb(tid);
1032 cur_tcp->flags |= TCB_ATTACHED | TCB_STARTUP | post_attach_sigstop;
1037 sigprocmask(SIG_SETMASK, &empty_set, NULL);
1040 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
1044 perror_msg("attach: ptrace(PTRACE_ATTACH, ...)");
1049 fprintf(stderr, ntid > 1
1050 ? "Process %u attached with %u threads\n"
1051 : "Process %u attached\n",
1054 if (!(tcp->flags & TCB_ATTACHED)) {
1055 /* -p PID, we failed to attach to PID itself
1056 * but did attach to some of its sibling threads.
1062 } /* if (opendir worked) */
1064 if (ptrace_attach_or_seize(tcp->pid) < 0) {
1065 perror_msg("attach: ptrace(PTRACE_ATTACH, ...)");
1069 tcp->flags |= TCB_ATTACHED | TCB_STARTUP | post_attach_sigstop;
1072 fprintf(stderr, "attach to pid %d (main) succeeded\n", tcp->pid);
1074 if (daemonized_tracer) {
1076 * Make parent go away.
1077 * Also makes grandparent's wait() unblock.
1079 kill(getppid(), SIGKILL);
1084 "Process %u attached\n",
1086 } /* for each tcbtab[] */
1090 sigprocmask(SIG_SETMASK, &empty_set, NULL);
1093 /* Stack-o-phobic exec helper, in the hope to work around
1094 * NOMMU + "daemonized tracer" difficulty.
1096 struct exec_params {
1103 static struct exec_params params_for_tracee;
1104 static void __attribute__ ((noinline, noreturn))
1107 struct exec_params *params = ¶ms_for_tracee;
1109 if (params->fd_to_close >= 0)
1110 close(params->fd_to_close);
1111 if (!daemonized_tracer && !use_seize) {
1112 if (ptrace(PTRACE_TRACEME, 0L, 0L, 0L) < 0) {
1113 perror_msg_and_die("ptrace(PTRACE_TRACEME, ...)");
1117 if (username != NULL) {
1119 * It is important to set groups before we
1120 * lose privileges on setuid.
1122 if (initgroups(username, run_gid) < 0) {
1123 perror_msg_and_die("initgroups");
1125 if (setregid(run_gid, params->run_egid) < 0) {
1126 perror_msg_and_die("setregid");
1128 if (setreuid(run_uid, params->run_euid) < 0) {
1129 perror_msg_and_die("setreuid");
1132 else if (geteuid() != 0)
1133 if (setreuid(run_uid, run_uid) < 0) {
1134 perror_msg_and_die("setreuid");
1137 if (!daemonized_tracer) {
1139 * Induce a ptrace stop. Tracer (our parent)
1140 * will resume us with PTRACE_SYSCALL and display
1141 * the immediately following execve syscall.
1142 * Can't do this on NOMMU systems, we are after
1143 * vfork: parent is blocked, stopping would deadlock.
1146 kill(getpid(), SIGSTOP);
1149 /* we depend on SIGCHLD set to SIG_DFL by init code */
1150 /* if it happens to be SIG_IGN'ed, wait won't block */
1155 execv(params->pathname, params->argv);
1156 perror_msg_and_die("exec");
1160 startup_child(char **argv)
1162 struct_stat statbuf;
1163 const char *filename;
1164 char pathname[PATH_MAX];
1169 if (strchr(filename, '/')) {
1170 if (strlen(filename) > sizeof pathname - 1) {
1171 errno = ENAMETOOLONG;
1172 perror_msg_and_die("exec");
1174 strcpy(pathname, filename);
1176 #ifdef USE_DEBUGGING_EXEC
1178 * Debuggers customarily check the current directory
1179 * first regardless of the path but doing that gives
1180 * security geeks a panic attack.
1182 else if (stat_file(filename, &statbuf) == 0)
1183 strcpy(pathname, filename);
1184 #endif /* USE_DEBUGGING_EXEC */
1189 for (path = getenv("PATH"); path && *path; path += m) {
1190 const char *colon = strchr(path, ':');
1196 m = n = strlen(path);
1198 if (!getcwd(pathname, PATH_MAX))
1200 len = strlen(pathname);
1202 else if (n > sizeof pathname - 1)
1205 strncpy(pathname, path, n);
1208 if (len && pathname[len - 1] != '/')
1209 pathname[len++] = '/';
1210 strcpy(pathname + len, filename);
1211 if (stat_file(pathname, &statbuf) == 0 &&
1212 /* Accept only regular files
1213 with some execute bits set.
1214 XXX not perfect, might still fail */
1215 S_ISREG(statbuf.st_mode) &&
1216 (statbuf.st_mode & 0111))
1220 if (stat_file(pathname, &statbuf) < 0) {
1221 perror_msg_and_die("Can't stat '%s'", filename);
1224 params_for_tracee.fd_to_close = (shared_log != stderr) ? fileno(shared_log) : -1;
1225 params_for_tracee.run_euid = (statbuf.st_mode & S_ISUID) ? statbuf.st_uid : run_uid;
1226 params_for_tracee.run_egid = (statbuf.st_mode & S_ISGID) ? statbuf.st_gid : run_gid;
1227 params_for_tracee.argv = argv;
1229 * On NOMMU, can be safely freed only after execve in tracee.
1230 * It's hard to know when that happens, so we just leak it.
1232 params_for_tracee.pathname = NOMMU_SYSTEM ? strdup(pathname) : pathname;
1234 #if defined HAVE_PRCTL && defined PR_SET_PTRACER && defined PR_SET_PTRACER_ANY
1235 if (daemonized_tracer)
1236 prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY);
1241 perror_msg_and_die("fork");
1243 if ((pid != 0 && daemonized_tracer)
1244 || (pid == 0 && !daemonized_tracer)
1246 /* We are to become the tracee. Two cases:
1248 * not -D: we are child
1253 /* We are the tracer */
1255 if (!daemonized_tracer) {
1258 /* child did PTRACE_TRACEME, nothing to do in parent */
1260 if (!NOMMU_SYSTEM) {
1261 /* Wait until child stopped itself */
1263 while (waitpid(pid, &status, WSTOPPED) < 0) {
1266 perror_msg_and_die("waitpid");
1268 if (!WIFSTOPPED(status) || WSTOPSIG(status) != SIGSTOP) {
1269 kill_save_errno(pid, SIGKILL);
1270 perror_msg_and_die("Unexpected wait status %x", status);
1273 /* Else: NOMMU case, we have no way to sync.
1274 * Just attach to it as soon as possible.
1275 * This means that we may miss a few first syscalls...
1278 if (ptrace_attach_or_seize(pid)) {
1279 kill_save_errno(pid, SIGKILL);
1280 perror_msg_and_die("Can't attach to %d", pid);
1285 tcp = alloctcb(pid);
1287 tcp->flags |= TCB_ATTACHED | TCB_STARTUP | post_attach_sigstop;
1289 tcp->flags |= TCB_ATTACHED | TCB_STARTUP;
1293 /* With -D, we are *child* here, IOW: different pid. Fetch it: */
1294 strace_tracer_pid = getpid();
1295 /* The tracee is our parent: */
1298 /* attaching will be done later, by startup_attach */
1299 /* note: we don't do newoutf(tcp) here either! */
1301 /* NOMMU BUG! -D mode is active, we (child) return,
1302 * and we will scribble over parent's stack!
1303 * When parent later unpauses, it segfaults.
1306 * (1) by declaring exec_or_die() NORETURN,
1307 * hopefully compiler will just jump to it
1308 * instead of call (won't push anything to stack),
1309 * (2) by trying very hard in exec_or_die()
1310 * to not use any stack,
1311 * (3) having a really big (PATH_MAX) stack object
1312 * in this function, which creates a "buffer" between
1313 * child's and parent's stack pointers.
1314 * This may save us if (1) and (2) failed
1315 * and compiler decided to use stack in exec_or_die() anyway
1316 * (happens on i386 because of stack parameter passing).
1318 * A cleaner solution is to use makecontext + setcontext
1319 * to create a genuine separate stack and execute on it.
1325 * Test whether the kernel support PTRACE_O_TRACECLONE et al options.
1326 * First fork a new child, call ptrace with PTRACE_SETOPTIONS on it,
1327 * and then see which options are supported by the kernel.
1330 test_ptrace_setoptions_followfork(void)
1332 int pid, expected_grandchild = 0, found_grandchild = 0;
1333 const unsigned int test_options = PTRACE_O_TRACECLONE |
1334 PTRACE_O_TRACEFORK |
1335 PTRACE_O_TRACEVFORK;
1337 /* Need fork for test. NOMMU has no forks */
1339 goto worked; /* be bold, and pretend that test succeeded */
1343 perror_msg_and_die("fork");
1346 if (ptrace(PTRACE_TRACEME, 0L, 0L, 0L) < 0)
1347 perror_msg_and_die("%s: PTRACE_TRACEME doesn't work",
1349 kill_save_errno(pid, SIGSTOP);
1351 perror_msg_and_die("fork");
1356 int status, tracee_pid;
1359 tracee_pid = wait(&status);
1360 if (tracee_pid <= 0) {
1363 if (errno == ECHILD)
1365 kill_save_errno(pid, SIGKILL);
1366 perror_msg_and_die("%s: unexpected wait result %d",
1367 __func__, tracee_pid);
1369 if (WIFEXITED(status)) {
1370 if (WEXITSTATUS(status)) {
1371 if (tracee_pid != pid)
1372 kill_save_errno(pid, SIGKILL);
1373 error_msg_and_die("%s: unexpected exit status %u",
1374 __func__, WEXITSTATUS(status));
1378 if (WIFSIGNALED(status)) {
1379 if (tracee_pid != pid)
1380 kill_save_errno(pid, SIGKILL);
1381 error_msg_and_die("%s: unexpected signal %u",
1382 __func__, WTERMSIG(status));
1384 if (!WIFSTOPPED(status)) {
1385 if (tracee_pid != pid)
1386 kill_save_errno(tracee_pid, SIGKILL);
1387 kill_save_errno(pid, SIGKILL);
1388 error_msg_and_die("%s: unexpected wait status %x",
1391 if (tracee_pid != pid) {
1392 found_grandchild = tracee_pid;
1393 if (ptrace(PTRACE_CONT, tracee_pid, 0, 0) < 0) {
1394 kill_save_errno(tracee_pid, SIGKILL);
1395 kill_save_errno(pid, SIGKILL);
1396 perror_msg_and_die("PTRACE_CONT doesn't work");
1400 switch (WSTOPSIG(status)) {
1402 if (ptrace(PTRACE_SETOPTIONS, pid, 0, test_options) < 0
1403 && errno != EINVAL && errno != EIO)
1404 perror_msg("PTRACE_SETOPTIONS");
1407 if (status >> 16 == PTRACE_EVENT_FORK) {
1410 if (ptrace(PTRACE_GETEVENTMSG, pid,
1411 NULL, (long) &msg) == 0)
1412 expected_grandchild = msg;
1416 if (ptrace(PTRACE_SYSCALL, pid, 0, 0) < 0) {
1417 kill_save_errno(pid, SIGKILL);
1418 perror_msg_and_die("PTRACE_SYSCALL doesn't work");
1421 if (expected_grandchild && expected_grandchild == found_grandchild) {
1423 ptrace_setoptions |= test_options;
1425 fprintf(stderr, "ptrace_setoptions = %#x\n",
1429 error_msg("Test for PTRACE_O_TRACECLONE failed, "
1430 "giving up using this feature.");
1435 * Test whether the kernel support PTRACE_O_TRACESYSGOOD.
1436 * First fork a new child, call ptrace(PTRACE_SETOPTIONS) on it,
1437 * and then see whether it will stop with (SIGTRAP | 0x80).
1439 * Use of this option enables correct handling of user-generated SIGTRAPs,
1440 * and SIGTRAPs generated by special instructions such as int3 on x86:
1442 # compile with: gcc -nostartfiles -nostdlib -o int3 int3.S
1443 _start: .globl _start
1450 test_ptrace_setoptions_for_all(void)
1452 const unsigned int test_options = PTRACE_O_TRACESYSGOOD |
1457 /* Need fork for test. NOMMU has no forks */
1459 goto worked; /* be bold, and pretend that test succeeded */
1463 perror_msg_and_die("fork");
1467 if (ptrace(PTRACE_TRACEME, 0L, 0L, 0L) < 0)
1468 /* Note: exits with exitcode 1 */
1469 perror_msg_and_die("%s: PTRACE_TRACEME doesn't work",
1472 _exit(0); /* parent should see entry into this syscall */
1476 int status, tracee_pid;
1479 tracee_pid = wait(&status);
1480 if (tracee_pid <= 0) {
1483 kill_save_errno(pid, SIGKILL);
1484 perror_msg_and_die("%s: unexpected wait result %d",
1485 __func__, tracee_pid);
1487 if (WIFEXITED(status)) {
1488 if (WEXITSTATUS(status) == 0)
1490 error_msg_and_die("%s: unexpected exit status %u",
1491 __func__, WEXITSTATUS(status));
1493 if (WIFSIGNALED(status)) {
1494 error_msg_and_die("%s: unexpected signal %u",
1495 __func__, WTERMSIG(status));
1497 if (!WIFSTOPPED(status)) {
1499 error_msg_and_die("%s: unexpected wait status %x",
1502 if (WSTOPSIG(status) == SIGSTOP) {
1504 * We don't check "options aren't accepted" error.
1505 * If it happens, we'll never get (SIGTRAP | 0x80),
1506 * and thus will decide to not use the option.
1507 * IOW: the outcome of the test will be correct.
1509 if (ptrace(PTRACE_SETOPTIONS, pid, 0L, test_options) < 0
1510 && errno != EINVAL && errno != EIO)
1511 perror_msg("PTRACE_SETOPTIONS");
1513 if (WSTOPSIG(status) == (SIGTRAP | 0x80)) {
1516 if (ptrace(PTRACE_SYSCALL, pid, 0L, 0L) < 0) {
1517 kill_save_errno(pid, SIGKILL);
1518 perror_msg_and_die("PTRACE_SYSCALL doesn't work");
1524 syscall_trap_sig = (SIGTRAP | 0x80);
1525 ptrace_setoptions |= test_options;
1527 fprintf(stderr, "ptrace_setoptions = %#x\n",
1532 error_msg("Test for PTRACE_O_TRACESYSGOOD failed, "
1533 "giving up using this feature.");
1539 test_ptrace_seize(void)
1543 /* Need fork for test. NOMMU has no forks */
1545 post_attach_sigstop = 0; /* this sets use_seize to 1 */
1551 perror_msg_and_die("fork");
1558 /* PTRACE_SEIZE, unlike ATTACH, doesn't force tracee to trap. After
1559 * attaching tracee continues to run unless a trap condition occurs.
1560 * PTRACE_SEIZE doesn't affect signal or group stop state.
1562 if (ptrace(PTRACE_SEIZE, pid, 0, 0) == 0) {
1563 post_attach_sigstop = 0; /* this sets use_seize to 1 */
1564 } else if (debug_flag) {
1565 fprintf(stderr, "PTRACE_SEIZE doesn't work\n");
1571 int status, tracee_pid;
1574 tracee_pid = waitpid(pid, &status, 0);
1575 if (tracee_pid <= 0) {
1578 perror_msg_and_die("%s: unexpected wait result %d",
1579 __func__, tracee_pid);
1581 if (WIFSIGNALED(status)) {
1584 error_msg_and_die("%s: unexpected wait status %x",
1588 #else /* !USE_SEIZE */
1589 # define test_ptrace_seize() ((void)0)
1593 get_os_release(void)
1599 perror_msg_and_die("uname");
1600 /* u.release has this form: "3.2.9[-some-garbage]" */
1604 if (!(*p >= '0' && *p <= '9'))
1605 error_msg_and_die("Bad OS release string: '%s'", u.release);
1606 /* Note: this open-codes KERNEL_VERSION(): */
1607 rel = (rel << 8) | atoi(p);
1608 if (rel >= KERNEL_VERSION(1,0,0))
1610 while (*p >= '0' && *p <= '9')
1613 if (rel >= KERNEL_VERSION(0,1,0)) {
1614 /* "X.Y-something" means "X.Y.0" */
1618 error_msg_and_die("Bad OS release string: '%s'", u.release);
1626 * Initialization part of main() was eating much stack (~0.5k),
1627 * which was unused after init.
1628 * We can reuse it if we move init code into a separate function.
1630 * Don't want main() to inline us and defeat the reason
1631 * we have a separate function.
1633 static void __attribute__ ((noinline))
1634 init(int argc, char *argv[])
1640 struct sigaction sa;
1642 progname = argv[0] ? argv[0] : "strace";
1644 /* Make sure SIGCHLD has the default action so that waitpid
1645 definitely works without losing track of children. The user
1646 should not have given us a bogus state to inherit, but he might
1647 have. Arguably we should detect SIG_IGN here and pass it on
1648 to children, but probably noone really needs that. */
1649 signal(SIGCHLD, SIG_DFL);
1651 strace_tracer_pid = getpid();
1653 os_release = get_os_release();
1655 /* Allocate the initial tcbtab. */
1656 tcbtabsize = argc; /* Surely enough for all -p args. */
1657 tcbtab = calloc(tcbtabsize, sizeof(tcbtab[0]));
1659 die_out_of_memory();
1660 tcp = calloc(tcbtabsize, sizeof(*tcp));
1662 die_out_of_memory();
1663 for (tcbi = 0; tcbi < tcbtabsize; tcbi++)
1664 tcbtab[tcbi] = tcp++;
1666 shared_log = stderr;
1667 set_sortby(DEFAULT_SORTBY);
1668 set_personality(DEFAULT_PERSONALITY);
1669 qualify("trace=all");
1670 qualify("abbrev=all");
1671 qualify("verbose=all");
1672 #if DEFAULT_QUAL_FLAGS != (QUAL_TRACE | QUAL_ABBREV | QUAL_VERBOSE)
1673 # error Bug in DEFAULT_QUAL_FLAGS
1675 qualify("signal=all");
1676 while ((c = getopt(argc, argv,
1677 "+b:cCdfFhiqrtTvVwxyz"
1678 #ifdef USE_LIBUNWIND
1682 "a:e:o:O:p:s:S:u:E:P:I:")) != EOF) {
1685 if (strcmp(optarg, "execve") != 0)
1686 error_msg_and_die("Syscall '%s' for -b isn't supported",
1688 detach_on_execve = 1;
1691 if (cflag == CFLAG_BOTH) {
1692 error_msg_and_die("-c and -C are mutually exclusive");
1694 cflag = CFLAG_ONLY_STATS;
1697 if (cflag == CFLAG_ONLY_STATS) {
1698 error_msg_and_die("-c and -C are mutually exclusive");
1706 daemonized_tracer = 1;
1725 /* fall through to tflag++ */
1733 count_wallclock = 1;
1742 qualify("abbrev=none");
1745 printf("%s -- version %s\n", PACKAGE_NAME, VERSION);
1749 not_failing_only = 1;
1752 acolumn = string_to_uint(optarg);
1754 error_opt_arg(c, optarg);
1760 outfname = strdup(optarg);
1763 i = string_to_uint(optarg);
1765 error_opt_arg(c, optarg);
1769 process_opt_p_list(optarg);
1772 pathtrace_select(optarg);
1775 i = string_to_uint(optarg);
1777 error_opt_arg(c, optarg);
1784 username = strdup(optarg);
1786 #ifdef USE_LIBUNWIND
1788 stack_trace_enabled = true;
1792 if (putenv(optarg) < 0)
1793 die_out_of_memory();
1796 opt_intr = string_to_uint(optarg);
1797 if (opt_intr <= 0 || opt_intr >= NUM_INTR_OPTS)
1798 error_opt_arg(c, optarg);
1806 /* argc -= optind; - no need, argc is not used below */
1808 acolumn_spaces = malloc(acolumn + 1);
1809 if (!acolumn_spaces)
1810 die_out_of_memory();
1811 memset(acolumn_spaces, ' ', acolumn);
1812 acolumn_spaces[acolumn] = '\0';
1814 /* Must have PROG [ARGS], or -p PID. Not both. */
1815 if (!argv[0] == !nprocs)
1818 if (nprocs != 0 && daemonized_tracer) {
1819 error_msg_and_die("-D and -p are mutually exclusive");
1825 if (followfork >= 2 && cflag) {
1826 error_msg_and_die("(-c or -C) and -ff are mutually exclusive");
1829 if (count_wallclock && !cflag) {
1830 error_msg_and_die("-w must be given with (-c or -C)");
1833 if (cflag == CFLAG_ONLY_STATS) {
1835 error_msg("-%c has no effect with -c", 'i');
1836 #ifdef USE_LIBUNWIND
1837 if (stack_trace_enabled)
1838 error_msg("-%c has no effect with -c", 'k');
1841 error_msg("-%c has no effect with -c", 'r');
1843 error_msg("-%c has no effect with -c", 't');
1845 error_msg("-%c has no effect with -c", 'T');
1847 error_msg("-%c has no effect with -c", 'y');
1850 #ifdef USE_LIBUNWIND
1851 if (stack_trace_enabled)
1855 /* See if they want to run as another user. */
1856 if (username != NULL) {
1857 struct passwd *pent;
1859 if (getuid() != 0 || geteuid() != 0) {
1860 error_msg_and_die("You must be root to use the -u option");
1862 pent = getpwnam(username);
1864 error_msg_and_die("Cannot find user '%s'", username);
1866 run_uid = pent->pw_uid;
1867 run_gid = pent->pw_gid;
1875 * On any reasonably recent Linux kernel (circa about 2.5.46)
1876 * need_fork_exec_workarounds should stay 0 after these tests:
1878 /*need_fork_exec_workarounds = 0; - already is */
1880 need_fork_exec_workarounds = test_ptrace_setoptions_followfork();
1881 need_fork_exec_workarounds |= test_ptrace_setoptions_for_all();
1882 test_ptrace_seize();
1884 /* Check if they want to redirect the output. */
1886 /* See if they want to pipe the output. */
1887 if (outfname[0] == '|' || outfname[0] == '!') {
1889 * We can't do the <outfname>.PID funny business
1890 * when using popen, so prohibit it.
1892 if (followfork >= 2)
1893 error_msg_and_die("Piping the output and -ff are mutually exclusive");
1894 shared_log = strace_popen(outfname + 1);
1896 else if (followfork < 2)
1897 shared_log = strace_fopen(outfname);
1899 /* -ff without -o FILE is the same as single -f */
1900 if (followfork >= 2)
1904 if (!outfname || outfname[0] == '|' || outfname[0] == '!') {
1905 char *buf = malloc(BUFSIZ);
1907 die_out_of_memory();
1908 setvbuf(shared_log, buf, _IOLBF, BUFSIZ);
1910 if (outfname && argv[0]) {
1912 opt_intr = INTR_NEVER;
1916 opt_intr = INTR_WHILE_WAIT;
1918 /* argv[0] -pPID -oFILE Default interactive setting
1919 * yes 0 0 INTR_WHILE_WAIT
1920 * no 1 0 INTR_WHILE_WAIT
1921 * yes 0 1 INTR_NEVER
1922 * no 1 1 INTR_WHILE_WAIT
1925 sigemptyset(&empty_set);
1926 sigemptyset(&blocked_set);
1928 /* startup_child() must be called before the signal handlers get
1929 * installed below as they are inherited into the spawned process.
1930 * Also we do not need to be protected by them as during interruption
1931 * in the startup_child() mode we kill the spawned process anyway.
1934 if (!NOMMU_SYSTEM || daemonized_tracer)
1935 hide_log_until_execve = 1;
1936 skip_one_b_execve = 1;
1937 startup_child(argv);
1940 sa.sa_handler = SIG_IGN;
1941 sigemptyset(&sa.sa_mask);
1943 sigaction(SIGTTOU, &sa, NULL); /* SIG_IGN */
1944 sigaction(SIGTTIN, &sa, NULL); /* SIG_IGN */
1945 if (opt_intr != INTR_ANYWHERE) {
1946 if (opt_intr == INTR_BLOCK_TSTP_TOO)
1947 sigaction(SIGTSTP, &sa, NULL); /* SIG_IGN */
1949 * In interactive mode (if no -o OUTFILE, or -p PID is used),
1950 * fatal signals are blocked while syscall stop is processed,
1951 * and acted on in between, when waiting for new syscall stops.
1952 * In non-interactive mode, signals are ignored.
1954 if (opt_intr == INTR_WHILE_WAIT) {
1955 sigaddset(&blocked_set, SIGHUP);
1956 sigaddset(&blocked_set, SIGINT);
1957 sigaddset(&blocked_set, SIGQUIT);
1958 sigaddset(&blocked_set, SIGPIPE);
1959 sigaddset(&blocked_set, SIGTERM);
1960 sa.sa_handler = interrupt;
1962 /* SIG_IGN, or set handler for these */
1963 sigaction(SIGHUP, &sa, NULL);
1964 sigaction(SIGINT, &sa, NULL);
1965 sigaction(SIGQUIT, &sa, NULL);
1966 sigaction(SIGPIPE, &sa, NULL);
1967 sigaction(SIGTERM, &sa, NULL);
1969 if (nprocs != 0 || daemonized_tracer)
1972 /* Do we want pids printed in our -o OUTFILE?
1973 * -ff: no (every pid has its own file); or
1974 * -f: yes (there can be more pids in the future); or
1975 * -p PID1,PID2: yes (there are already more than one pid)
1977 print_pid_pfx = (outfname && followfork < 2 && (followfork == 1 || nprocs > 1));
1988 for (i = 0; i < tcbtabsize; i++) {
1989 struct tcb *tcp = tcbtab[i];
1990 if (tcp->pid == pid)
2004 /* 'interrupted' is a volatile object, fetch it only once */
2005 fatal_sig = interrupted;
2007 fatal_sig = SIGTERM;
2009 for (i = 0; i < tcbtabsize; i++) {
2015 "cleanup: looking at pid %u\n", tcp->pid);
2016 if (tcp->pid == strace_child) {
2017 kill(tcp->pid, SIGCONT);
2018 kill(tcp->pid, fatal_sig);
2023 call_summary(shared_log);
2037 /* Used to be "while (nprocs != 0)", but in this testcase:
2038 * int main() { _exit(!!fork()); }
2039 * under strace -f, parent sometimes (rarely) manages
2040 * to exit before we see the first stop of the child,
2041 * and we are losing track of it:
2042 * 19923 clone(...) = 19924
2043 * 19923 exit_group(1) = ?
2044 * 19923 +++ exited with 1 +++
2045 * Waiting for ECHILD works better.
2046 * (However, if -o|logger is in use, we can't do that.
2047 * Can work around that by double-forking the logger,
2048 * but that loses the ability to wait for its completion on exit.
2063 if (popen_pid != 0 && nprocs == 0)
2067 sigprocmask(SIG_SETMASK, &empty_set, NULL);
2068 pid = wait4(-1, &status, __WALL, (cflag ? &ru : NULL));
2071 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
2074 if (wait_errno == EINTR)
2076 if (nprocs == 0 && wait_errno == ECHILD)
2078 /* If nprocs > 0, ECHILD is not expected,
2079 * treat it as any other error here:
2082 perror_msg_and_die("wait4(__WALL)");
2085 if (pid == popen_pid) {
2086 if (!WIFSTOPPED(status))
2091 event = ((unsigned)status >> 16);
2093 char buf[sizeof("WIFEXITED,exitcode=%u") + sizeof(int)*3 /*paranoia:*/ + 16];
2094 char evbuf[sizeof(",EVENT_VFORK_DONE (%u)") + sizeof(int)*3 /*paranoia:*/ + 16];
2096 if (WIFSIGNALED(status))
2098 sprintf(buf, "WIFSIGNALED,%ssig=%s",
2099 WCOREDUMP(status) ? "core," : "",
2100 signame(WTERMSIG(status)));
2102 sprintf(buf, "WIFSIGNALED,sig=%s",
2103 signame(WTERMSIG(status)));
2105 if (WIFEXITED(status))
2106 sprintf(buf, "WIFEXITED,exitcode=%u", WEXITSTATUS(status));
2107 if (WIFSTOPPED(status))
2108 sprintf(buf, "WIFSTOPPED,sig=%s", signame(WSTOPSIG(status)));
2110 /* Should never be seen */
2111 if (WIFCONTINUED(status))
2112 strcpy(buf, "WIFCONTINUED");
2116 static const char *const event_names[] = {
2117 [PTRACE_EVENT_CLONE] = "CLONE",
2118 [PTRACE_EVENT_FORK] = "FORK",
2119 [PTRACE_EVENT_VFORK] = "VFORK",
2120 [PTRACE_EVENT_VFORK_DONE] = "VFORK_DONE",
2121 [PTRACE_EVENT_EXEC] = "EXEC",
2122 [PTRACE_EVENT_EXIT] = "EXIT",
2123 /* [PTRACE_EVENT_STOP (=128)] would make biggish array */
2125 const char *e = "??";
2126 if (event < ARRAY_SIZE(event_names))
2127 e = event_names[event];
2128 else if (event == PTRACE_EVENT_STOP)
2130 sprintf(evbuf, ",EVENT_%s (%u)", e, event);
2132 fprintf(stderr, " [wait(0x%06x) = %u] %s%s\n", status, pid, buf, evbuf);
2135 /* Look up 'pid' in our table. */
2139 if (!WIFSTOPPED(status)) {
2140 /* This can happen if we inherited
2141 * an unknown child. Example:
2142 * (sleep 1 & exec strace sleep 2)
2144 error_msg("Exit of unknown pid %u seen", pid);
2148 /* We assume it's a fork/vfork/clone child */
2149 tcp = alloctcb(pid);
2150 tcp->flags |= TCB_ATTACHED | TCB_STARTUP | post_attach_sigstop;
2153 fprintf(stderr, "Process %d attached\n",
2156 /* This can happen if a clone call used
2157 * CLONE_PTRACE itself.
2159 ptrace(PTRACE_CONT, pid, (char *) 0, 0);
2160 error_msg("Stop of unknown pid %u seen, PTRACE_CONTed it", pid);
2166 if (WIFSTOPPED(status))
2169 /* Under Linux, execve changes pid to thread leader's pid,
2170 * and we see this changed pid on EVENT_EXEC and later,
2171 * execve sysexit. Leader "disappears" without exit
2172 * notification. Let user know that, drop leader's tcb,
2173 * and fix up pid in execve thread's tcb.
2174 * Effectively, execve thread's tcb replaces leader's tcb.
2176 * BTW, leader is 'stuck undead' (doesn't report WIFEXITED
2177 * on exit syscall) in multithreaded programs exactly
2178 * in order to handle this case.
2180 * PTRACE_GETEVENTMSG returns old pid starting from Linux 3.0.
2181 * On 2.6 and earlier, it can return garbage.
2183 if (event == PTRACE_EVENT_EXEC && os_release >= KERNEL_VERSION(3,0,0)) {
2185 struct tcb *execve_thread;
2188 if (ptrace(PTRACE_GETEVENTMSG, pid, NULL, (long) &old_pid) < 0)
2189 goto dont_switch_tcbs;
2190 /* Avoid truncation in pid2tcb() param passing */
2191 if (old_pid <= 0 || old_pid == pid)
2192 goto dont_switch_tcbs;
2193 if ((unsigned long) old_pid > UINT_MAX)
2194 goto dont_switch_tcbs;
2195 execve_thread = pid2tcb(old_pid);
2196 /* It should be !NULL, but I feel paranoid */
2198 goto dont_switch_tcbs;
2200 if (execve_thread->curcol != 0) {
2202 * One case we are here is -ff:
2203 * try "strace -oLOG -ff test/threaded_execve"
2205 fprintf(execve_thread->outf, " <pid changed to %d ...>\n", pid);
2206 /*execve_thread->curcol = 0; - no need, see code below */
2208 /* Swap output FILEs (needed for -ff) */
2209 fp = execve_thread->outf;
2210 execve_thread->outf = tcp->outf;
2212 /* And their column positions */
2213 execve_thread->curcol = tcp->curcol;
2215 /* Drop leader, but close execve'd thread outfile (if -ff) */
2217 /* Switch to the thread, reusing leader's outfile and pid */
2218 tcp = execve_thread;
2220 if (cflag != CFLAG_ONLY_STATS) {
2222 tprintf("+++ superseded by execve in pid %lu +++\n", old_pid);
2224 tcp->flags |= TCB_REPRINT;
2229 if (event == PTRACE_EVENT_EXEC) {
2230 if (detach_on_execve && !skip_one_b_execve)
2231 detach(tcp); /* do "-b execve" thingy */
2232 skip_one_b_execve = 0;
2235 /* Set current output file */
2239 tv_sub(&tcp->dtime, &ru.ru_stime, &tcp->stime);
2240 tcp->stime = ru.ru_stime;
2243 if (WIFSIGNALED(status)) {
2244 if (pid == strace_child)
2245 exit_code = 0x100 | WTERMSIG(status);
2246 if (cflag != CFLAG_ONLY_STATS
2247 && (qual_flags[WTERMSIG(status)] & QUAL_SIGNAL)
2251 tprintf("+++ killed by %s %s+++\n",
2252 signame(WTERMSIG(status)),
2253 WCOREDUMP(status) ? "(core dumped) " : "");
2255 tprintf("+++ killed by %s +++\n",
2256 signame(WTERMSIG(status)));
2263 if (WIFEXITED(status)) {
2264 if (pid == strace_child)
2265 exit_code = WEXITSTATUS(status);
2266 if (cflag != CFLAG_ONLY_STATS &&
2269 tprintf("+++ exited with %d +++\n", WEXITSTATUS(status));
2275 if (!WIFSTOPPED(status)) {
2276 fprintf(stderr, "PANIC: pid %u not stopped\n", pid);
2281 /* Is this the very first time we see this tracee stopped? */
2282 if (tcp->flags & TCB_STARTUP) {
2284 fprintf(stderr, "pid %d has TCB_STARTUP, initializing it\n", tcp->pid);
2285 tcp->flags &= ~TCB_STARTUP;
2286 if (tcp->flags & TCB_BPTSET) {
2288 * One example is a breakpoint inherited from
2289 * parent through fork().
2291 if (clearbpt(tcp) < 0) {
2298 if (!use_seize && ptrace_setoptions) {
2300 fprintf(stderr, "setting opts 0x%x on pid %d\n", ptrace_setoptions, tcp->pid);
2301 if (ptrace(PTRACE_SETOPTIONS, tcp->pid, NULL, ptrace_setoptions) < 0) {
2302 if (errno != ESRCH) {
2303 /* Should never happen, really */
2304 perror_msg_and_die("PTRACE_SETOPTIONS");
2310 sig = WSTOPSIG(status);
2315 if (event == PTRACE_EVENT_STOP) {
2317 * PTRACE_INTERRUPT-stop or group-stop.
2318 * PTRACE_INTERRUPT-stop has sig == SIGTRAP here.
2330 goto restart_tracee_with_sig_0;
2333 /* Is this post-attach SIGSTOP?
2334 * Interestingly, the process may stop
2335 * with STOPSIG equal to some other signal
2336 * than SIGSTOP if we happend to attach
2337 * just before the process takes a signal.
2339 if (sig == SIGSTOP && (tcp->flags & TCB_IGNORE_ONE_SIGSTOP)) {
2341 fprintf(stderr, "ignored SIGSTOP on pid %d\n", tcp->pid);
2342 tcp->flags &= ~TCB_IGNORE_ONE_SIGSTOP;
2343 goto restart_tracee_with_sig_0;
2346 if (sig != syscall_trap_sig) {
2349 /* Nonzero (true) if tracee is stopped by signal
2350 * (as opposed to "tracee received signal").
2351 * TODO: shouldn't we check for errno == EINVAL too?
2352 * We can get ESRCH instead, you know...
2354 stopped = (ptrace(PTRACE_GETSIGINFO, pid, 0, (long) &si) < 0);
2358 if (cflag != CFLAG_ONLY_STATS
2359 && !hide_log_until_execve
2360 && (qual_flags[sig] & QUAL_SIGNAL)
2364 tprintf("--- %s ", signame(sig));
2365 printsiginfo(&si, verbose(tcp));
2368 tprintf("--- stopped by %s ---\n",
2374 /* It's signal-delivery-stop. Inject the signal */
2375 goto restart_tracee;
2377 /* It's group-stop */
2380 * This ends ptrace-stop, but does *not* end group-stop.
2381 * This makes stopping signals work properly on straced process
2382 * (that is, process really stops. It used to continue to run).
2384 if (ptrace_restart(PTRACE_LISTEN, tcp, 0) < 0) {
2385 /* Note: ptrace_restart emitted error message */
2391 /* We don't have PTRACE_LISTEN support... */
2392 goto restart_tracee;
2395 /* We handled quick cases, we are permitted to interrupt now. */
2399 /* This should be syscall entry or exit.
2400 * (Or it still can be that pesky post-execve SIGTRAP!)
2403 if (trace_syscall(tcp) < 0) {
2404 /* ptrace() failed in trace_syscall().
2405 * Likely a result of process disappearing mid-flight.
2406 * Observed case: exit_group() or SIGKILL terminating
2407 * all processes in thread group.
2408 * We assume that ptrace error was caused by process death.
2409 * We used to detach(tcp) here, but since we no longer
2410 * implement "detach before death" policy/hack,
2411 * we can let this process to report its death to us
2412 * normally, via WIFEXITED or WIFSIGNALED wait status.
2416 restart_tracee_with_sig_0:
2419 if (ptrace_restart(PTRACE_SYSCALL, tcp, sig) < 0) {
2420 /* Note: ptrace_restart emitted error message */
2428 main(int argc, char *argv[])
2432 /* Run main tracing loop */
2437 if (shared_log != stderr)
2440 while (waitpid(popen_pid, NULL, 0) < 0 && errno == EINTR)
2443 if (exit_code > 0xff) {
2444 /* Avoid potential core file clobbering. */
2445 struct_rlimit rlim = {0, 0};
2446 set_rlimit(RLIMIT_CORE, &rlim);
2448 /* Child was killed by a signal, mimic that. */
2450 signal(exit_code, SIG_DFL);
2452 /* Paranoia - what if this signal is not fatal?
2453 Exit with 128 + signo then. */