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>
6 * Copyright (c) 1999-2017 The strace developers.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. The name of the author may not be used to endorse or promote products
18 * derived from this software without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
21 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
22 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
23 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
24 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
25 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
29 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 #include <sys/param.h>
37 #include <sys/resource.h>
46 #include <sys/utsname.h>
48 # include <sys/prctl.h>
50 #include <asm/unistd.h>
52 #include "number_set.h"
55 #include "printsiginfo.h"
56 #include "trace_event.h"
59 /* In some libc, these aren't declared. Do it ourself: */
60 extern char **environ;
65 /* if this is true do the stack trace for every system call */
66 bool stack_trace_enabled;
69 #define my_tkill(tid, sig) syscall(__NR_tkill, (tid), (sig))
71 /* Glue for systems without a MMU that cannot provide fork() */
72 #if !defined(HAVE_FORK)
74 # define NOMMU_SYSTEM 1
77 # define fork() vfork()
80 const unsigned int syscall_trap_sig = SIGTRAP | 0x80;
82 cflag_t cflag = CFLAG_NONE;
83 unsigned int followfork;
84 unsigned int ptrace_setoptions = PTRACE_O_TRACESYSGOOD | PTRACE_O_TRACEEXEC
92 static unsigned int tflag;
94 static bool print_pid_pfx;
99 INTR_ANYWHERE = 1, /* don't block/ignore any signals */
100 INTR_WHILE_WAIT = 2, /* block fatal signals while decoding syscall. default */
101 INTR_NEVER = 3, /* block fatal signals. default if '-o FILE PROG' */
102 INTR_BLOCK_TSTP_TOO = 4, /* block fatal signals and SIGTSTP (^Z) */
106 /* We play with signal mask only if this mode is active: */
107 #define interactive (opt_intr == INTR_WHILE_WAIT)
110 * daemonized_tracer supports -D option.
111 * With this option, strace forks twice.
112 * Unlike normal case, with -D *grandparent* process exec's,
113 * becoming a traced process. Child exits (this prevents traced process
114 * from having children it doesn't expect to have), and grandchild
115 * attaches to grandparent similarly to strace -p PID.
116 * This allows for more transparent interaction in cases
117 * when process and its parent are communicating via signals,
118 * wait() etc. Without -D, strace process gets lodged in between,
119 * disrupting parent<->child link.
121 static bool daemonized_tracer;
124 static int post_attach_sigstop = TCB_IGNORE_ONE_SIGSTOP;
125 # define use_seize (post_attach_sigstop == 0)
127 # define post_attach_sigstop TCB_IGNORE_ONE_SIGSTOP
131 /* Sometimes we want to print only succeeding syscalls. */
132 bool not_failing_only;
134 /* Show path associated with fd arguments */
135 unsigned int show_fd_path;
137 static bool detach_on_execve;
139 static int exit_code;
140 static int strace_child;
141 static int strace_tracer_pid;
143 static const char *username;
144 static uid_t run_uid;
145 static gid_t run_gid;
147 unsigned int max_strlen = DEFAULT_STRLEN;
148 static int acolumn = DEFAULT_ACOLUMN;
149 static char *acolumn_spaces;
151 static const char *outfname;
152 /* If -ff, points to stderr. Else, it's our common output log */
153 static FILE *shared_log;
155 struct tcb *printing_tcp;
156 static struct tcb *current_tcp;
158 static struct tcb **tcbtab;
159 static unsigned int nprocs;
160 static size_t tcbtabsize;
162 #ifndef HAVE_PROGRAM_INVOCATION_NAME
163 char *program_invocation_name;
166 unsigned os_release; /* generated from uname()'s u.release */
168 static void detach(struct tcb *tcp);
169 static void cleanup(void);
170 static void interrupt(int sig);
171 static sigset_t start_set, blocked_set;
173 #ifdef HAVE_SIG_ATOMIC_T
174 static volatile sig_atomic_t interrupted;
176 static volatile int interrupted;
179 #ifndef HAVE_STRERROR
181 #if !HAVE_DECL_SYS_ERRLIST
183 extern char *sys_errlist[];
189 static char buf[sizeof("Unknown error %d") + sizeof(int)*3];
191 if (err_no < 1 || err_no >= sys_nerr) {
192 xsprintf(buf, "Unknown error %d", err_no);
195 return sys_errlist[err_no];
198 #endif /* HAVE_STERRROR */
203 static const char features[] =
206 #endif /* USE_LIBUNWIND */
209 printf("%s -- version %s\n"
210 "Copyright (c) 1991-%s The strace developers <%s>.\n"
211 "This is free software; see the source for copying conditions. There is NO\n"
212 "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n",
213 PACKAGE_NAME, PACKAGE_VERSION, COPYRIGHT_YEAR, PACKAGE_URL);
214 printf("\nOptional features enabled:%s\n",
215 features[0] ? features : " (none)");
222 usage: strace [-CdffhiqrtttTvVwxxy] [-I n] [-e expr]...\n\
223 [-a column] [-o file] [-s strsize] [-P path]...\n\
224 -p pid... / [-D] [-E var=val]... [-u username] PROG [ARGS]\n\
225 or: strace -c[dfw] [-I n] [-e expr]... [-O overhead] [-S sortby]\n\
226 -p pid... / [-D] [-E var=val]... [-u username] PROG [ARGS]\n\
229 -a column alignment COLUMN for printing syscall results (default %d)\n\
230 -i print instruction pointer at time of syscall\n\
234 -k obtain stack trace between each syscall (experimental)\n\
238 -o file send trace output to FILE instead of stderr\n\
239 -q suppress messages about attaching, detaching, etc.\n\
240 -r print relative timestamp\n\
241 -s strsize limit length of print strings to STRSIZE chars (default %d)\n\
242 -t print absolute timestamp\n\
243 -tt print absolute timestamp with usecs\n\
244 -T print time spent in each syscall\n\
245 -x print non-ascii strings in hex\n\
246 -xx print all strings in hex\n\
247 -y print paths associated with file descriptor arguments\n\
248 -yy print protocol specific information associated with socket file descriptors\n\
251 -c count time, calls, and errors for each syscall and report summary\n\
252 -C like -c but also print regular output\n\
253 -O overhead set overhead for tracing syscalls to OVERHEAD usecs\n\
254 -S sortby sort syscall counts by: time, calls, name, nothing (default %s)\n\
255 -w summarise syscall latency (default is system time)\n\
258 -e expr a qualifying expression: option=[!]all or option=[!]val1[,val2]...\n\
259 options: trace, abbrev, verbose, raw, signal, read, write, fault\n\
260 -P path trace accesses to path\n\
263 -b execve detach on execve syscall\n\
264 -D run tracer process as a detached grandchild, not as parent\n\
266 -ff follow forks with output into separate files\n\
268 1: no signals are blocked\n\
269 2: fatal signals are blocked while decoding syscall (default)\n\
270 3: fatal signals are always blocked (default if '-o FILE PROG')\n\
271 4: fatal signals and SIGTSTP (^Z) are always blocked\n\
272 (useful to make 'strace -o FILE PROG' not stop on ^Z)\n\
275 -E var remove var from the environment for command\n\
276 -E var=val put var=val in the environment for command\n\
277 -p pid trace process with process id PID, may be repeated\n\
278 -u username run command as username handling setuid and/or setgid\n\
281 -d enable debug output to stderr\n\
282 -v verbose mode: print unabbreviated argv, stat, termios, etc. args\n\
283 -h print help message\n\
286 /* ancient, no one should use it
287 -F -- attempt to follow vforks (deprecated, use -f)\n\
289 /* this is broken, so don't document it
290 -z -- print only succeeding syscalls\n\
292 , DEFAULT_ACOLUMN, DEFAULT_STRLEN, DEFAULT_SORTBY);
296 void ATTRIBUTE_NORETURN
299 if (strace_tracer_pid == getpid()) {
309 error_opt_arg(int opt, const char *arg)
311 error_msg_and_help("invalid -%c argument: '%s'", opt, arg);
314 static const char *ptrace_attach_cmd;
317 ptrace_attach_or_seize(int pid)
322 return ptrace_attach_cmd = "PTRACE_ATTACH",
323 ptrace(PTRACE_ATTACH, pid, 0L, 0L);
324 r = ptrace(PTRACE_SEIZE, pid, 0L, (unsigned long) ptrace_setoptions);
326 return ptrace_attach_cmd = "PTRACE_SEIZE", r;
327 r = ptrace(PTRACE_INTERRUPT, pid, 0L, 0L);
328 return ptrace_attach_cmd = "PTRACE_INTERRUPT", r;
330 return ptrace_attach_cmd = "PTRACE_ATTACH",
331 ptrace(PTRACE_ATTACH, pid, 0L, 0L);
336 * Used when we want to unblock stopped traced process.
337 * Should be only used with PTRACE_CONT, PTRACE_DETACH and PTRACE_SYSCALL.
338 * Returns 0 on success or if error was ESRCH
339 * (presumably process was killed while we talk to it).
340 * Otherwise prints error message and returns -1.
343 ptrace_restart(const unsigned int op, struct tcb *const tcp, unsigned int sig)
349 ptrace(op, tcp->pid, 0L, (unsigned long) sig);
369 * Why curcol != 0? Otherwise sometimes we get this:
371 * 10252 kill(10253, SIGKILL) = 0
372 * <ptrace(SYSCALL,10252):No such process>10253 ...next decode...
374 * 10252 died after we retrieved syscall exit data,
375 * but before we tried to restart it. Log looks ugly.
377 if (current_tcp && current_tcp->curcol != 0) {
378 tprintf(" <ptrace(%s):%s>\n", msg, strerror(err));
384 perror_msg("ptrace(PTRACE_%s,pid:%d,sig:%u)", msg, tcp->pid, sig);
389 set_cloexec_flag(int fd)
393 flags = fcntl(fd, F_GETFD);
395 /* Can happen only if fd is bad.
396 * Should never happen: if it does, we have a bug
397 * in the caller. Therefore we just abort
398 * instead of propagating the error.
400 perror_msg_and_die("fcntl(%d, F_GETFD)", fd);
403 newflags = flags | FD_CLOEXEC;
404 if (flags == newflags)
407 fcntl(fd, F_SETFD, newflags); /* never fails */
411 kill_save_errno(pid_t pid, int sig)
413 int saved_errno = errno;
415 (void) kill(pid, sig);
420 * When strace is setuid executable, we have to swap uids
421 * before and after filesystem and process management operations.
426 int euid = geteuid(), uid = getuid();
428 if (euid != uid && setreuid(euid, uid) < 0) {
429 perror_msg_and_die("setreuid");
433 #ifdef _LARGEFILE64_SOURCE
435 # define fopen_for_output fopen64
437 # define fopen_for_output fopen
439 # define struct_stat struct stat64
440 # define stat_file stat64
441 # define struct_dirent struct dirent64
442 # define read_dir readdir64
443 # define struct_rlimit struct rlimit64
444 # define set_rlimit setrlimit64
446 # define fopen_for_output fopen
447 # define struct_stat struct stat
448 # define stat_file stat
449 # define struct_dirent struct dirent
450 # define read_dir readdir
451 # define struct_rlimit struct rlimit
452 # define set_rlimit setrlimit
456 strace_fopen(const char *path)
461 fp = fopen_for_output(path, "w");
463 perror_msg_and_die("Can't fopen '%s'", path);
465 set_cloexec_flag(fileno(fp));
469 static int popen_pid;
472 # define _PATH_BSHELL "/bin/sh"
476 * We cannot use standard popen(3) here because we have to distinguish
477 * popen child process from other processes we trace, and standard popen(3)
478 * does not export its child's pid.
481 strace_popen(const char *command)
489 perror_msg_and_die("pipe");
491 set_cloexec_flag(fds[1]); /* never fails */
495 perror_msg_and_die("vfork");
502 perror_msg_and_die("dup2");
505 execl(_PATH_BSHELL, "sh", "-c", command, NULL);
506 perror_msg_and_die("Can't execute '%s'", _PATH_BSHELL);
513 fp = fdopen(fds[1], "w");
515 perror_msg_and_die("fdopen");
519 ATTRIBUTE_FORMAT((printf, 1, 0))
521 tvprintf(const char *const fmt, va_list args)
524 int n = vfprintf(current_tcp->outf, fmt, args);
526 /* very unlikely due to vfprintf buffering */
527 if (current_tcp->outf != stderr)
528 perror_msg("%s", outfname);
530 current_tcp->curcol += n;
535 tprintf(const char *fmt, ...)
543 #ifndef HAVE_FPUTS_UNLOCKED
544 # define fputs_unlocked fputs
548 tprints(const char *str)
551 int n = fputs_unlocked(str, current_tcp->outf);
553 current_tcp->curcol += strlen(str);
556 /* very unlikely due to fputs_unlocked buffering */
557 if (current_tcp->outf != stderr)
558 perror_msg("%s", outfname);
563 tprints_comment(const char *const str)
566 tprintf(" /* %s */", str);
570 tprintf_comment(const char *fmt, ...)
584 flush_tcp_output(const struct tcb *const tcp)
586 if (fflush(tcp->outf) && tcp->outf != stderr)
587 perror_msg("%s", outfname);
594 current_tcp->curcol = 0;
595 flush_tcp_output(current_tcp);
598 printing_tcp->curcol = 0;
604 printleader(struct tcb *tcp)
606 /* If -ff, "previous tcb we printed" is always the same as current,
607 * because we have per-tcb output files.
613 current_tcp = printing_tcp;
614 if (printing_tcp->curcol != 0 && (followfork < 2 || printing_tcp == tcp)) {
616 * case 1: we have a shared log (i.e. not -ff), and last line
617 * wasn't finished (same or different tcb, doesn't matter).
618 * case 2: split log, we are the same tcb, but our last line
619 * didn't finish ("SIGKILL nuked us after syscall entry" etc).
621 tprints(" <unfinished ...>\n");
622 printing_tcp->curcol = 0;
628 current_tcp->curcol = 0;
631 tprintf("%-5d ", tcp->pid);
632 else if (nprocs > 1 && !outfname)
633 tprintf("[pid %5u] ", tcp->pid);
636 char str[sizeof("HH:MM:SS")];
637 struct timeval tv, dtv;
638 static struct timeval otv;
640 gettimeofday(&tv, NULL);
644 tv_sub(&dtv, &tv, &otv);
645 tprintf("%6ld.%06ld ",
646 (long) dtv.tv_sec, (long) dtv.tv_usec);
648 } else if (tflag > 2) {
649 tprintf("%ld.%06ld ",
650 (long) tv.tv_sec, (long) tv.tv_usec);
652 time_t local = tv.tv_sec;
653 strftime(str, sizeof(str), "%T", localtime(&local));
655 tprintf("%s.%06ld ", str, (long) tv.tv_usec);
667 if (current_tcp->curcol < acolumn)
668 tprints(acolumn_spaces + current_tcp->curcol);
671 /* Should be only called directly *after successful attach* to a tracee.
672 * Otherwise, "strace -oFILE -ff -p<nonexistant_pid>"
673 * may create bogus empty FILE.<nonexistant_pid>, and then die.
676 newoutf(struct tcb *tcp)
678 tcp->outf = shared_log; /* if not -ff mode, the same file is for all */
679 if (followfork >= 2) {
681 xsprintf(name, "%s.%u", outfname, tcp->pid);
682 tcp->outf = strace_fopen(name);
689 /* Allocate some (more) TCBs (and expand the table).
690 We don't want to relocate the TCBs because our
691 callers have pointers and it would be a pain.
692 So tcbtab is a table of pointers. Since we never
693 free the TCBs, we allocate a single chunk of many. */
694 size_t old_tcbtabsize;
696 struct tcb **tcb_ptr;
698 old_tcbtabsize = tcbtabsize;
700 tcbtab = xgrowarray(tcbtab, &tcbtabsize, sizeof(tcbtab[0]));
701 newtcbs = xcalloc(tcbtabsize - old_tcbtabsize, sizeof(newtcbs[0]));
703 for (tcb_ptr = tcbtab + old_tcbtabsize;
704 tcb_ptr < tcbtab + tcbtabsize; tcb_ptr++, newtcbs++)
714 if (nprocs == tcbtabsize)
717 for (i = 0; i < tcbtabsize; i++) {
720 memset(tcp, 0, sizeof(*tcp));
722 #if SUPPORTED_PERSONALITIES > 1
723 tcp->currpers = current_personality;
727 if (stack_trace_enabled)
728 unwind_tcb_init(tcp);
732 debug_msg("new tcb for pid %d, active tcbs:%d",
737 error_msg_and_die("bug in alloctcb");
741 get_tcb_priv_data(const struct tcb *tcp)
743 return tcp->_priv_data;
747 set_tcb_priv_data(struct tcb *tcp, void *const priv_data,
748 void (*const free_priv_data)(void *))
753 tcp->_free_priv_data = free_priv_data;
754 tcp->_priv_data = priv_data;
760 free_tcb_priv_data(struct tcb *tcp)
762 if (tcp->_priv_data) {
763 if (tcp->_free_priv_data) {
764 tcp->_free_priv_data(tcp->_priv_data);
765 tcp->_free_priv_data = NULL;
767 tcp->_priv_data = NULL;
772 droptcb(struct tcb *tcp)
778 for (p = 0; p < SUPPORTED_PERSONALITIES; ++p)
779 free(tcp->inject_vec[p]);
781 free_tcb_priv_data(tcp);
784 if (stack_trace_enabled) {
790 debug_msg("dropped tcb for pid %d, %d remain", tcp->pid, nprocs);
793 if (followfork >= 2) {
794 if (tcp->curcol != 0)
795 fprintf(tcp->outf, " <detached ...>\n");
798 if (printing_tcp == tcp && tcp->curcol != 0)
799 fprintf(tcp->outf, " <detached ...>\n");
800 flush_tcp_output(tcp);
804 if (current_tcp == tcp)
806 if (printing_tcp == tcp)
809 memset(tcp, 0, sizeof(*tcp));
812 /* Detach traced process.
813 * Never call DETACH twice on the same process as both unattached and
814 * attached-unstopped processes give the same ESRCH. For unattached process we
815 * would SIGSTOP it and wait for its SIGSTOP notification forever.
818 detach(struct tcb *tcp)
824 * Linux wrongly insists the child be stopped
825 * before detaching. Arghh. We go through hoops
826 * to make a clean break of things.
829 if (!(tcp->flags & TCB_ATTACHED))
832 /* We attached but possibly didn't see the expected SIGSTOP.
833 * We must catch exactly one as otherwise the detached process
834 * would be left stopped (process state T).
836 if (tcp->flags & TCB_IGNORE_ONE_SIGSTOP)
839 error = ptrace(PTRACE_DETACH, tcp->pid, 0, 0);
841 /* On a clear day, you can see forever. */
844 if (errno != ESRCH) {
845 /* Shouldn't happen. */
846 perror_func_msg("ptrace(PTRACE_DETACH,%u)", tcp->pid);
849 /* ESRCH: process is either not stopped or doesn't exist. */
850 if (my_tkill(tcp->pid, 0) < 0) {
852 /* Shouldn't happen. */
853 perror_func_msg("tkill(%u,0)", tcp->pid);
854 /* else: process doesn't exist. */
857 /* Process is not stopped, need to stop it. */
860 * With SEIZE, tracee can be in group-stop already.
861 * In this state sending it another SIGSTOP does nothing.
862 * Need to use INTERRUPT.
863 * Testcase: trying to ^C a "strace -p <stopped_process>".
865 error = ptrace(PTRACE_INTERRUPT, tcp->pid, 0, 0);
869 perror_func_msg("ptrace(PTRACE_INTERRUPT,%u)", tcp->pid);
871 error = my_tkill(tcp->pid, SIGSTOP);
875 perror_func_msg("tkill(%u,SIGSTOP)", tcp->pid);
877 /* Either process doesn't exist, or some weird error. */
881 /* We end up here in three cases:
882 * 1. We sent PTRACE_INTERRUPT (use_seize case)
883 * 2. We sent SIGSTOP (!use_seize)
884 * 3. Attach SIGSTOP was already pending (TCB_IGNORE_ONE_SIGSTOP set)
888 if (waitpid(tcp->pid, &status, __WALL) < 0) {
892 * if (errno == ECHILD) break;
893 * ^^^ WRONG! We expect this PID to exist,
894 * and want to emit a message otherwise:
896 perror_func_msg("waitpid(%u)", tcp->pid);
899 if (!WIFSTOPPED(status)) {
901 * Tracee exited or was killed by signal.
902 * We shouldn't normally reach this place:
903 * we don't want to consume exit status.
904 * Consider "strace -p PID" being ^C-ed:
905 * we want merely to detach from PID.
907 * However, we _can_ end up here if tracee
912 sig = WSTOPSIG(status);
913 debug_msg("detach wait: event:%d sig:%d",
914 (unsigned) status >> 16, sig);
916 unsigned event = (unsigned)status >> 16;
917 if (event == PTRACE_EVENT_STOP /*&& sig == SIGTRAP*/) {
919 * sig == SIGTRAP: PTRACE_INTERRUPT stop.
920 * sig == other: process was already stopped
921 * with this stopping sig (see tests/detach-stopped).
922 * Looks like re-injecting this sig is not necessary
923 * in DETACH for the tracee to remain stopped.
928 * PTRACE_INTERRUPT is not guaranteed to produce
929 * the above event if other ptrace-stop is pending.
930 * See tests/detach-sleeping testcase:
931 * strace got SIGINT while tracee is sleeping.
932 * We sent PTRACE_INTERRUPT.
933 * We see syscall exit, not PTRACE_INTERRUPT stop.
934 * We won't get PTRACE_INTERRUPT stop
935 * if we would CONT now. Need to DETACH.
937 if (sig == syscall_trap_sig)
939 /* else: not sure in which case we can be here.
940 * Signal stop? Inject it while detaching.
942 ptrace_restart(PTRACE_DETACH, tcp, sig);
945 /* Note: this check has to be after use_seize check */
946 /* (else, in use_seize case SIGSTOP will be mistreated) */
947 if (sig == SIGSTOP) {
948 /* Detach, suppressing SIGSTOP */
949 ptrace_restart(PTRACE_DETACH, tcp, 0);
952 if (sig == syscall_trap_sig)
954 /* Can't detach just yet, may need to wait for SIGSTOP */
955 error = ptrace_restart(PTRACE_CONT, tcp, sig);
957 /* Should not happen.
958 * Note: ptrace_restart returns 0 on ESRCH, so it's not it.
959 * ptrace_restart already emitted error message.
966 if (!qflag && (tcp->flags & TCB_ATTACHED))
967 error_msg("Process %u detached", tcp->pid);
973 process_opt_p_list(char *opt)
977 * We accept -p PID,PID; -p "`pidof PROG`"; -p "`pgrep PROG`".
978 * pidof uses space as delim, pgrep uses newline. :(
981 char *delim = opt + strcspn(opt, "\n\t ,");
985 pid = string_to_uint(opt);
987 error_msg_and_die("Invalid process id: '%s'", opt);
989 if (pid == strace_tracer_pid) {
990 error_msg_and_die("I'm sorry, I can't let you do that, Dave.");
1001 attach_tcb(struct tcb *const tcp)
1003 if (ptrace_attach_or_seize(tcp->pid) < 0) {
1004 perror_msg("attach: ptrace(%s, %d)",
1005 ptrace_attach_cmd, tcp->pid);
1010 tcp->flags |= TCB_ATTACHED | TCB_GRABBED | TCB_STARTUP |
1011 post_attach_sigstop;
1013 debug_msg("attach to pid %d (main) succeeded", tcp->pid);
1015 static const char task_path[] = "/proc/%d/task";
1016 char procdir[sizeof(task_path) + sizeof(int) * 3];
1018 unsigned int ntid = 0, nerr = 0;
1020 if (followfork && tcp->pid != strace_child &&
1021 xsprintf(procdir, task_path, tcp->pid) > 0 &&
1022 (dir = opendir(procdir)) != NULL) {
1025 while ((de = read_dir(dir)) != NULL) {
1026 if (de->d_fileno == 0)
1029 int tid = string_to_uint(de->d_name);
1030 if (tid <= 0 || tid == tcp->pid)
1034 if (ptrace_attach_or_seize(tid) < 0) {
1036 debug_perror_msg("attach: ptrace(%s, %d)",
1037 ptrace_attach_cmd, tid);
1040 debug_msg("attach to pid %d succeeded", tid);
1042 struct tcb *tid_tcp = alloctcb(tid);
1043 tid_tcp->flags |= TCB_ATTACHED | TCB_GRABBED |
1044 TCB_STARTUP | post_attach_sigstop;
1053 error_msg("Process %u attached"
1055 tcp->pid, ntid - nerr + 1);
1057 error_msg("Process %u attached",
1063 startup_attach(void)
1065 pid_t parent_pid = strace_tracer_pid;
1070 * Block user interruptions as we would leave the traced
1071 * process stopped (process state T) if we would terminate in
1072 * between PTRACE_ATTACH and wait4() on SIGSTOP.
1073 * We rely on cleanup() from this point on.
1076 sigprocmask(SIG_SETMASK, &blocked_set, NULL);
1078 if (daemonized_tracer) {
1081 perror_func_msg_and_die("fork");
1083 if (pid) { /* parent */
1085 * Wait for grandchild to attach to straced process
1086 * (grandparent). Grandchild SIGKILLs us after it attached.
1087 * Grandparent's wait() is unblocked by our death,
1088 * it proceeds to exec the straced program.
1091 _exit(0); /* paranoia */
1094 /* We will be the tracer process. Remember our new pid: */
1095 strace_tracer_pid = getpid();
1098 for (tcbi = 0; tcbi < tcbtabsize; tcbi++) {
1104 /* Is this a process we should attach to, but not yet attached? */
1105 if (tcp->flags & TCB_ATTACHED)
1106 continue; /* no, we already attached it */
1108 if (tcp->pid == parent_pid || tcp->pid == strace_tracer_pid) {
1110 perror_msg("attach: pid %d", tcp->pid);
1118 sigprocmask(SIG_SETMASK, &start_set, NULL);
1121 sigprocmask(SIG_SETMASK, &blocked_set, NULL);
1123 } /* for each tcbtab[] */
1125 if (daemonized_tracer) {
1127 * Make parent go away.
1128 * Also makes grandparent's wait() unblock.
1130 kill(parent_pid, SIGKILL);
1136 sigprocmask(SIG_SETMASK, &start_set, NULL);
1139 /* Stack-o-phobic exec helper, in the hope to work around
1140 * NOMMU + "daemonized tracer" difficulty.
1142 struct exec_params {
1148 struct sigaction child_sa;
1150 static struct exec_params params_for_tracee;
1152 static void ATTRIBUTE_NOINLINE ATTRIBUTE_NORETURN
1155 struct exec_params *params = ¶ms_for_tracee;
1157 if (params->fd_to_close >= 0)
1158 close(params->fd_to_close);
1159 if (!daemonized_tracer && !use_seize) {
1160 if (ptrace(PTRACE_TRACEME, 0L, 0L, 0L) < 0) {
1161 perror_msg_and_die("ptrace(PTRACE_TRACEME, ...)");
1165 if (username != NULL) {
1167 * It is important to set groups before we
1168 * lose privileges on setuid.
1170 if (initgroups(username, run_gid) < 0) {
1171 perror_msg_and_die("initgroups");
1173 if (setregid(run_gid, params->run_egid) < 0) {
1174 perror_msg_and_die("setregid");
1176 if (setreuid(run_uid, params->run_euid) < 0) {
1177 perror_msg_and_die("setreuid");
1179 } else if (geteuid() != 0)
1180 if (setreuid(run_uid, run_uid) < 0) {
1181 perror_msg_and_die("setreuid");
1184 if (!daemonized_tracer) {
1186 * Induce a ptrace stop. Tracer (our parent)
1187 * will resume us with PTRACE_SYSCALL and display
1188 * the immediately following execve syscall.
1189 * Can't do this on NOMMU systems, we are after
1190 * vfork: parent is blocked, stopping would deadlock.
1193 kill(getpid(), SIGSTOP);
1196 /* we depend on SIGCHLD set to SIG_DFL by init code */
1197 /* if it happens to be SIG_IGN'ed, wait won't block */
1202 if (params_for_tracee.child_sa.sa_handler != SIG_DFL)
1203 sigaction(SIGCHLD, ¶ms_for_tracee.child_sa, NULL);
1205 execv(params->pathname, params->argv);
1206 perror_msg_and_die("exec");
1210 * Open a dummy descriptor for use as a placeholder.
1211 * The descriptor is O_RDONLY with FD_CLOEXEC flag set.
1212 * A read attempt from such descriptor ends with EOF,
1213 * a write attempt is rejected with EBADF.
1216 open_dummy_desc(void)
1221 perror_func_msg_and_die("pipe");
1223 set_cloexec_flag(fds[0]);
1227 /* placeholder fds status for stdin and stdout */
1228 static bool fd_is_placeholder[2];
1231 * Ensure that all standard file descriptors are open by opening placeholder
1232 * file descriptors for those standard file descriptors that are not open.
1234 * The information which descriptors have been made open is saved
1235 * in fd_is_placeholder for later use.
1238 ensure_standard_fds_opened(void)
1242 while ((fd = open_dummy_desc()) <= 2) {
1245 fd_is_placeholder[fd] = true;
1253 * Redirect stdin and stdout unless they have been opened earlier
1254 * by ensure_standard_fds_opened as placeholders.
1257 redirect_standard_fds(void)
1262 * It might be a good idea to redirect stderr as well,
1263 * but we sometimes need to print error messages.
1265 for (i = 0; i <= 1; ++i) {
1266 if (!fd_is_placeholder[i]) {
1274 startup_child(char **argv)
1276 struct_stat statbuf;
1277 const char *filename;
1278 size_t filename_len;
1279 char pathname[PATH_MAX];
1284 filename_len = strlen(filename);
1286 if (filename_len > sizeof(pathname) - 1) {
1287 errno = ENAMETOOLONG;
1288 perror_msg_and_die("exec");
1290 if (strchr(filename, '/')) {
1291 strcpy(pathname, filename);
1293 #ifdef USE_DEBUGGING_EXEC
1295 * Debuggers customarily check the current directory
1296 * first regardless of the path but doing that gives
1297 * security geeks a panic attack.
1299 else if (stat_file(filename, &statbuf) == 0)
1300 strcpy(pathname, filename);
1301 #endif /* USE_DEBUGGING_EXEC */
1306 for (path = getenv("PATH"); path && *path; path += m) {
1307 const char *colon = strchr(path, ':');
1312 m = n = strlen(path);
1314 if (!getcwd(pathname, PATH_MAX))
1316 len = strlen(pathname);
1317 } else if (n > sizeof(pathname) - 1)
1320 strncpy(pathname, path, n);
1323 if (len && pathname[len - 1] != '/')
1324 pathname[len++] = '/';
1325 if (filename_len + len > sizeof(pathname) - 1)
1327 strcpy(pathname + len, filename);
1328 if (stat_file(pathname, &statbuf) == 0 &&
1329 /* Accept only regular files
1330 with some execute bits set.
1331 XXX not perfect, might still fail */
1332 S_ISREG(statbuf.st_mode) &&
1333 (statbuf.st_mode & 0111))
1336 if (!path || !*path)
1339 if (stat_file(pathname, &statbuf) < 0) {
1340 perror_msg_and_die("Can't stat '%s'", filename);
1343 params_for_tracee.fd_to_close = (shared_log != stderr) ? fileno(shared_log) : -1;
1344 params_for_tracee.run_euid = (statbuf.st_mode & S_ISUID) ? statbuf.st_uid : run_uid;
1345 params_for_tracee.run_egid = (statbuf.st_mode & S_ISGID) ? statbuf.st_gid : run_gid;
1346 params_for_tracee.argv = argv;
1348 * On NOMMU, can be safely freed only after execve in tracee.
1349 * It's hard to know when that happens, so we just leak it.
1351 params_for_tracee.pathname = NOMMU_SYSTEM ? xstrdup(pathname) : pathname;
1353 #if defined HAVE_PRCTL && defined PR_SET_PTRACER && defined PR_SET_PTRACER_ANY
1354 if (daemonized_tracer)
1355 prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY);
1360 perror_func_msg_and_die("fork");
1362 if ((pid != 0 && daemonized_tracer)
1363 || (pid == 0 && !daemonized_tracer)
1365 /* We are to become the tracee. Two cases:
1367 * not -D: we are child
1372 /* We are the tracer */
1374 if (!daemonized_tracer) {
1377 /* child did PTRACE_TRACEME, nothing to do in parent */
1379 if (!NOMMU_SYSTEM) {
1380 /* Wait until child stopped itself */
1382 while (waitpid(pid, &status, WSTOPPED) < 0) {
1385 perror_msg_and_die("waitpid");
1387 if (!WIFSTOPPED(status) || WSTOPSIG(status) != SIGSTOP) {
1388 kill_save_errno(pid, SIGKILL);
1389 perror_msg_and_die("Unexpected wait status %#x",
1393 /* Else: NOMMU case, we have no way to sync.
1394 * Just attach to it as soon as possible.
1395 * This means that we may miss a few first syscalls...
1398 if (ptrace_attach_or_seize(pid)) {
1399 kill_save_errno(pid, SIGKILL);
1400 perror_msg_and_die("attach: ptrace(%s, %d)",
1401 ptrace_attach_cmd, pid);
1406 tcp = alloctcb(pid);
1407 tcp->flags |= TCB_ATTACHED | TCB_STARTUP
1408 | TCB_SKIP_DETACH_ON_FIRST_EXEC
1409 | (NOMMU_SYSTEM ? 0 : (TCB_HIDE_LOG | post_attach_sigstop));
1412 /* With -D, we are *child* here, the tracee is our parent. */
1413 strace_child = strace_tracer_pid;
1414 strace_tracer_pid = getpid();
1415 tcp = alloctcb(strace_child);
1416 tcp->flags |= TCB_SKIP_DETACH_ON_FIRST_EXEC | TCB_HIDE_LOG;
1417 /* attaching will be done later, by startup_attach */
1418 /* note: we don't do newoutf(tcp) here either! */
1420 /* NOMMU BUG! -D mode is active, we (child) return,
1421 * and we will scribble over parent's stack!
1422 * When parent later unpauses, it segfaults.
1425 * (1) by declaring exec_or_die() NORETURN,
1426 * hopefully compiler will just jump to it
1427 * instead of call (won't push anything to stack),
1428 * (2) by trying very hard in exec_or_die()
1429 * to not use any stack,
1430 * (3) having a really big (PATH_MAX) stack object
1431 * in this function, which creates a "buffer" between
1432 * child's and parent's stack pointers.
1433 * This may save us if (1) and (2) failed
1434 * and compiler decided to use stack in exec_or_die() anyway
1435 * (happens on i386 because of stack parameter passing).
1437 * A cleaner solution is to use makecontext + setcontext
1438 * to create a genuine separate stack and execute on it.
1442 * A case where straced process is part of a pipe:
1443 * { sleep 1; yes | head -n99999; } | strace -o/dev/null sh -c 'exec <&-; sleep 9'
1444 * If strace won't close its fd#0, closing it in tracee is not enough:
1445 * the pipe is still open, it has a reader. Thus, "head" will not get its
1446 * SIGPIPE at once, on the first write.
1448 * Preventing it by redirecting strace's stdin/out.
1449 * (Don't leave fds 0 and 1 closed, this is bad practice: future opens
1450 * will reuse them, unexpectedly making a newly opened object "stdin").
1452 redirect_standard_fds();
1457 test_ptrace_seize(void)
1461 /* Need fork for test. NOMMU has no forks */
1463 post_attach_sigstop = 0; /* this sets use_seize to 1 */
1469 perror_func_msg_and_die("fork");
1476 /* PTRACE_SEIZE, unlike ATTACH, doesn't force tracee to trap. After
1477 * attaching tracee continues to run unless a trap condition occurs.
1478 * PTRACE_SEIZE doesn't affect signal or group stop state.
1480 if (ptrace(PTRACE_SEIZE, pid, 0, 0) == 0) {
1481 post_attach_sigstop = 0; /* this sets use_seize to 1 */
1483 debug_msg("PTRACE_SEIZE doesn't work");
1489 int status, tracee_pid;
1492 tracee_pid = waitpid(pid, &status, 0);
1493 if (tracee_pid <= 0) {
1496 perror_func_msg_and_die("unexpected wait result %d",
1499 if (WIFSIGNALED(status))
1502 error_func_msg_and_die("unexpected wait status %#x", status);
1505 #else /* !USE_SEIZE */
1506 # define test_ptrace_seize() ((void)0)
1510 get_os_release(void)
1516 perror_msg_and_die("uname");
1517 /* u.release has this form: "3.2.9[-some-garbage]" */
1521 if (!(*p >= '0' && *p <= '9'))
1522 error_msg_and_die("Bad OS release string: '%s'", u.release);
1523 /* Note: this open-codes KERNEL_VERSION(): */
1524 rel = (rel << 8) | atoi(p);
1525 if (rel >= KERNEL_VERSION(1, 0, 0))
1527 while (*p >= '0' && *p <= '9')
1530 if (rel >= KERNEL_VERSION(0, 1, 0)) {
1531 /* "X.Y-something" means "X.Y.0" */
1535 error_msg_and_die("Bad OS release string: '%s'", u.release);
1543 set_sighandler(int signo, void (*sighandler)(int), struct sigaction *oldact)
1545 /* if signal handler is a function, add the signal to blocked_set */
1546 if (sighandler != SIG_IGN && sighandler != SIG_DFL)
1547 sigaddset(&blocked_set, signo);
1549 const struct sigaction sa = { .sa_handler = sighandler };
1550 sigaction(signo, &sa, oldact);
1554 * Initialization part of main() was eating much stack (~0.5k),
1555 * which was unused after init.
1556 * We can reuse it if we move init code into a separate function.
1558 * Don't want main() to inline us and defeat the reason
1559 * we have a separate function.
1561 static void ATTRIBUTE_NOINLINE
1562 init(int argc, char *argv[])
1567 if (!program_invocation_name || !*program_invocation_name) {
1568 static char name[] = "strace";
1569 program_invocation_name =
1570 (argc > 0 && argv[0] && *argv[0]) ? argv[0] : name;
1573 strace_tracer_pid = getpid();
1575 os_release = get_os_release();
1577 shared_log = stderr;
1578 set_sortby(DEFAULT_SORTBY);
1579 set_personality(DEFAULT_PERSONALITY);
1580 qualify("trace=all");
1581 qualify("abbrev=all");
1582 qualify("verbose=all");
1583 #if DEFAULT_QUAL_FLAGS != (QUAL_TRACE | QUAL_ABBREV | QUAL_VERBOSE)
1584 # error Bug in DEFAULT_QUAL_FLAGS
1586 qualify("signal=all");
1587 while ((c = getopt(argc, argv, "+"
1588 #ifdef USE_LIBUNWIND
1591 "a:b:cCdDe:E:fFhiI:o:O:p:P:qrs:S:tTu:vVwxyz")) != EOF) {
1594 acolumn = string_to_uint(optarg);
1596 error_opt_arg(c, optarg);
1599 if (strcmp(optarg, "execve") != 0)
1600 error_msg_and_die("Syscall '%s' for -b isn't supported",
1602 detach_on_execve = 1;
1605 if (cflag == CFLAG_BOTH) {
1606 error_msg_and_help("-c and -C are mutually exclusive");
1608 cflag = CFLAG_ONLY_STATS;
1611 if (cflag == CFLAG_ONLY_STATS) {
1612 error_msg_and_help("-c and -C are mutually exclusive");
1620 daemonized_tracer = 1;
1626 if (putenv(optarg) < 0)
1627 perror_msg_and_die("putenv");
1642 opt_intr = string_to_uint_upto(optarg, NUM_INTR_OPTS - 1);
1644 error_opt_arg(c, optarg);
1646 #ifdef USE_LIBUNWIND
1648 stack_trace_enabled = true;
1655 i = string_to_uint(optarg);
1657 error_opt_arg(c, optarg);
1661 process_opt_p_list(optarg);
1664 pathtrace_select(optarg);
1673 i = string_to_uint(optarg);
1674 if (i < 0 || (unsigned int) i > -1U / 4)
1675 error_opt_arg(c, optarg);
1691 qualify("abbrev=none");
1698 count_wallclock = 1;
1707 not_failing_only = 1;
1710 error_msg_and_help(NULL);
1718 if (argc < 0 || (!nprocs && !argc)) {
1719 error_msg_and_help("must have PROG [ARGS] or -p PID");
1722 if (!argc && daemonized_tracer) {
1723 error_msg_and_help("PROG [ARGS] must be specified with -D");
1728 error_msg("deprecated option -F ignored");
1730 error_msg("option -F is deprecated, "
1731 "please use -f instead");
1736 if (followfork >= 2 && cflag) {
1737 error_msg_and_help("(-c or -C) and -ff are mutually exclusive");
1740 if (count_wallclock && !cflag) {
1741 error_msg_and_help("-w must be given with (-c or -C)");
1744 if (cflag == CFLAG_ONLY_STATS) {
1746 error_msg("-%c has no effect with -c", 'i');
1747 #ifdef USE_LIBUNWIND
1748 if (stack_trace_enabled)
1749 error_msg("-%c has no effect with -c", 'k');
1752 error_msg("-%c has no effect with -c", 'r');
1754 error_msg("-%c has no effect with -c", 't');
1756 error_msg("-%c has no effect with -c", 'T');
1758 error_msg("-%c has no effect with -c", 'y');
1763 error_msg("-tt has no effect with -r");
1767 acolumn_spaces = xmalloc(acolumn + 1);
1768 memset(acolumn_spaces, ' ', acolumn);
1769 acolumn_spaces[acolumn] = '\0';
1771 sigprocmask(SIG_SETMASK, NULL, &start_set);
1772 memcpy(&blocked_set, &start_set, sizeof(blocked_set));
1774 set_sighandler(SIGCHLD, SIG_DFL, ¶ms_for_tracee.child_sa);
1776 #ifdef USE_LIBUNWIND
1777 if (stack_trace_enabled) {
1781 for (tcbi = 0; tcbi < tcbtabsize; ++tcbi) {
1782 unwind_tcb_init(tcbtab[tcbi]);
1787 /* See if they want to run as another user. */
1788 if (username != NULL) {
1789 struct passwd *pent;
1791 if (getuid() != 0 || geteuid() != 0) {
1792 error_msg_and_die("You must be root to use the -u option");
1794 pent = getpwnam(username);
1796 error_msg_and_die("Cannot find user '%s'", username);
1798 run_uid = pent->pw_uid;
1799 run_gid = pent->pw_gid;
1806 ptrace_setoptions |= PTRACE_O_TRACECLONE |
1807 PTRACE_O_TRACEFORK |
1808 PTRACE_O_TRACEVFORK;
1809 debug_msg("ptrace_setoptions = %#x", ptrace_setoptions);
1810 test_ptrace_seize();
1813 * Is something weird with our stdin and/or stdout -
1814 * for example, may they be not open? In this case,
1815 * ensure that none of the future opens uses them.
1817 * This was seen in the wild when /proc/sys/kernel/core_pattern
1818 * was set to "|/bin/strace -o/tmp/LOG PROG":
1819 * kernel runs coredump helper with fd#0 open but fd#1 closed (!),
1820 * therefore LOG gets opened to fd#1, and fd#1 is closed by
1821 * "don't hold up stdin/out open" code soon after.
1823 ensure_standard_fds_opened();
1825 /* Check if they want to redirect the output. */
1827 /* See if they want to pipe the output. */
1828 if (outfname[0] == '|' || outfname[0] == '!') {
1830 * We can't do the <outfname>.PID funny business
1831 * when using popen, so prohibit it.
1833 if (followfork >= 2)
1834 error_msg_and_help("piping the output and -ff "
1835 "are mutually exclusive");
1836 shared_log = strace_popen(outfname + 1);
1837 } else if (followfork < 2) {
1838 shared_log = strace_fopen(outfname);
1839 } else if (strlen(outfname) >= PATH_MAX - sizeof(int) * 3) {
1840 errno = ENAMETOOLONG;
1841 perror_msg_and_die("%s", outfname);
1844 /* -ff without -o FILE is the same as single -f */
1845 if (followfork >= 2)
1849 if (!outfname || outfname[0] == '|' || outfname[0] == '!') {
1850 setvbuf(shared_log, NULL, _IOLBF, 0);
1854 * argv[0] -pPID -oFILE Default interactive setting
1855 * yes * 0 INTR_WHILE_WAIT
1856 * no 1 0 INTR_WHILE_WAIT
1857 * yes * 1 INTR_NEVER
1858 * no 1 1 INTR_WHILE_WAIT
1861 if (outfname && argc) {
1863 opt_intr = INTR_NEVER;
1868 opt_intr = INTR_WHILE_WAIT;
1871 * startup_child() must be called before the signal handlers get
1872 * installed below as they are inherited into the spawned process.
1873 * Also we do not need to be protected by them as during interruption
1874 * in the startup_child() mode we kill the spawned process anyway.
1877 startup_child(argv);
1880 set_sighandler(SIGTTOU, SIG_IGN, NULL);
1881 set_sighandler(SIGTTIN, SIG_IGN, NULL);
1882 if (opt_intr != INTR_ANYWHERE) {
1883 if (opt_intr == INTR_BLOCK_TSTP_TOO)
1884 set_sighandler(SIGTSTP, SIG_IGN, NULL);
1886 * In interactive mode (if no -o OUTFILE, or -p PID is used),
1887 * fatal signals are blocked while syscall stop is processed,
1888 * and acted on in between, when waiting for new syscall stops.
1889 * In non-interactive mode, signals are ignored.
1891 set_sighandler(SIGHUP, interactive ? interrupt : SIG_IGN, NULL);
1892 set_sighandler(SIGINT, interactive ? interrupt : SIG_IGN, NULL);
1893 set_sighandler(SIGQUIT, interactive ? interrupt : SIG_IGN, NULL);
1894 set_sighandler(SIGPIPE, interactive ? interrupt : SIG_IGN, NULL);
1895 set_sighandler(SIGTERM, interactive ? interrupt : SIG_IGN, NULL);
1898 if (nprocs != 0 || daemonized_tracer)
1901 /* Do we want pids printed in our -o OUTFILE?
1902 * -ff: no (every pid has its own file); or
1903 * -f: yes (there can be more pids in the future); or
1904 * -p PID1,PID2: yes (there are already more than one pid)
1906 print_pid_pfx = (outfname && followfork < 2 && (followfork == 1 || nprocs > 1));
1917 for (i = 0; i < tcbtabsize; i++) {
1918 struct tcb *tcp = tcbtab[i];
1919 if (tcp->pid == pid)
1933 /* 'interrupted' is a volatile object, fetch it only once */
1934 fatal_sig = interrupted;
1936 fatal_sig = SIGTERM;
1938 for (i = 0; i < tcbtabsize; i++) {
1942 debug_func_msg("looking at pid %u", tcp->pid);
1943 if (tcp->pid == strace_child) {
1944 kill(tcp->pid, SIGCONT);
1945 kill(tcp->pid, fatal_sig);
1950 call_summary(shared_log);
1960 print_debug_info(const int pid, int status)
1962 const unsigned int event = (unsigned int) status >> 16;
1963 char buf[sizeof("WIFEXITED,exitcode=%u") + sizeof(int)*3 /*paranoia:*/ + 16];
1964 char evbuf[sizeof(",EVENT_VFORK_DONE (%u)") + sizeof(int)*3 /*paranoia:*/ + 16];
1967 if (WIFSIGNALED(status))
1969 xsprintf(buf, "WIFSIGNALED,%ssig=%s",
1970 WCOREDUMP(status) ? "core," : "",
1971 signame(WTERMSIG(status)));
1973 xsprintf(buf, "WIFSIGNALED,sig=%s",
1974 signame(WTERMSIG(status)));
1976 if (WIFEXITED(status))
1977 xsprintf(buf, "WIFEXITED,exitcode=%u", WEXITSTATUS(status));
1978 if (WIFSTOPPED(status))
1979 xsprintf(buf, "WIFSTOPPED,sig=%s", signame(WSTOPSIG(status)));
1982 static const char *const event_names[] = {
1983 [PTRACE_EVENT_CLONE] = "CLONE",
1984 [PTRACE_EVENT_FORK] = "FORK",
1985 [PTRACE_EVENT_VFORK] = "VFORK",
1986 [PTRACE_EVENT_VFORK_DONE] = "VFORK_DONE",
1987 [PTRACE_EVENT_EXEC] = "EXEC",
1988 [PTRACE_EVENT_EXIT] = "EXIT",
1989 /* [PTRACE_EVENT_STOP (=128)] would make biggish array */
1991 const char *e = "??";
1992 if (event < ARRAY_SIZE(event_names))
1993 e = event_names[event];
1994 else if (event == PTRACE_EVENT_STOP)
1996 xsprintf(evbuf, ",EVENT_%s (%u)", e, event);
1998 error_msg("[wait(0x%06x) = %u] %s%s", status, pid, buf, evbuf);
2002 maybe_allocate_tcb(const int pid, int status)
2004 if (!WIFSTOPPED(status)) {
2005 if (detach_on_execve && pid == strace_child) {
2006 /* example: strace -bexecve sh -c 'exec true' */
2011 * This can happen if we inherited an unknown child.
2012 * Example: (sleep 1 & exec strace true)
2014 error_msg("Exit of unknown pid %u ignored", pid);
2018 /* We assume it's a fork/vfork/clone child */
2019 struct tcb *tcp = alloctcb(pid);
2020 tcp->flags |= TCB_ATTACHED | TCB_STARTUP | post_attach_sigstop;
2023 error_msg("Process %d attached", pid);
2027 * This can happen if a clone call misused CLONE_PTRACE itself.
2029 * There used to be a dance around possible re-injection of
2030 * WSTOPSIG(status), but it was later removed as the only
2031 * observable stop here is the initial ptrace-stop.
2033 ptrace(PTRACE_DETACH, pid, NULL, 0L);
2034 error_msg("Detached unknown pid %d", pid);
2040 maybe_switch_tcbs(struct tcb *tcp, const int pid)
2043 struct tcb *execve_thread;
2046 if (ptrace(PTRACE_GETEVENTMSG, pid, NULL, &old_pid) < 0)
2048 /* Avoid truncation in pid2tcb() param passing */
2049 if (old_pid <= 0 || old_pid == pid)
2051 if ((unsigned long) old_pid > UINT_MAX)
2053 execve_thread = pid2tcb(old_pid);
2054 /* It should be !NULL, but I feel paranoid */
2058 if (execve_thread->curcol != 0) {
2060 * One case we are here is -ff:
2061 * try "strace -oLOG -ff test/threaded_execve"
2063 fprintf(execve_thread->outf, " <pid changed to %d ...>\n", pid);
2064 /*execve_thread->curcol = 0; - no need, see code below */
2066 /* Swap output FILEs (needed for -ff) */
2067 fp = execve_thread->outf;
2068 execve_thread->outf = tcp->outf;
2070 /* And their column positions */
2071 execve_thread->curcol = tcp->curcol;
2073 /* Drop leader, but close execve'd thread outfile (if -ff) */
2075 /* Switch to the thread, reusing leader's outfile and pid */
2076 tcp = execve_thread;
2078 if (cflag != CFLAG_ONLY_STATS) {
2080 tprintf("+++ superseded by execve in pid %lu +++\n", old_pid);
2082 tcp->flags |= TCB_REPRINT;
2089 print_signalled(struct tcb *tcp, const int pid, int status)
2091 if (pid == strace_child) {
2092 exit_code = 0x100 | WTERMSIG(status);
2096 if (cflag != CFLAG_ONLY_STATS
2097 && is_number_in_set(WTERMSIG(status), signal_set)) {
2100 tprintf("+++ killed by %s %s+++\n",
2101 signame(WTERMSIG(status)),
2102 WCOREDUMP(status) ? "(core dumped) " : "");
2104 tprintf("+++ killed by %s +++\n",
2105 signame(WTERMSIG(status)));
2112 print_exited(struct tcb *tcp, const int pid, int status)
2114 if (pid == strace_child) {
2115 exit_code = WEXITSTATUS(status);
2119 if (cflag != CFLAG_ONLY_STATS &&
2122 tprintf("+++ exited with %d +++\n", WEXITSTATUS(status));
2128 print_stopped(struct tcb *tcp, const siginfo_t *si, const unsigned int sig)
2130 if (cflag != CFLAG_ONLY_STATS
2132 && is_number_in_set(sig, signal_set)) {
2135 tprintf("--- %s ", signame(sig));
2139 tprintf("--- stopped by %s ---\n", signame(sig));
2145 startup_tcb(struct tcb *tcp)
2147 debug_msg("pid %d has TCB_STARTUP, initializing it", tcp->pid);
2149 tcp->flags &= ~TCB_STARTUP;
2152 debug_msg("setting opts 0x%x on pid %d",
2153 ptrace_setoptions, tcp->pid);
2154 if (ptrace(PTRACE_SETOPTIONS, tcp->pid, NULL, ptrace_setoptions) < 0) {
2155 if (errno != ESRCH) {
2156 /* Should never happen, really */
2157 perror_msg_and_die("PTRACE_SETOPTIONS");
2162 if ((tcp->flags & TCB_GRABBED) && (get_scno(tcp) == 1))
2163 tcp->s_prev_ent = tcp->s_ent;
2167 print_event_exit(struct tcb *tcp)
2169 if (entering(tcp) || filtered(tcp) || hide_log(tcp)
2170 || cflag == CFLAG_ONLY_STATS) {
2174 if (followfork < 2 && printing_tcp && printing_tcp != tcp
2175 && printing_tcp->curcol != 0) {
2176 current_tcp = printing_tcp;
2177 tprints(" <unfinished ...>\n");
2178 flush_tcp_output(printing_tcp);
2179 printing_tcp->curcol = 0;
2183 if ((followfork < 2 && printing_tcp != tcp)
2184 || (tcp->flags & TCB_REPRINT)) {
2185 tcp->flags &= ~TCB_REPRINT;
2187 tprintf("<... %s resumed>", tcp->s_ent->sys_name);
2190 if (!(tcp->sys_func_rval & RVAL_DECODED)) {
2192 * The decoder has probably decided to print something
2193 * on exiting syscall which is not going to happen.
2195 tprints(" <unfinished ...>");
2203 static enum trace_event
2204 next_event(int *pstatus, siginfo_t *si)
2216 * Used to exit simply when nprocs hits zero, but in this testcase:
2217 * int main(void) { _exit(!!fork()); }
2218 * under strace -f, parent sometimes (rarely) manages
2219 * to exit before we see the first stop of the child,
2220 * and we are losing track of it:
2221 * 19923 clone(...) = 19924
2222 * 19923 exit_group(1) = ?
2223 * 19923 +++ exited with 1 +++
2224 * Exiting only when wait() returns ECHILD works better.
2226 if (popen_pid != 0) {
2227 /* However, if -o|logger is in use, we can't do that.
2228 * Can work around that by double-forking the logger,
2229 * but that loses the ability to wait for its completion
2230 * on exit. Oh well...
2237 sigprocmask(SIG_SETMASK, &start_set, NULL);
2238 pid = wait4(-1, pstatus, __WALL, (cflag ? &ru : NULL));
2241 sigprocmask(SIG_SETMASK, &blocked_set, NULL);
2244 if (wait_errno == EINTR)
2246 if (nprocs == 0 && wait_errno == ECHILD)
2249 * If nprocs > 0, ECHILD is not expected,
2250 * treat it as any other error here:
2253 perror_msg_and_die("wait4(__WALL)");
2258 if (pid == popen_pid) {
2259 if (!WIFSTOPPED(status))
2265 print_debug_info(pid, status);
2267 /* Look up 'pid' in our table. */
2271 tcp = maybe_allocate_tcb(pid, status);
2278 /* Set current output file */
2282 tv_sub(&tcp->dtime, &ru.ru_stime, &tcp->stime);
2283 tcp->stime = ru.ru_stime;
2286 if (WIFSIGNALED(status))
2287 return TE_SIGNALLED;
2289 if (WIFEXITED(status))
2293 * As WCONTINUED flag has not been specified to wait4,
2294 * it cannot be WIFCONTINUED(status), so the only case
2295 * that remains is WIFSTOPPED(status).
2298 /* Is this the very first time we see this tracee stopped? */
2299 if (tcp->flags & TCB_STARTUP)
2302 const unsigned int sig = WSTOPSIG(status);
2303 const unsigned int event = (unsigned int) status >> 16;
2308 * Is this post-attach SIGSTOP?
2309 * Interestingly, the process may stop
2310 * with STOPSIG equal to some other signal
2311 * than SIGSTOP if we happened to attach
2312 * just before the process takes a signal.
2314 if (sig == SIGSTOP && (tcp->flags & TCB_IGNORE_ONE_SIGSTOP)) {
2315 debug_func_msg("ignored SIGSTOP on pid %d", tcp->pid);
2316 tcp->flags &= ~TCB_IGNORE_ONE_SIGSTOP;
2318 } else if (sig == syscall_trap_sig) {
2319 return TE_SYSCALL_STOP;
2321 *si = (siginfo_t) {};
2323 * True if tracee is stopped by signal
2324 * (as opposed to "tracee received signal").
2325 * TODO: shouldn't we check for errno == EINVAL too?
2326 * We can get ESRCH instead, you know...
2328 bool stopped = ptrace(PTRACE_GETSIGINFO, pid, 0, si) < 0;
2329 return stopped ? TE_GROUP_STOP : TE_SIGNAL_DELIVERY_STOP;
2333 case PTRACE_EVENT_STOP:
2335 * PTRACE_INTERRUPT-stop or group-stop.
2336 * PTRACE_INTERRUPT-stop has sig == SIGTRAP here.
2343 return TE_GROUP_STOP;
2347 case PTRACE_EVENT_EXEC:
2348 return TE_STOP_BEFORE_EXECVE;
2349 case PTRACE_EVENT_EXIT:
2350 return TE_STOP_BEFORE_EXIT;
2357 trace_syscall(struct tcb *tcp, unsigned int *sig)
2359 if (entering(tcp)) {
2360 int res = syscall_entering_decode(tcp);
2365 res = syscall_entering_trace(tcp, sig);
2367 syscall_entering_finish(tcp, res);
2370 struct timeval tv = {};
2371 int res = syscall_exiting_decode(tcp, &tv);
2373 res = syscall_exiting_trace(tcp, tv, res);
2375 syscall_exiting_finish(tcp);
2380 /* Returns true iff the main trace loop has to continue. */
2382 dispatch_event(enum trace_event ret, int *pstatus, siginfo_t *si)
2384 unsigned int restart_op = PTRACE_SYSCALL;
2385 unsigned int restart_sig = 0;
2397 case TE_SYSCALL_STOP:
2398 if (trace_syscall(current_tcp, &restart_sig) < 0) {
2400 * ptrace() failed in trace_syscall().
2401 * Likely a result of process disappearing mid-flight.
2402 * Observed case: exit_group() or SIGKILL terminating
2403 * all processes in thread group.
2404 * We assume that ptrace error was caused by process death.
2405 * We used to detach(current_tcp) here, but since we no
2406 * longer implement "detach before death" policy/hack,
2407 * we can let this process to report its death to us
2408 * normally, via WIFEXITED or WIFSIGNALED wait status.
2414 case TE_SIGNAL_DELIVERY_STOP:
2415 restart_sig = WSTOPSIG(*pstatus);
2416 print_stopped(current_tcp, si, restart_sig);
2420 print_signalled(current_tcp, current_tcp->pid, *pstatus);
2421 droptcb(current_tcp);
2425 restart_sig = WSTOPSIG(*pstatus);
2426 print_stopped(current_tcp, NULL, restart_sig);
2429 * This ends ptrace-stop, but does *not* end group-stop.
2430 * This makes stopping signals work properly on straced
2431 * process (that is, process really stops. It used to
2434 restart_op = PTRACE_LISTEN;
2440 print_exited(current_tcp, current_tcp->pid, *pstatus);
2441 droptcb(current_tcp);
2444 case TE_STOP_BEFORE_EXECVE:
2446 * Under Linux, execve changes pid to thread leader's pid,
2447 * and we see this changed pid on EVENT_EXEC and later,
2448 * execve sysexit. Leader "disappears" without exit
2449 * notification. Let user know that, drop leader's tcb,
2450 * and fix up pid in execve thread's tcb.
2451 * Effectively, execve thread's tcb replaces leader's tcb.
2453 * BTW, leader is 'stuck undead' (doesn't report WIFEXITED
2454 * on exit syscall) in multithreaded programs exactly
2455 * in order to handle this case.
2457 * PTRACE_GETEVENTMSG returns old pid starting from Linux 3.0.
2458 * On 2.6 and earlier, it can return garbage.
2460 if (os_release >= KERNEL_VERSION(3, 0, 0))
2461 current_tcp = maybe_switch_tcbs(current_tcp, current_tcp->pid);
2463 if (detach_on_execve) {
2464 if (current_tcp->flags & TCB_SKIP_DETACH_ON_FIRST_EXEC) {
2465 current_tcp->flags &= ~TCB_SKIP_DETACH_ON_FIRST_EXEC;
2467 detach(current_tcp); /* do "-b execve" thingy */
2473 case TE_STOP_BEFORE_EXIT:
2474 print_event_exit(current_tcp);
2478 /* We handled quick cases, we are permitted to interrupt now. */
2482 if (ptrace_restart(restart_op, current_tcp, restart_sig) < 0) {
2483 /* Note: ptrace_restart emitted error message */
2490 #ifdef ENABLE_COVERAGE_GCOV
2491 extern void __gcov_flush(void);
2494 static void ATTRIBUTE_NORETURN
2499 if (shared_log != stderr)
2502 while (waitpid(popen_pid, NULL, 0) < 0 && errno == EINTR)
2505 if (exit_code > 0xff) {
2506 /* Avoid potential core file clobbering. */
2507 struct_rlimit rlim = {0, 0};
2508 set_rlimit(RLIMIT_CORE, &rlim);
2510 /* Child was killed by a signal, mimic that. */
2512 signal(exit_code, SIG_DFL);
2513 #ifdef ENABLE_COVERAGE_GCOV
2518 /* Unblock the signal. */
2521 sigaddset(&mask, exit_code);
2522 #ifdef ENABLE_COVERAGE_GCOV
2525 sigprocmask(SIG_UNBLOCK, &mask, NULL);
2527 /* Paranoia - what if this signal is not fatal?
2528 Exit with 128 + signo then. */
2535 main(int argc, char *argv[])
2539 exit_code = !nprocs;
2543 while (dispatch_event(next_event(&status, &si), &status, &si))