2 * Copyright (c) 1991, 1992 Paul Kranenburg <pk@cs.few.eur.nl>
3 * Copyright (c) 1993 Branko Lankester <branko@hacktic.nl>
4 * Copyright (c) 1993, 1994, 1995, 1996 Rick Sladkey <jrs@world.std.com>
5 * Copyright (c) 1996-1999 Wichert Akkerman <wichert@cistron.nl>
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. The name of the author may not be used to endorse or promote products
17 * derived from this software without specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 #include <sys/param.h>
35 #include <sys/resource.h>
41 #include <sys/utsname.h>
43 # include <sys/prctl.h>
46 # include <asm/ptrace_offsets.h>
48 /* In some libc, these aren't declared. Do it ourself: */
49 extern char **environ;
54 #if defined __NR_tkill
55 # define my_tkill(tid, sig) syscall(__NR_tkill, (tid), (sig))
57 /* kill() may choose arbitrarily the target task of the process group
58 while we later wait on a that specific TID. PID process waits become
59 TID task specific waits for a process under ptrace(2). */
60 # warning "tkill(2) not available, risk of strace hangs!"
61 # define my_tkill(tid, sig) kill((tid), (sig))
64 /* Glue for systems without a MMU that cannot provide fork() */
65 #if !defined(HAVE_FORK)
67 # define NOMMU_SYSTEM 1
70 # define fork() vfork()
73 cflag_t cflag = CFLAG_NONE;
74 unsigned int followfork = 0;
75 unsigned int ptrace_setoptions = 0;
76 unsigned int xflag = 0;
77 bool need_fork_exec_workarounds = 0;
81 unsigned int qflag = 0;
82 /* Which WSTOPSIG(status) value marks syscall traps? */
83 static unsigned int syscall_trap_sig = SIGTRAP;
84 static unsigned int tflag = 0;
85 static bool rflag = 0;
86 static bool print_pid_pfx = 0;
91 INTR_ANYWHERE = 1, /* don't block/ignore any signals */
92 INTR_WHILE_WAIT = 2, /* block fatal signals while decoding syscall. default */
93 INTR_NEVER = 3, /* block fatal signals. default if '-o FILE PROG' */
94 INTR_BLOCK_TSTP_TOO = 4, /* block fatal signals and SIGTSTP (^Z) */
98 /* We play with signal mask only if this mode is active: */
99 #define interactive (opt_intr == INTR_WHILE_WAIT)
102 * daemonized_tracer supports -D option.
103 * With this option, strace forks twice.
104 * Unlike normal case, with -D *grandparent* process exec's,
105 * becoming a traced process. Child exits (this prevents traced process
106 * from having children it doesn't expect to have), and grandchild
107 * attaches to grandparent similarly to strace -p PID.
108 * This allows for more transparent interaction in cases
109 * when process and its parent are communicating via signals,
110 * wait() etc. Without -D, strace process gets lodged in between,
111 * disrupting parent<->child link.
113 static bool daemonized_tracer = 0;
116 static int post_attach_sigstop = TCB_IGNORE_ONE_SIGSTOP;
117 # define use_seize (post_attach_sigstop == 0)
119 # define post_attach_sigstop TCB_IGNORE_ONE_SIGSTOP
123 /* Sometimes we want to print only succeeding syscalls. */
124 bool not_failing_only = 0;
126 /* Show path associated with fd arguments */
127 bool show_fd_path = 0;
129 static bool detach_on_execve = 0;
130 /* Are we "strace PROG" and need to skip detach on first execve? */
131 static bool skip_one_b_execve = 0;
132 /* Are we "strace PROG" and need to hide everything until execve? */
133 bool hide_log_until_execve = 0;
135 static int exit_code = 0;
136 static int strace_child = 0;
137 static int strace_tracer_pid = 0;
139 static char *username = NULL;
140 static uid_t run_uid;
141 static gid_t run_gid;
143 unsigned int max_strlen = DEFAULT_STRLEN;
144 static int acolumn = DEFAULT_ACOLUMN;
145 static char *acolumn_spaces;
147 static char *outfname = NULL;
148 /* If -ff, points to stderr. Else, it's our common output log */
149 static FILE *shared_log;
151 struct tcb *printing_tcp = NULL;
152 static struct tcb *current_tcp;
154 static struct tcb **tcbtab;
155 static unsigned int nprocs, tcbtabsize;
156 static const char *progname;
158 unsigned os_release; /* generated from uname()'s u.release */
160 static void detach(struct tcb *tcp);
161 static void cleanup(void);
162 static void interrupt(int sig);
163 static sigset_t empty_set, blocked_set;
165 #ifdef HAVE_SIG_ATOMIC_T
166 static volatile sig_atomic_t interrupted;
168 static volatile int interrupted;
171 #ifndef HAVE_STRERROR
173 #if !HAVE_DECL_SYS_ERRLIST
175 extern char *sys_errlist[];
181 static char buf[sizeof("Unknown error %d") + sizeof(int)*3];
183 if (err_no < 1 || err_no >= sys_nerr) {
184 sprintf(buf, "Unknown error %d", err_no);
187 return sys_errlist[err_no];
190 #endif /* HAVE_STERRROR */
193 usage(FILE *ofp, int exitval)
196 usage: strace [-CdffhiqrtttTvVxxy] [-I n] [-e expr]...\n\
197 [-a column] [-o file] [-s strsize] [-P path]...\n\
198 -p pid... / [-D] [-E var=val]... [-u username] PROG [ARGS]\n\
199 or: strace -c[df] [-I n] [-e expr]... [-O overhead] [-S sortby]\n\
200 -p pid... / [-D] [-E var=val]... [-u username] PROG [ARGS]\n\
201 -c -- count time, calls, and errors for each syscall and report summary\n\
202 -C -- like -c but also print regular output\n\
203 -d -- enable debug output to stderr\n\
204 -D -- run tracer process as a detached grandchild, not as parent\n\
205 -f -- follow forks, -ff -- with output into separate files\n\
206 -i -- print instruction pointer at time of syscall\n\
207 -q -- suppress messages about attaching, detaching, etc.\n\
208 -r -- print relative timestamp, -t -- absolute timestamp, -tt -- with usecs\n\
209 -T -- print time spent in each syscall\n\
210 -v -- verbose mode: print unabbreviated argv, stat, termios, etc. args\n\
211 -x -- print non-ascii strings in hex, -xx -- print all strings in hex\n\
212 -y -- print paths associated with file descriptor arguments\n\
213 -h -- print help message, -V -- print version\n\
214 -a column -- alignment COLUMN for printing syscall results (default %d)\n\
215 -b execve -- detach on this syscall\n\
216 -e expr -- a qualifying expression: option=[!]all or option=[!]val1[,val2]...\n\
217 options: trace, abbrev, verbose, raw, signal, read, write\n\
218 -I interruptible --\n\
219 1: no signals are blocked\n\
220 2: fatal signals are blocked while decoding syscall (default)\n\
221 3: fatal signals are always blocked (default if '-o FILE PROG')\n\
222 4: fatal signals and SIGTSTP (^Z) are always blocked\n\
223 (useful to make 'strace -o FILE PROG' not stop on ^Z)\n\
224 -o file -- send trace output to FILE instead of stderr\n\
225 -O overhead -- set overhead for tracing syscalls to OVERHEAD usecs\n\
226 -p pid -- trace process with process id PID, may be repeated\n\
227 -s strsize -- limit length of print strings to STRSIZE chars (default %d)\n\
228 -S sortby -- sort syscall counts by: time, calls, name, nothing (default %s)\n\
229 -u username -- run command as username handling setuid and/or setgid\n\
230 -E var=val -- put var=val in the environment for command\n\
231 -E var -- remove var from the environment for command\n\
232 -P path -- trace accesses to path\n\
234 /* ancient, no one should use it
235 -F -- attempt to follow vforks (deprecated, use -f)\n\
237 /* this is broken, so don't document it
238 -z -- print only succeeding syscalls\n\
240 , DEFAULT_ACOLUMN, DEFAULT_STRLEN, DEFAULT_SORTBY);
244 static void die(void) __attribute__ ((noreturn));
245 static void die(void)
247 if (strace_tracer_pid == getpid()) {
254 static void verror_msg(int err_no, const char *fmt, va_list p)
260 /* We want to print entire message with single fprintf to ensure
261 * message integrity if stderr is shared with other programs.
262 * Thus we use vasprintf + single fprintf.
265 if (vasprintf(&msg, fmt, p) >= 0) {
267 fprintf(stderr, "%s: %s: %s\n", progname, msg, strerror(err_no));
269 fprintf(stderr, "%s: %s\n", progname, msg);
272 /* malloc in vasprintf failed, try it without malloc */
273 fprintf(stderr, "%s: ", progname);
274 vfprintf(stderr, fmt, p);
276 fprintf(stderr, ": %s\n", strerror(err_no));
280 /* We don't switch stderr to buffered, thus fprintf(stderr)
281 * always flushes its output and this is not necessary: */
282 /* fflush(stderr); */
285 void error_msg(const char *fmt, ...)
289 verror_msg(0, fmt, p);
293 void error_msg_and_die(const char *fmt, ...)
297 verror_msg(0, fmt, p);
301 void perror_msg(const char *fmt, ...)
305 verror_msg(errno, fmt, p);
309 void perror_msg_and_die(const char *fmt, ...)
313 verror_msg(errno, fmt, p);
317 void die_out_of_memory(void)
319 static bool recursed = 0;
323 error_msg_and_die("Out of memory");
327 error_opt_arg(int opt, const char *arg)
329 error_msg_and_die("Invalid -%c argument: '%s'", opt, arg);
334 ptrace_attach_or_seize(int pid)
338 return ptrace(PTRACE_ATTACH, pid, 0L, 0L);
339 r = ptrace(PTRACE_SEIZE, pid, 0L, (unsigned long)ptrace_setoptions);
342 r = ptrace(PTRACE_INTERRUPT, pid, 0L, 0L);
346 # define ptrace_attach_or_seize(pid) ptrace(PTRACE_ATTACH, (pid), 0, 0)
350 * Used when we want to unblock stopped traced process.
351 * Should be only used with PTRACE_CONT, PTRACE_DETACH and PTRACE_SYSCALL.
352 * Returns 0 on success or if error was ESRCH
353 * (presumably process was killed while we talk to it).
354 * Otherwise prints error message and returns -1.
357 ptrace_restart(int op, struct tcb *tcp, int sig)
363 ptrace(op, tcp->pid, (void *) 0, (long) sig);
369 if (op == PTRACE_CONT)
371 if (op == PTRACE_DETACH)
374 if (op == PTRACE_LISTEN)
378 * Why curcol != 0? Otherwise sometimes we get this:
380 * 10252 kill(10253, SIGKILL) = 0
381 * <ptrace(SYSCALL,10252):No such process>10253 ...next decode...
383 * 10252 died after we retrieved syscall exit data,
384 * but before we tried to restart it. Log looks ugly.
386 if (current_tcp && current_tcp->curcol != 0) {
387 tprintf(" <ptrace(%s):%s>\n", msg, strerror(err));
393 perror_msg("ptrace(PTRACE_%s,pid:%d,sig:%d)", msg, tcp->pid, sig);
398 set_cloexec_flag(int fd)
402 flags = fcntl(fd, F_GETFD);
404 /* Can happen only if fd is bad.
405 * Should never happen: if it does, we have a bug
406 * in the caller. Therefore we just abort
407 * instead of propagating the error.
409 perror_msg_and_die("fcntl(%d, F_GETFD)", fd);
412 newflags = flags | FD_CLOEXEC;
413 if (flags == newflags)
416 fcntl(fd, F_SETFD, newflags); /* never fails */
419 static void kill_save_errno(pid_t pid, int sig)
421 int saved_errno = errno;
423 (void) kill(pid, sig);
428 * When strace is setuid executable, we have to swap uids
429 * before and after filesystem and process management operations.
434 int euid = geteuid(), uid = getuid();
436 if (euid != uid && setreuid(euid, uid) < 0) {
437 perror_msg_and_die("setreuid");
441 #ifdef _LARGEFILE64_SOURCE
443 # define fopen_for_output fopen64
445 # define fopen_for_output fopen
447 # define struct_stat struct stat64
448 # define stat_file stat64
449 # define struct_dirent struct dirent64
450 # define read_dir readdir64
451 # define struct_rlimit struct rlimit64
452 # define set_rlimit setrlimit64
454 # define fopen_for_output fopen
455 # define struct_stat struct stat
456 # define stat_file stat
457 # define struct_dirent struct dirent
458 # define read_dir readdir
459 # define struct_rlimit struct rlimit
460 # define set_rlimit setrlimit
464 strace_fopen(const char *path)
469 fp = fopen_for_output(path, "w");
471 perror_msg_and_die("Can't fopen '%s'", path);
473 set_cloexec_flag(fileno(fp));
477 static int popen_pid = 0;
480 # define _PATH_BSHELL "/bin/sh"
484 * We cannot use standard popen(3) here because we have to distinguish
485 * popen child process from other processes we trace, and standard popen(3)
486 * does not export its child's pid.
489 strace_popen(const char *command)
497 perror_msg_and_die("pipe");
499 set_cloexec_flag(fds[1]); /* never fails */
503 perror_msg_and_die("vfork");
510 perror_msg_and_die("dup2");
513 execl(_PATH_BSHELL, "sh", "-c", command, NULL);
514 perror_msg_and_die("Can't execute '%s'", _PATH_BSHELL);
521 fp = fdopen(fds[1], "w");
528 tprintf(const char *fmt, ...)
534 int n = strace_vfprintf(current_tcp->outf, fmt, args);
536 if (current_tcp->outf != stderr)
537 perror_msg("%s", outfname);
539 current_tcp->curcol += n;
544 #ifndef HAVE_FPUTS_UNLOCKED
545 # define fputs_unlocked fputs
549 tprints(const char *str)
552 int n = fputs_unlocked(str, current_tcp->outf);
554 current_tcp->curcol += strlen(str);
557 if (current_tcp->outf != stderr)
558 perror_msg("%s", outfname);
566 current_tcp->curcol = 0;
567 fflush(current_tcp->outf);
570 printing_tcp->curcol = 0;
576 printleader(struct tcb *tcp)
578 /* If -ff, "previous tcb we printed" is always the same as current,
579 * because we have per-tcb output files.
585 current_tcp = printing_tcp;
586 if (printing_tcp->curcol != 0 && (followfork < 2 || printing_tcp == tcp)) {
588 * case 1: we have a shared log (i.e. not -ff), and last line
589 * wasn't finished (same or different tcb, doesn't matter).
590 * case 2: split log, we are the same tcb, but our last line
591 * didn't finish ("SIGKILL nuked us after syscall entry" etc).
593 tprints(" <unfinished ...>\n");
594 printing_tcp->curcol = 0;
600 current_tcp->curcol = 0;
603 tprintf("%-5d ", tcp->pid);
604 else if (nprocs > 1 && !outfname)
605 tprintf("[pid %5u] ", tcp->pid);
608 char str[sizeof("HH:MM:SS")];
609 struct timeval tv, dtv;
610 static struct timeval otv;
612 gettimeofday(&tv, NULL);
616 tv_sub(&dtv, &tv, &otv);
617 tprintf("%6ld.%06ld ",
618 (long) dtv.tv_sec, (long) dtv.tv_usec);
621 else if (tflag > 2) {
622 tprintf("%ld.%06ld ",
623 (long) tv.tv_sec, (long) tv.tv_usec);
626 time_t local = tv.tv_sec;
627 strftime(str, sizeof(str), "%T", localtime(&local));
629 tprintf("%s.%06ld ", str, (long) tv.tv_usec);
641 if (current_tcp->curcol < acolumn)
642 tprints(acolumn_spaces + current_tcp->curcol);
645 /* Should be only called directly *after successful attach* to a tracee.
646 * Otherwise, "strace -oFILE -ff -p<nonexistant_pid>"
647 * may create bogus empty FILE.<nonexistant_pid>, and then die.
650 newoutf(struct tcb *tcp)
652 tcp->outf = shared_log; /* if not -ff mode, the same file is for all */
653 if (followfork >= 2) {
654 char name[520 + sizeof(int) * 3];
655 sprintf(name, "%.512s.%u", outfname, tcp->pid);
656 tcp->outf = strace_fopen(name);
663 /* Allocate some more TCBs and expand the table.
664 We don't want to relocate the TCBs because our
665 callers have pointers and it would be a pain.
666 So tcbtab is a table of pointers. Since we never
667 free the TCBs, we allocate a single chunk of many. */
669 struct tcb *newtcbs = calloc(tcbtabsize, sizeof(newtcbs[0]));
670 struct tcb **newtab = realloc(tcbtab, tcbtabsize * 2 * sizeof(tcbtab[0]));
671 if (!newtab || !newtcbs)
675 while (i < tcbtabsize)
676 tcbtab[i++] = newtcbs++;
685 if (nprocs == tcbtabsize)
688 for (i = 0; i < tcbtabsize; i++) {
691 memset(tcp, 0, sizeof(*tcp));
693 #if SUPPORTED_PERSONALITIES > 1
694 tcp->currpers = current_personality;
698 fprintf(stderr, "new tcb for pid %d, active tcbs:%d\n", tcp->pid, nprocs);
702 error_msg_and_die("bug in alloctcb");
706 droptcb(struct tcb *tcp)
713 fprintf(stderr, "dropped tcb for pid %d, %d remain\n", tcp->pid, nprocs);
716 if (followfork >= 2) {
717 if (tcp->curcol != 0)
718 fprintf(tcp->outf, " <detached ...>\n");
721 if (printing_tcp == tcp && tcp->curcol != 0)
722 fprintf(tcp->outf, " <detached ...>\n");
727 if (current_tcp == tcp)
729 if (printing_tcp == tcp)
732 memset(tcp, 0, sizeof(*tcp));
735 /* Detach traced process.
736 * Never call DETACH twice on the same process as both unattached and
737 * attached-unstopped processes give the same ESRCH. For unattached process we
738 * would SIGSTOP it and wait for its SIGSTOP notification forever.
741 detach(struct tcb *tcp)
746 if (tcp->flags & TCB_BPTSET)
750 * Linux wrongly insists the child be stopped
751 * before detaching. Arghh. We go through hoops
752 * to make a clean break of things.
755 # undef PTRACE_DETACH
756 # define PTRACE_DETACH PTRACE_SUNDETACH
759 if (!(tcp->flags & TCB_ATTACHED))
762 /* We attached but possibly didn't see the expected SIGSTOP.
763 * We must catch exactly one as otherwise the detached process
764 * would be left stopped (process state T).
766 if (tcp->flags & TCB_IGNORE_ONE_SIGSTOP)
769 error = ptrace(PTRACE_DETACH, tcp->pid, 0, 0);
771 /* On a clear day, you can see forever. */
774 if (errno != ESRCH) {
775 /* Shouldn't happen. */
776 perror_msg("detach: ptrace(PTRACE_DETACH,%u)", tcp->pid);
779 /* ESRCH: process is either not stopped or doesn't exist. */
780 if (my_tkill(tcp->pid, 0) < 0) {
782 /* Shouldn't happen. */
783 perror_msg("detach: tkill(%u,0)", tcp->pid);
784 /* else: process doesn't exist. */
787 /* Process is not stopped, need to stop it. */
790 * With SEIZE, tracee can be in group-stop already.
791 * In this state sending it another SIGSTOP does nothing.
792 * Need to use INTERRUPT.
793 * Testcase: trying to ^C a "strace -p <stopped_process>".
795 error = ptrace(PTRACE_INTERRUPT, tcp->pid, 0, 0);
799 perror_msg("detach: ptrace(PTRACE_INTERRUPT,%u)", tcp->pid);
802 error = my_tkill(tcp->pid, SIGSTOP);
806 perror_msg("detach: tkill(%u,SIGSTOP)", tcp->pid);
808 /* Either process doesn't exist, or some weird error. */
812 /* We end up here in three cases:
813 * 1. We sent PTRACE_INTERRUPT (use_seize case)
814 * 2. We sent SIGSTOP (!use_seize)
815 * 3. Attach SIGSTOP was already pending (TCB_IGNORE_ONE_SIGSTOP set)
819 if (waitpid(tcp->pid, &status, __WALL) < 0) {
823 * if (errno == ECHILD) break;
824 * ^^^ WRONG! We expect this PID to exist,
825 * and want to emit a message otherwise:
827 perror_msg("detach: waitpid(%u)", tcp->pid);
830 if (!WIFSTOPPED(status)) {
832 * Tracee exited or was killed by signal.
833 * We shouldn't normally reach this place:
834 * we don't want to consume exit status.
835 * Consider "strace -p PID" being ^C-ed:
836 * we want merely to detach from PID.
838 * However, we _can_ end up here if tracee
843 sig = WSTOPSIG(status);
845 fprintf(stderr, "detach wait: event:%d sig:%d\n",
846 (unsigned)status >> 16, sig);
848 unsigned event = (unsigned)status >> 16;
849 if (event == PTRACE_EVENT_STOP /*&& sig == SIGTRAP*/) {
851 * sig == SIGTRAP: PTRACE_INTERRUPT stop.
852 * sig == other: process was already stopped
853 * with this stopping sig (see tests/detach-stopped).
854 * Looks like re-injecting this sig is not necessary
855 * in DETACH for the tracee to remain stopped.
860 * PTRACE_INTERRUPT is not guaranteed to produce
861 * the above event if other ptrace-stop is pending.
862 * See tests/detach-sleeping testcase:
863 * strace got SIGINT while tracee is sleeping.
864 * We sent PTRACE_INTERRUPT.
865 * We see syscall exit, not PTRACE_INTERRUPT stop.
866 * We won't get PTRACE_INTERRUPT stop
867 * if we would CONT now. Need to DETACH.
869 if (sig == syscall_trap_sig)
871 /* else: not sure in which case we can be here.
872 * Signal stop? Inject it while detaching.
874 ptrace_restart(PTRACE_DETACH, tcp, sig);
877 /* Note: this check has to be after use_seize check */
878 /* (else, in use_seize case SIGSTOP will be mistreated) */
879 if (sig == SIGSTOP) {
880 /* Detach, suppressing SIGSTOP */
881 ptrace_restart(PTRACE_DETACH, tcp, 0);
884 if (sig == syscall_trap_sig)
886 /* Can't detach just yet, may need to wait for SIGSTOP */
887 error = ptrace_restart(PTRACE_CONT, tcp, sig);
889 /* Should not happen.
890 * Note: ptrace_restart returns 0 on ESRCH, so it's not it.
891 * ptrace_restart already emitted error message.
898 if (!qflag && (tcp->flags & TCB_ATTACHED))
899 fprintf(stderr, "Process %u detached\n", tcp->pid);
905 process_opt_p_list(char *opt)
909 * We accept -p PID,PID; -p "`pidof PROG`"; -p "`pgrep PROG`".
910 * pidof uses space as delim, pgrep uses newline. :(
913 char *delim = opt + strcspn(opt, ", \n\t");
917 pid = string_to_uint(opt);
919 error_msg_and_die("Invalid process id: '%s'", opt);
921 if (pid == strace_tracer_pid) {
922 error_msg_and_die("I'm sorry, I can't let you do that, Dave.");
939 * Block user interruptions as we would leave the traced
940 * process stopped (process state T) if we would terminate in
941 * between PTRACE_ATTACH and wait4() on SIGSTOP.
942 * We rely on cleanup() from this point on.
945 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
947 if (daemonized_tracer) {
950 perror_msg_and_die("fork");
952 if (pid) { /* parent */
954 * Wait for grandchild to attach to straced process
955 * (grandparent). Grandchild SIGKILLs us after it attached.
956 * Grandparent's wait() is unblocked by our death,
957 * it proceeds to exec the straced program.
960 _exit(0); /* paranoia */
963 /* We will be the tracer process. Remember our new pid: */
964 strace_tracer_pid = getpid();
967 for (tcbi = 0; tcbi < tcbtabsize; tcbi++) {
973 /* Is this a process we should attach to, but not yet attached? */
974 if (tcp->flags & TCB_ATTACHED)
975 continue; /* no, we already attached it */
977 if (followfork && !daemonized_tracer) {
978 char procdir[sizeof("/proc/%d/task") + sizeof(int) * 3];
981 sprintf(procdir, "/proc/%d/task", tcp->pid);
982 dir = opendir(procdir);
984 unsigned int ntid = 0, nerr = 0;
987 while ((de = read_dir(dir)) != NULL) {
991 if (de->d_fileno == 0)
993 /* we trust /proc filesystem */
994 tid = atoi(de->d_name);
998 if (ptrace_attach_or_seize(tid) < 0) {
1001 fprintf(stderr, "attach to pid %d failed\n", tid);
1005 fprintf(stderr, "attach to pid %d succeeded\n", tid);
1007 if (tid != tcp->pid)
1008 cur_tcp = alloctcb(tid);
1009 cur_tcp->flags |= TCB_ATTACHED | TCB_STARTUP | post_attach_sigstop;
1014 sigprocmask(SIG_SETMASK, &empty_set, NULL);
1017 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
1021 perror_msg("attach: ptrace(PTRACE_ATTACH, ...)");
1026 fprintf(stderr, ntid > 1
1027 ? "Process %u attached with %u threads\n"
1028 : "Process %u attached\n",
1031 if (!(tcp->flags & TCB_ATTACHED)) {
1032 /* -p PID, we failed to attach to PID itself
1033 * but did attach to some of its sibling threads.
1039 } /* if (opendir worked) */
1041 if (ptrace_attach_or_seize(tcp->pid) < 0) {
1042 perror_msg("attach: ptrace(PTRACE_ATTACH, ...)");
1046 tcp->flags |= TCB_ATTACHED | TCB_STARTUP | post_attach_sigstop;
1049 fprintf(stderr, "attach to pid %d (main) succeeded\n", tcp->pid);
1051 if (daemonized_tracer) {
1053 * Make parent go away.
1054 * Also makes grandparent's wait() unblock.
1056 kill(getppid(), SIGKILL);
1061 "Process %u attached\n",
1063 } /* for each tcbtab[] */
1067 sigprocmask(SIG_SETMASK, &empty_set, NULL);
1070 /* Stack-o-phobic exec helper, in the hope to work around
1071 * NOMMU + "daemonized tracer" difficulty.
1073 struct exec_params {
1080 static struct exec_params params_for_tracee;
1081 static void __attribute__ ((noinline, noreturn))
1084 struct exec_params *params = ¶ms_for_tracee;
1086 if (params->fd_to_close >= 0)
1087 close(params->fd_to_close);
1088 if (!daemonized_tracer && !use_seize) {
1089 if (ptrace(PTRACE_TRACEME, 0L, 0L, 0L) < 0) {
1090 perror_msg_and_die("ptrace(PTRACE_TRACEME, ...)");
1094 if (username != NULL) {
1096 * It is important to set groups before we
1097 * lose privileges on setuid.
1099 if (initgroups(username, run_gid) < 0) {
1100 perror_msg_and_die("initgroups");
1102 if (setregid(run_gid, params->run_egid) < 0) {
1103 perror_msg_and_die("setregid");
1105 if (setreuid(run_uid, params->run_euid) < 0) {
1106 perror_msg_and_die("setreuid");
1109 else if (geteuid() != 0)
1110 if (setreuid(run_uid, run_uid) < 0) {
1111 perror_msg_and_die("setreuid");
1114 if (!daemonized_tracer) {
1116 * Induce a ptrace stop. Tracer (our parent)
1117 * will resume us with PTRACE_SYSCALL and display
1118 * the immediately following execve syscall.
1119 * Can't do this on NOMMU systems, we are after
1120 * vfork: parent is blocked, stopping would deadlock.
1123 kill(getpid(), SIGSTOP);
1126 /* we depend on SIGCHLD set to SIG_DFL by init code */
1127 /* if it happens to be SIG_IGN'ed, wait won't block */
1132 execv(params->pathname, params->argv);
1133 perror_msg_and_die("exec");
1137 startup_child(char **argv)
1139 struct_stat statbuf;
1140 const char *filename;
1141 char pathname[MAXPATHLEN];
1146 if (strchr(filename, '/')) {
1147 if (strlen(filename) > sizeof pathname - 1) {
1148 errno = ENAMETOOLONG;
1149 perror_msg_and_die("exec");
1151 strcpy(pathname, filename);
1153 #ifdef USE_DEBUGGING_EXEC
1155 * Debuggers customarily check the current directory
1156 * first regardless of the path but doing that gives
1157 * security geeks a panic attack.
1159 else if (stat_file(filename, &statbuf) == 0)
1160 strcpy(pathname, filename);
1161 #endif /* USE_DEBUGGING_EXEC */
1166 for (path = getenv("PATH"); path && *path; path += m) {
1167 const char *colon = strchr(path, ':');
1173 m = n = strlen(path);
1175 if (!getcwd(pathname, MAXPATHLEN))
1177 len = strlen(pathname);
1179 else if (n > sizeof pathname - 1)
1182 strncpy(pathname, path, n);
1185 if (len && pathname[len - 1] != '/')
1186 pathname[len++] = '/';
1187 strcpy(pathname + len, filename);
1188 if (stat_file(pathname, &statbuf) == 0 &&
1189 /* Accept only regular files
1190 with some execute bits set.
1191 XXX not perfect, might still fail */
1192 S_ISREG(statbuf.st_mode) &&
1193 (statbuf.st_mode & 0111))
1197 if (stat_file(pathname, &statbuf) < 0) {
1198 perror_msg_and_die("Can't stat '%s'", filename);
1201 params_for_tracee.fd_to_close = (shared_log != stderr) ? fileno(shared_log) : -1;
1202 params_for_tracee.run_euid = (statbuf.st_mode & S_ISUID) ? statbuf.st_uid : run_uid;
1203 params_for_tracee.run_egid = (statbuf.st_mode & S_ISGID) ? statbuf.st_gid : run_gid;
1204 params_for_tracee.argv = argv;
1206 * On NOMMU, can be safely freed only after execve in tracee.
1207 * It's hard to know when that happens, so we just leak it.
1209 params_for_tracee.pathname = NOMMU_SYSTEM ? strdup(pathname) : pathname;
1211 #if defined HAVE_PRCTL && defined PR_SET_PTRACER && defined PR_SET_PTRACER_ANY
1212 if (daemonized_tracer)
1213 prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY);
1218 perror_msg_and_die("fork");
1220 if ((pid != 0 && daemonized_tracer)
1221 || (pid == 0 && !daemonized_tracer)
1223 /* We are to become the tracee. Two cases:
1225 * not -D: we are child
1230 /* We are the tracer */
1232 if (!daemonized_tracer) {
1235 /* child did PTRACE_TRACEME, nothing to do in parent */
1237 if (!NOMMU_SYSTEM) {
1238 /* Wait until child stopped itself */
1240 while (waitpid(pid, &status, WSTOPPED) < 0) {
1243 perror_msg_and_die("waitpid");
1245 if (!WIFSTOPPED(status) || WSTOPSIG(status) != SIGSTOP) {
1246 kill_save_errno(pid, SIGKILL);
1247 perror_msg_and_die("Unexpected wait status %x", status);
1250 /* Else: NOMMU case, we have no way to sync.
1251 * Just attach to it as soon as possible.
1252 * This means that we may miss a few first syscalls...
1255 if (ptrace_attach_or_seize(pid)) {
1256 kill_save_errno(pid, SIGKILL);
1257 perror_msg_and_die("Can't attach to %d", pid);
1262 tcp = alloctcb(pid);
1264 tcp->flags |= TCB_ATTACHED | TCB_STARTUP | post_attach_sigstop;
1266 tcp->flags |= TCB_ATTACHED | TCB_STARTUP;
1270 /* With -D, we are *child* here, IOW: different pid. Fetch it: */
1271 strace_tracer_pid = getpid();
1272 /* The tracee is our parent: */
1275 /* attaching will be done later, by startup_attach */
1276 /* note: we don't do newoutf(tcp) here either! */
1278 /* NOMMU BUG! -D mode is active, we (child) return,
1279 * and we will scribble over parent's stack!
1280 * When parent later unpauses, it segfaults.
1283 * (1) by declaring exec_or_die() NORETURN,
1284 * hopefully compiler will just jump to it
1285 * instead of call (won't push anything to stack),
1286 * (2) by trying very hard in exec_or_die()
1287 * to not use any stack,
1288 * (3) having a really big (MAXPATHLEN) stack object
1289 * in this function, which creates a "buffer" between
1290 * child's and parent's stack pointers.
1291 * This may save us if (1) and (2) failed
1292 * and compiler decided to use stack in exec_or_die() anyway
1293 * (happens on i386 because of stack parameter passing).
1295 * A cleaner solution is to use makecontext + setcontext
1296 * to create a genuine separate stack and execute on it.
1302 * Test whether the kernel support PTRACE_O_TRACECLONE et al options.
1303 * First fork a new child, call ptrace with PTRACE_SETOPTIONS on it,
1304 * and then see which options are supported by the kernel.
1307 test_ptrace_setoptions_followfork(void)
1309 int pid, expected_grandchild = 0, found_grandchild = 0;
1310 const unsigned int test_options = PTRACE_O_TRACECLONE |
1311 PTRACE_O_TRACEFORK |
1312 PTRACE_O_TRACEVFORK;
1314 /* Need fork for test. NOMMU has no forks */
1316 goto worked; /* be bold, and pretend that test succeeded */
1320 perror_msg_and_die("fork");
1323 if (ptrace(PTRACE_TRACEME, 0L, 0L, 0L) < 0)
1324 perror_msg_and_die("%s: PTRACE_TRACEME doesn't work",
1326 kill_save_errno(pid, SIGSTOP);
1328 perror_msg_and_die("fork");
1333 int status, tracee_pid;
1336 tracee_pid = wait(&status);
1337 if (tracee_pid <= 0) {
1340 if (errno == ECHILD)
1342 kill_save_errno(pid, SIGKILL);
1343 perror_msg_and_die("%s: unexpected wait result %d",
1344 __func__, tracee_pid);
1346 if (WIFEXITED(status)) {
1347 if (WEXITSTATUS(status)) {
1348 if (tracee_pid != pid)
1349 kill_save_errno(pid, SIGKILL);
1350 error_msg_and_die("%s: unexpected exit status %u",
1351 __func__, WEXITSTATUS(status));
1355 if (WIFSIGNALED(status)) {
1356 if (tracee_pid != pid)
1357 kill_save_errno(pid, SIGKILL);
1358 error_msg_and_die("%s: unexpected signal %u",
1359 __func__, WTERMSIG(status));
1361 if (!WIFSTOPPED(status)) {
1362 if (tracee_pid != pid)
1363 kill_save_errno(tracee_pid, SIGKILL);
1364 kill_save_errno(pid, SIGKILL);
1365 error_msg_and_die("%s: unexpected wait status %x",
1368 if (tracee_pid != pid) {
1369 found_grandchild = tracee_pid;
1370 if (ptrace(PTRACE_CONT, tracee_pid, 0, 0) < 0) {
1371 kill_save_errno(tracee_pid, SIGKILL);
1372 kill_save_errno(pid, SIGKILL);
1373 perror_msg_and_die("PTRACE_CONT doesn't work");
1377 switch (WSTOPSIG(status)) {
1379 if (ptrace(PTRACE_SETOPTIONS, pid, 0, test_options) < 0
1380 && errno != EINVAL && errno != EIO)
1381 perror_msg("PTRACE_SETOPTIONS");
1384 if (status >> 16 == PTRACE_EVENT_FORK) {
1387 if (ptrace(PTRACE_GETEVENTMSG, pid,
1388 NULL, (long) &msg) == 0)
1389 expected_grandchild = msg;
1393 if (ptrace(PTRACE_SYSCALL, pid, 0, 0) < 0) {
1394 kill_save_errno(pid, SIGKILL);
1395 perror_msg_and_die("PTRACE_SYSCALL doesn't work");
1398 if (expected_grandchild && expected_grandchild == found_grandchild) {
1400 ptrace_setoptions |= test_options;
1402 fprintf(stderr, "ptrace_setoptions = %#x\n",
1406 error_msg("Test for PTRACE_O_TRACECLONE failed, "
1407 "giving up using this feature.");
1412 * Test whether the kernel support PTRACE_O_TRACESYSGOOD.
1413 * First fork a new child, call ptrace(PTRACE_SETOPTIONS) on it,
1414 * and then see whether it will stop with (SIGTRAP | 0x80).
1416 * Use of this option enables correct handling of user-generated SIGTRAPs,
1417 * and SIGTRAPs generated by special instructions such as int3 on x86:
1418 * _start: .globl _start
1423 * (compile with: "gcc -nostartfiles -nostdlib -o int3 int3.S")
1426 test_ptrace_setoptions_for_all(void)
1428 const unsigned int test_options = PTRACE_O_TRACESYSGOOD |
1433 /* Need fork for test. NOMMU has no forks */
1435 goto worked; /* be bold, and pretend that test succeeded */
1439 perror_msg_and_die("fork");
1443 if (ptrace(PTRACE_TRACEME, 0L, 0L, 0L) < 0)
1444 /* Note: exits with exitcode 1 */
1445 perror_msg_and_die("%s: PTRACE_TRACEME doesn't work",
1448 _exit(0); /* parent should see entry into this syscall */
1452 int status, tracee_pid;
1455 tracee_pid = wait(&status);
1456 if (tracee_pid <= 0) {
1459 kill_save_errno(pid, SIGKILL);
1460 perror_msg_and_die("%s: unexpected wait result %d",
1461 __func__, tracee_pid);
1463 if (WIFEXITED(status)) {
1464 if (WEXITSTATUS(status) == 0)
1466 error_msg_and_die("%s: unexpected exit status %u",
1467 __func__, WEXITSTATUS(status));
1469 if (WIFSIGNALED(status)) {
1470 error_msg_and_die("%s: unexpected signal %u",
1471 __func__, WTERMSIG(status));
1473 if (!WIFSTOPPED(status)) {
1475 error_msg_and_die("%s: unexpected wait status %x",
1478 if (WSTOPSIG(status) == SIGSTOP) {
1480 * We don't check "options aren't accepted" error.
1481 * If it happens, we'll never get (SIGTRAP | 0x80),
1482 * and thus will decide to not use the option.
1483 * IOW: the outcome of the test will be correct.
1485 if (ptrace(PTRACE_SETOPTIONS, pid, 0L, test_options) < 0
1486 && errno != EINVAL && errno != EIO)
1487 perror_msg("PTRACE_SETOPTIONS");
1489 if (WSTOPSIG(status) == (SIGTRAP | 0x80)) {
1492 if (ptrace(PTRACE_SYSCALL, pid, 0L, 0L) < 0) {
1493 kill_save_errno(pid, SIGKILL);
1494 perror_msg_and_die("PTRACE_SYSCALL doesn't work");
1500 syscall_trap_sig = (SIGTRAP | 0x80);
1501 ptrace_setoptions |= test_options;
1503 fprintf(stderr, "ptrace_setoptions = %#x\n",
1508 error_msg("Test for PTRACE_O_TRACESYSGOOD failed, "
1509 "giving up using this feature.");
1515 test_ptrace_seize(void)
1519 /* Need fork for test. NOMMU has no forks */
1521 post_attach_sigstop = 0; /* this sets use_seize to 1 */
1527 perror_msg_and_die("fork");
1534 /* PTRACE_SEIZE, unlike ATTACH, doesn't force tracee to trap. After
1535 * attaching tracee continues to run unless a trap condition occurs.
1536 * PTRACE_SEIZE doesn't affect signal or group stop state.
1538 if (ptrace(PTRACE_SEIZE, pid, 0, 0) == 0) {
1539 post_attach_sigstop = 0; /* this sets use_seize to 1 */
1540 } else if (debug_flag) {
1541 fprintf(stderr, "PTRACE_SEIZE doesn't work\n");
1547 int status, tracee_pid;
1550 tracee_pid = waitpid(pid, &status, 0);
1551 if (tracee_pid <= 0) {
1554 perror_msg_and_die("%s: unexpected wait result %d",
1555 __func__, tracee_pid);
1557 if (WIFSIGNALED(status)) {
1560 error_msg_and_die("%s: unexpected wait status %x",
1564 #else /* !USE_SEIZE */
1565 # define test_ptrace_seize() ((void)0)
1569 get_os_release(void)
1575 perror_msg_and_die("uname");
1576 /* u.release has this form: "3.2.9[-some-garbage]" */
1580 if (!(*p >= '0' && *p <= '9'))
1581 error_msg_and_die("Bad OS release string: '%s'", u.release);
1582 /* Note: this open-codes KERNEL_VERSION(): */
1583 rel = (rel << 8) | atoi(p);
1584 if (rel >= KERNEL_VERSION(1,0,0))
1586 while (*p >= '0' && *p <= '9')
1589 if (rel >= KERNEL_VERSION(0,1,0)) {
1590 /* "X.Y-something" means "X.Y.0" */
1594 error_msg_and_die("Bad OS release string: '%s'", u.release);
1602 * Initialization part of main() was eating much stack (~0.5k),
1603 * which was unused after init.
1604 * We can reuse it if we move init code into a separate function.
1606 * Don't want main() to inline us and defeat the reason
1607 * we have a separate function.
1609 static void __attribute__ ((noinline))
1610 init(int argc, char *argv[])
1615 struct sigaction sa;
1617 progname = argv[0] ? argv[0] : "strace";
1619 /* Make sure SIGCHLD has the default action so that waitpid
1620 definitely works without losing track of children. The user
1621 should not have given us a bogus state to inherit, but he might
1622 have. Arguably we should detect SIG_IGN here and pass it on
1623 to children, but probably noone really needs that. */
1624 signal(SIGCHLD, SIG_DFL);
1626 strace_tracer_pid = getpid();
1628 os_release = get_os_release();
1630 /* Allocate the initial tcbtab. */
1631 tcbtabsize = argc; /* Surely enough for all -p args. */
1632 tcbtab = calloc(tcbtabsize, sizeof(tcbtab[0]));
1634 die_out_of_memory();
1635 tcp = calloc(tcbtabsize, sizeof(*tcp));
1637 die_out_of_memory();
1638 for (c = 0; c < tcbtabsize; c++)
1641 shared_log = stderr;
1642 set_sortby(DEFAULT_SORTBY);
1643 set_personality(DEFAULT_PERSONALITY);
1644 qualify("trace=all");
1645 qualify("abbrev=all");
1646 qualify("verbose=all");
1647 #if DEFAULT_QUAL_FLAGS != (QUAL_TRACE | QUAL_ABBREV | QUAL_VERBOSE)
1648 # error Bug in DEFAULT_QUAL_FLAGS
1650 qualify("signal=all");
1651 while ((c = getopt(argc, argv,
1652 "+b:cCdfFhiqrtTvVxyz"
1654 "a:e:o:O:p:s:S:u:E:P:I:")) != EOF) {
1657 if (strcmp(optarg, "execve") != 0)
1658 error_msg_and_die("Syscall '%s' for -b isn't supported",
1660 detach_on_execve = 1;
1663 if (cflag == CFLAG_BOTH) {
1664 error_msg_and_die("-c and -C are mutually exclusive");
1666 cflag = CFLAG_ONLY_STATS;
1669 if (cflag == CFLAG_ONLY_STATS) {
1670 error_msg_and_die("-c and -C are mutually exclusive");
1678 daemonized_tracer = 1;
1697 /* fall through to tflag++ */
1711 qualify("abbrev=none");
1714 printf("%s -- version %s\n", PACKAGE_NAME, VERSION);
1718 not_failing_only = 1;
1721 acolumn = string_to_uint(optarg);
1723 error_opt_arg(c, optarg);
1729 outfname = strdup(optarg);
1732 i = string_to_uint(optarg);
1734 error_opt_arg(c, optarg);
1738 process_opt_p_list(optarg);
1741 pathtrace_select(optarg);
1744 i = string_to_uint(optarg);
1746 error_opt_arg(c, optarg);
1753 username = strdup(optarg);
1756 if (putenv(optarg) < 0)
1757 die_out_of_memory();
1760 opt_intr = string_to_uint(optarg);
1761 if (opt_intr <= 0 || opt_intr >= NUM_INTR_OPTS)
1762 error_opt_arg(c, optarg);
1770 /* argc -= optind; - no need, argc is not used below */
1772 acolumn_spaces = malloc(acolumn + 1);
1773 if (!acolumn_spaces)
1774 die_out_of_memory();
1775 memset(acolumn_spaces, ' ', acolumn);
1776 acolumn_spaces[acolumn] = '\0';
1778 /* Must have PROG [ARGS], or -p PID. Not both. */
1779 if (!argv[0] == !nprocs)
1782 if (nprocs != 0 && daemonized_tracer) {
1783 error_msg_and_die("-D and -p are mutually exclusive");
1789 if (followfork >= 2 && cflag) {
1790 error_msg_and_die("(-c or -C) and -ff are mutually exclusive");
1793 /* See if they want to run as another user. */
1794 if (username != NULL) {
1795 struct passwd *pent;
1797 if (getuid() != 0 || geteuid() != 0) {
1798 error_msg_and_die("You must be root to use the -u option");
1800 pent = getpwnam(username);
1802 error_msg_and_die("Cannot find user '%s'", username);
1804 run_uid = pent->pw_uid;
1805 run_gid = pent->pw_gid;
1813 * On any reasonably recent Linux kernel (circa about 2.5.46)
1814 * need_fork_exec_workarounds should stay 0 after these tests:
1816 /*need_fork_exec_workarounds = 0; - already is */
1818 need_fork_exec_workarounds = test_ptrace_setoptions_followfork();
1819 need_fork_exec_workarounds |= test_ptrace_setoptions_for_all();
1820 test_ptrace_seize();
1822 /* Check if they want to redirect the output. */
1824 /* See if they want to pipe the output. */
1825 if (outfname[0] == '|' || outfname[0] == '!') {
1827 * We can't do the <outfname>.PID funny business
1828 * when using popen, so prohibit it.
1830 if (followfork >= 2)
1831 error_msg_and_die("Piping the output and -ff are mutually exclusive");
1832 shared_log = strace_popen(outfname + 1);
1834 else if (followfork < 2)
1835 shared_log = strace_fopen(outfname);
1837 /* -ff without -o FILE is the same as single -f */
1838 if (followfork >= 2)
1842 if (!outfname || outfname[0] == '|' || outfname[0] == '!') {
1843 char *buf = malloc(BUFSIZ);
1845 die_out_of_memory();
1846 setvbuf(shared_log, buf, _IOLBF, BUFSIZ);
1848 if (outfname && argv[0]) {
1850 opt_intr = INTR_NEVER;
1854 opt_intr = INTR_WHILE_WAIT;
1856 /* argv[0] -pPID -oFILE Default interactive setting
1857 * yes 0 0 INTR_WHILE_WAIT
1858 * no 1 0 INTR_WHILE_WAIT
1859 * yes 0 1 INTR_NEVER
1860 * no 1 1 INTR_WHILE_WAIT
1863 sigemptyset(&empty_set);
1864 sigemptyset(&blocked_set);
1866 /* startup_child() must be called before the signal handlers get
1867 * installed below as they are inherited into the spawned process.
1868 * Also we do not need to be protected by them as during interruption
1869 * in the startup_child() mode we kill the spawned process anyway.
1872 if (!NOMMU_SYSTEM || daemonized_tracer)
1873 hide_log_until_execve = 1;
1874 skip_one_b_execve = 1;
1875 startup_child(argv);
1878 sa.sa_handler = SIG_IGN;
1879 sigemptyset(&sa.sa_mask);
1881 sigaction(SIGTTOU, &sa, NULL); /* SIG_IGN */
1882 sigaction(SIGTTIN, &sa, NULL); /* SIG_IGN */
1883 if (opt_intr != INTR_ANYWHERE) {
1884 if (opt_intr == INTR_BLOCK_TSTP_TOO)
1885 sigaction(SIGTSTP, &sa, NULL); /* SIG_IGN */
1887 * In interactive mode (if no -o OUTFILE, or -p PID is used),
1888 * fatal signals are blocked while syscall stop is processed,
1889 * and acted on in between, when waiting for new syscall stops.
1890 * In non-interactive mode, signals are ignored.
1892 if (opt_intr == INTR_WHILE_WAIT) {
1893 sigaddset(&blocked_set, SIGHUP);
1894 sigaddset(&blocked_set, SIGINT);
1895 sigaddset(&blocked_set, SIGQUIT);
1896 sigaddset(&blocked_set, SIGPIPE);
1897 sigaddset(&blocked_set, SIGTERM);
1898 sa.sa_handler = interrupt;
1900 /* SIG_IGN, or set handler for these */
1901 sigaction(SIGHUP, &sa, NULL);
1902 sigaction(SIGINT, &sa, NULL);
1903 sigaction(SIGQUIT, &sa, NULL);
1904 sigaction(SIGPIPE, &sa, NULL);
1905 sigaction(SIGTERM, &sa, NULL);
1907 if (nprocs != 0 || daemonized_tracer)
1910 /* Do we want pids printed in our -o OUTFILE?
1911 * -ff: no (every pid has its own file); or
1912 * -f: yes (there can be more pids in the future); or
1913 * -p PID1,PID2: yes (there are already more than one pid)
1915 print_pid_pfx = (outfname && followfork < 2 && (followfork == 1 || nprocs > 1));
1926 for (i = 0; i < tcbtabsize; i++) {
1927 struct tcb *tcp = tcbtab[i];
1928 if (tcp->pid == pid)
1942 /* 'interrupted' is a volatile object, fetch it only once */
1943 fatal_sig = interrupted;
1945 fatal_sig = SIGTERM;
1947 for (i = 0; i < tcbtabsize; i++) {
1953 "cleanup: looking at pid %u\n", tcp->pid);
1954 if (tcp->pid == strace_child) {
1955 kill(tcp->pid, SIGCONT);
1956 kill(tcp->pid, fatal_sig);
1961 call_summary(shared_log);
1975 /* Used to be "while (nprocs != 0)", but in this testcase:
1976 * int main() { _exit(!!fork()); }
1977 * under strace -f, parent sometimes (rarely) manages
1978 * to exit before we see the first stop of the child,
1979 * and we are losing track of it:
1980 * 19923 clone(...) = 19924
1981 * 19923 exit_group(1) = ?
1982 * 19923 +++ exited with 1 +++
1983 * Waiting for ECHILD works better.
1984 * (However, if -o|logger is in use, we can't do that.
1985 * Can work around that by double-forking the logger,
1986 * but that loses the ability to wait for its completion on exit.
2000 if (popen_pid != 0 && nprocs == 0)
2004 sigprocmask(SIG_SETMASK, &empty_set, NULL);
2005 pid = wait4(-1, &status, __WALL, (cflag ? &ru : NULL));
2008 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
2011 if (wait_errno == EINTR)
2013 if (nprocs == 0 && wait_errno == ECHILD)
2015 /* If nprocs > 0, ECHILD is not expected,
2016 * treat it as any other error here:
2019 perror_msg_and_die("wait4(__WALL)");
2022 if (pid == popen_pid) {
2023 if (!WIFSTOPPED(status))
2028 event = ((unsigned)status >> 16);
2030 char buf[sizeof("WIFEXITED,exitcode=%u") + sizeof(int)*3 /*paranoia:*/ + 16];
2031 char evbuf[sizeof(",EVENT_VFORK_DONE (%u)") + sizeof(int)*3 /*paranoia:*/ + 16];
2033 if (WIFSIGNALED(status))
2035 sprintf(buf, "WIFSIGNALED,%ssig=%s",
2036 WCOREDUMP(status) ? "core," : "",
2037 signame(WTERMSIG(status)));
2039 sprintf(buf, "WIFSIGNALED,sig=%s",
2040 signame(WTERMSIG(status)));
2042 if (WIFEXITED(status))
2043 sprintf(buf, "WIFEXITED,exitcode=%u", WEXITSTATUS(status));
2044 if (WIFSTOPPED(status))
2045 sprintf(buf, "WIFSTOPPED,sig=%s", signame(WSTOPSIG(status)));
2047 /* Should never be seen */
2048 if (WIFCONTINUED(status))
2049 strcpy(buf, "WIFCONTINUED");
2053 static const char *const event_names[] = {
2054 [PTRACE_EVENT_CLONE] = "CLONE",
2055 [PTRACE_EVENT_FORK] = "FORK",
2056 [PTRACE_EVENT_VFORK] = "VFORK",
2057 [PTRACE_EVENT_VFORK_DONE] = "VFORK_DONE",
2058 [PTRACE_EVENT_EXEC] = "EXEC",
2059 [PTRACE_EVENT_EXIT] = "EXIT",
2060 /* [PTRACE_EVENT_STOP (=128)] would make biggish array */
2062 const char *e = "??";
2063 if (event < ARRAY_SIZE(event_names))
2064 e = event_names[event];
2065 else if (event == PTRACE_EVENT_STOP)
2067 sprintf(evbuf, ",EVENT_%s (%u)", e, event);
2069 fprintf(stderr, " [wait(0x%06x) = %u] %s%s\n", status, pid, buf, evbuf);
2072 /* Look up 'pid' in our table. */
2076 if (!WIFSTOPPED(status)) {
2077 /* This can happen if we inherited
2078 * an unknown child. Example:
2079 * (sleep 1 & exec strace sleep 2)
2081 error_msg("Exit of unknown pid %u seen", pid);
2085 /* We assume it's a fork/vfork/clone child */
2086 tcp = alloctcb(pid);
2087 tcp->flags |= TCB_ATTACHED | TCB_STARTUP | post_attach_sigstop;
2090 fprintf(stderr, "Process %d attached\n",
2093 /* This can happen if a clone call used
2094 * CLONE_PTRACE itself.
2096 ptrace(PTRACE_CONT, pid, (char *) 0, 0);
2097 error_msg("Stop of unknown pid %u seen, PTRACE_CONTed it", pid);
2103 if (WIFSTOPPED(status))
2106 /* Under Linux, execve changes pid to thread leader's pid,
2107 * and we see this changed pid on EVENT_EXEC and later,
2108 * execve sysexit. Leader "disappears" without exit
2109 * notification. Let user know that, drop leader's tcb,
2110 * and fix up pid in execve thread's tcb.
2111 * Effectively, execve thread's tcb replaces leader's tcb.
2113 * BTW, leader is 'stuck undead' (doesn't report WIFEXITED
2114 * on exit syscall) in multithreaded programs exactly
2115 * in order to handle this case.
2117 * PTRACE_GETEVENTMSG returns old pid starting from Linux 3.0.
2118 * On 2.6 and earlier, it can return garbage.
2120 if (event == PTRACE_EVENT_EXEC && os_release >= KERNEL_VERSION(3,0,0)) {
2122 struct tcb *execve_thread;
2125 if (ptrace(PTRACE_GETEVENTMSG, pid, NULL, (long) &old_pid) < 0)
2126 goto dont_switch_tcbs;
2127 /* Avoid truncation in pid2tcb() param passing */
2128 if (old_pid > UINT_MAX)
2129 goto dont_switch_tcbs;
2130 if (old_pid <= 0 || old_pid == pid)
2131 goto dont_switch_tcbs;
2132 execve_thread = pid2tcb(old_pid);
2133 /* It should be !NULL, but I feel paranoid */
2135 goto dont_switch_tcbs;
2137 if (execve_thread->curcol != 0) {
2139 * One case we are here is -ff:
2140 * try "strace -oLOG -ff test/threaded_execve"
2142 fprintf(execve_thread->outf, " <pid changed to %d ...>\n", pid);
2143 /*execve_thread->curcol = 0; - no need, see code below */
2145 /* Swap output FILEs (needed for -ff) */
2146 fp = execve_thread->outf;
2147 execve_thread->outf = tcp->outf;
2149 /* And their column positions */
2150 execve_thread->curcol = tcp->curcol;
2152 /* Drop leader, but close execve'd thread outfile (if -ff) */
2154 /* Switch to the thread, reusing leader's outfile and pid */
2155 tcp = execve_thread;
2157 if (cflag != CFLAG_ONLY_STATS) {
2159 tprintf("+++ superseded by execve in pid %lu +++\n", old_pid);
2161 tcp->flags |= TCB_REPRINT;
2166 if (event == PTRACE_EVENT_EXEC) {
2167 if (detach_on_execve && !skip_one_b_execve)
2168 detach(tcp); /* do "-b execve" thingy */
2169 skip_one_b_execve = 0;
2172 /* Set current output file */
2176 tv_sub(&tcp->dtime, &ru.ru_stime, &tcp->stime);
2177 tcp->stime = ru.ru_stime;
2180 if (WIFSIGNALED(status)) {
2181 if (pid == strace_child)
2182 exit_code = 0x100 | WTERMSIG(status);
2183 if (cflag != CFLAG_ONLY_STATS
2184 && (qual_flags[WTERMSIG(status)] & QUAL_SIGNAL)
2188 tprintf("+++ killed by %s %s+++\n",
2189 signame(WTERMSIG(status)),
2190 WCOREDUMP(status) ? "(core dumped) " : "");
2192 tprintf("+++ killed by %s +++\n",
2193 signame(WTERMSIG(status)));
2200 if (WIFEXITED(status)) {
2201 if (pid == strace_child)
2202 exit_code = WEXITSTATUS(status);
2203 if (cflag != CFLAG_ONLY_STATS &&
2206 tprintf("+++ exited with %d +++\n", WEXITSTATUS(status));
2212 if (!WIFSTOPPED(status)) {
2213 fprintf(stderr, "PANIC: pid %u not stopped\n", pid);
2218 /* Is this the very first time we see this tracee stopped? */
2219 if (tcp->flags & TCB_STARTUP) {
2221 fprintf(stderr, "pid %d has TCB_STARTUP, initializing it\n", tcp->pid);
2222 tcp->flags &= ~TCB_STARTUP;
2223 if (tcp->flags & TCB_BPTSET) {
2225 * One example is a breakpoint inherited from
2226 * parent through fork().
2228 if (clearbpt(tcp) < 0) {
2235 if (!use_seize && ptrace_setoptions) {
2237 fprintf(stderr, "setting opts 0x%x on pid %d\n", ptrace_setoptions, tcp->pid);
2238 if (ptrace(PTRACE_SETOPTIONS, tcp->pid, NULL, ptrace_setoptions) < 0) {
2239 if (errno != ESRCH) {
2240 /* Should never happen, really */
2241 perror_msg_and_die("PTRACE_SETOPTIONS");
2247 sig = WSTOPSIG(status);
2252 if (event == PTRACE_EVENT_STOP) {
2254 * PTRACE_INTERRUPT-stop or group-stop.
2255 * PTRACE_INTERRUPT-stop has sig == SIGTRAP here.
2267 goto restart_tracee_with_sig_0;
2270 /* Is this post-attach SIGSTOP?
2271 * Interestingly, the process may stop
2272 * with STOPSIG equal to some other signal
2273 * than SIGSTOP if we happend to attach
2274 * just before the process takes a signal.
2276 if (sig == SIGSTOP && (tcp->flags & TCB_IGNORE_ONE_SIGSTOP)) {
2278 fprintf(stderr, "ignored SIGSTOP on pid %d\n", tcp->pid);
2279 tcp->flags &= ~TCB_IGNORE_ONE_SIGSTOP;
2280 goto restart_tracee_with_sig_0;
2283 if (sig != syscall_trap_sig) {
2286 /* Nonzero (true) if tracee is stopped by signal
2287 * (as opposed to "tracee received signal").
2288 * TODO: shouldn't we check for errno == EINVAL too?
2289 * We can get ESRCH instead, you know...
2291 stopped = (ptrace(PTRACE_GETSIGINFO, pid, 0, (long) &si) < 0);
2295 if (cflag != CFLAG_ONLY_STATS
2296 && !hide_log_until_execve
2297 && (qual_flags[sig] & QUAL_SIGNAL)
2301 tprintf("--- %s ", signame(sig));
2302 printsiginfo(&si, verbose(tcp));
2305 tprintf("--- stopped by %s ---\n",
2311 /* It's signal-delivery-stop. Inject the signal */
2312 goto restart_tracee;
2314 /* It's group-stop */
2317 * This ends ptrace-stop, but does *not* end group-stop.
2318 * This makes stopping signals work properly on straced process
2319 * (that is, process really stops. It used to continue to run).
2321 if (ptrace_restart(PTRACE_LISTEN, tcp, 0) < 0) {
2322 /* Note: ptrace_restart emitted error message */
2328 /* We don't have PTRACE_LISTEN support... */
2329 goto restart_tracee;
2332 /* We handled quick cases, we are permitted to interrupt now. */
2336 /* This should be syscall entry or exit.
2337 * (Or it still can be that pesky post-execve SIGTRAP!)
2340 if (trace_syscall(tcp) < 0) {
2341 /* ptrace() failed in trace_syscall().
2342 * Likely a result of process disappearing mid-flight.
2343 * Observed case: exit_group() or SIGKILL terminating
2344 * all processes in thread group.
2345 * We assume that ptrace error was caused by process death.
2346 * We used to detach(tcp) here, but since we no longer
2347 * implement "detach before death" policy/hack,
2348 * we can let this process to report its death to us
2349 * normally, via WIFEXITED or WIFSIGNALED wait status.
2353 restart_tracee_with_sig_0:
2356 if (ptrace_restart(PTRACE_SYSCALL, tcp, sig) < 0) {
2357 /* Note: ptrace_restart emitted error message */
2365 main(int argc, char *argv[])
2369 /* Run main tracing loop */
2374 if (shared_log != stderr)
2377 while (waitpid(popen_pid, NULL, 0) < 0 && errno == EINTR)
2380 if (exit_code > 0xff) {
2381 /* Avoid potential core file clobbering. */
2382 struct_rlimit rlim = {0, 0};
2383 set_rlimit(RLIMIT_CORE, &rlim);
2385 /* Child was killed by a signal, mimic that. */
2387 signal(exit_code, SIG_DFL);
2389 /* Paranoia - what if this signal is not fatal?
2390 Exit with 128 + signo then. */