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 #endif /* USE_DEMANGLE */
210 #if SUPPORTED_PERSONALITIES > 1
211 # if defined HAVE_M32_MPERS
216 #endif /* SUPPORTED_PERSONALITIES > 1 */
217 #if SUPPORTED_PERSONALITIES > 2
218 # if defined HAVE_MX32_MPERS
223 #endif /* SUPPORTED_PERSONALITIES > 2 */
226 printf("%s -- version %s\n"
227 "Copyright (c) 1991-%s The strace developers <%s>.\n"
228 "This is free software; see the source for copying conditions. There is NO\n"
229 "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n",
230 PACKAGE_NAME, PACKAGE_VERSION, COPYRIGHT_YEAR, PACKAGE_URL);
231 printf("\nOptional features enabled:%s\n",
232 features[0] ? features : " (none)");
239 usage: strace [-CdffhiqrtttTvVwxxy] [-I n] [-e expr]...\n\
240 [-a column] [-o file] [-s strsize] [-P path]...\n\
241 -p pid... / [-D] [-E var=val]... [-u username] PROG [ARGS]\n\
242 or: strace -c[dfw] [-I n] [-e expr]... [-O overhead] [-S sortby]\n\
243 -p pid... / [-D] [-E var=val]... [-u username] PROG [ARGS]\n\
246 -a column alignment COLUMN for printing syscall results (default %d)\n\
247 -i print instruction pointer at time of syscall\n\
251 -k obtain stack trace between each syscall (experimental)\n\
255 -o file send trace output to FILE instead of stderr\n\
256 -q suppress messages about attaching, detaching, etc.\n\
257 -r print relative timestamp\n\
258 -s strsize limit length of print strings to STRSIZE chars (default %d)\n\
259 -t print absolute timestamp\n\
260 -tt print absolute timestamp with usecs\n\
261 -T print time spent in each syscall\n\
262 -x print non-ascii strings in hex\n\
263 -xx print all strings in hex\n\
264 -y print paths associated with file descriptor arguments\n\
265 -yy print protocol specific information associated with socket file descriptors\n\
268 -c count time, calls, and errors for each syscall and report summary\n\
269 -C like -c but also print regular output\n\
270 -O overhead set overhead for tracing syscalls to OVERHEAD usecs\n\
271 -S sortby sort syscall counts by: time, calls, name, nothing (default %s)\n\
272 -w summarise syscall latency (default is system time)\n\
275 -e expr a qualifying expression: option=[!]all or option=[!]val1[,val2]...\n\
276 options: trace, abbrev, verbose, raw, signal, read, write, fault\n\
277 -P path trace accesses to path\n\
280 -b execve detach on execve syscall\n\
281 -D run tracer process as a detached grandchild, not as parent\n\
283 -ff follow forks with output into separate files\n\
285 1: no signals are blocked\n\
286 2: fatal signals are blocked while decoding syscall (default)\n\
287 3: fatal signals are always blocked (default if '-o FILE PROG')\n\
288 4: fatal signals and SIGTSTP (^Z) are always blocked\n\
289 (useful to make 'strace -o FILE PROG' not stop on ^Z)\n\
292 -E var remove var from the environment for command\n\
293 -E var=val put var=val in the environment for command\n\
294 -p pid trace process with process id PID, may be repeated\n\
295 -u username run command as username handling setuid and/or setgid\n\
298 -d enable debug output to stderr\n\
299 -v verbose mode: print unabbreviated argv, stat, termios, etc. args\n\
300 -h print help message\n\
303 /* ancient, no one should use it
304 -F -- attempt to follow vforks (deprecated, use -f)\n\
306 /* this is broken, so don't document it
307 -z -- print only succeeding syscalls\n\
309 , DEFAULT_ACOLUMN, DEFAULT_STRLEN, DEFAULT_SORTBY);
313 void ATTRIBUTE_NORETURN
316 if (strace_tracer_pid == getpid()) {
326 error_opt_arg(int opt, const char *arg)
328 error_msg_and_help("invalid -%c argument: '%s'", opt, arg);
331 static const char *ptrace_attach_cmd;
334 ptrace_attach_or_seize(int pid)
339 return ptrace_attach_cmd = "PTRACE_ATTACH",
340 ptrace(PTRACE_ATTACH, pid, 0L, 0L);
341 r = ptrace(PTRACE_SEIZE, pid, 0L, (unsigned long) ptrace_setoptions);
343 return ptrace_attach_cmd = "PTRACE_SEIZE", r;
344 r = ptrace(PTRACE_INTERRUPT, pid, 0L, 0L);
345 return ptrace_attach_cmd = "PTRACE_INTERRUPT", r;
347 return ptrace_attach_cmd = "PTRACE_ATTACH",
348 ptrace(PTRACE_ATTACH, pid, 0L, 0L);
353 * Used when we want to unblock stopped traced process.
354 * Should be only used with PTRACE_CONT, PTRACE_DETACH and PTRACE_SYSCALL.
355 * Returns 0 on success or if error was ESRCH
356 * (presumably process was killed while we talk to it).
357 * Otherwise prints error message and returns -1.
360 ptrace_restart(const unsigned int op, struct tcb *const tcp, unsigned int sig)
366 ptrace(op, tcp->pid, 0L, (unsigned long) sig);
386 * Why curcol != 0? Otherwise sometimes we get this:
388 * 10252 kill(10253, SIGKILL) = 0
389 * <ptrace(SYSCALL,10252):No such process>10253 ...next decode...
391 * 10252 died after we retrieved syscall exit data,
392 * but before we tried to restart it. Log looks ugly.
394 if (current_tcp && current_tcp->curcol != 0) {
395 tprintf(" <ptrace(%s):%s>\n", msg, strerror(err));
401 perror_msg("ptrace(PTRACE_%s,pid:%d,sig:%u)", msg, tcp->pid, sig);
406 set_cloexec_flag(int fd)
410 flags = fcntl(fd, F_GETFD);
412 /* Can happen only if fd is bad.
413 * Should never happen: if it does, we have a bug
414 * in the caller. Therefore we just abort
415 * instead of propagating the error.
417 perror_msg_and_die("fcntl(%d, F_GETFD)", fd);
420 newflags = flags | FD_CLOEXEC;
421 if (flags == newflags)
424 fcntl(fd, F_SETFD, newflags); /* never fails */
428 kill_save_errno(pid_t pid, int sig)
430 int saved_errno = errno;
432 (void) kill(pid, sig);
437 * When strace is setuid executable, we have to swap uids
438 * before and after filesystem and process management operations.
443 int euid = geteuid(), uid = getuid();
445 if (euid != uid && setreuid(euid, uid) < 0) {
446 perror_msg_and_die("setreuid");
450 #ifdef _LARGEFILE64_SOURCE
452 # define fopen_for_output fopen64
454 # define fopen_for_output fopen
456 # define struct_stat struct stat64
457 # define stat_file stat64
458 # define struct_dirent struct dirent64
459 # define read_dir readdir64
460 # define struct_rlimit struct rlimit64
461 # define set_rlimit setrlimit64
463 # define fopen_for_output fopen
464 # define struct_stat struct stat
465 # define stat_file stat
466 # define struct_dirent struct dirent
467 # define read_dir readdir
468 # define struct_rlimit struct rlimit
469 # define set_rlimit setrlimit
473 strace_fopen(const char *path)
478 fp = fopen_for_output(path, "w");
480 perror_msg_and_die("Can't fopen '%s'", path);
482 set_cloexec_flag(fileno(fp));
486 static int popen_pid;
489 # define _PATH_BSHELL "/bin/sh"
493 * We cannot use standard popen(3) here because we have to distinguish
494 * popen child process from other processes we trace, and standard popen(3)
495 * does not export its child's pid.
498 strace_popen(const char *command)
506 perror_msg_and_die("pipe");
508 set_cloexec_flag(fds[1]); /* never fails */
512 perror_msg_and_die("vfork");
519 perror_msg_and_die("dup2");
522 execl(_PATH_BSHELL, "sh", "-c", command, NULL);
523 perror_msg_and_die("Can't execute '%s'", _PATH_BSHELL);
530 fp = fdopen(fds[1], "w");
532 perror_msg_and_die("fdopen");
536 ATTRIBUTE_FORMAT((printf, 1, 0))
538 tvprintf(const char *const fmt, va_list args)
541 int n = vfprintf(current_tcp->outf, fmt, args);
543 /* very unlikely due to vfprintf buffering */
544 if (current_tcp->outf != stderr)
545 perror_msg("%s", outfname);
547 current_tcp->curcol += n;
552 tprintf(const char *fmt, ...)
560 #ifndef HAVE_FPUTS_UNLOCKED
561 # define fputs_unlocked fputs
565 tprints(const char *str)
568 int n = fputs_unlocked(str, current_tcp->outf);
570 current_tcp->curcol += strlen(str);
573 /* very unlikely due to fputs_unlocked buffering */
574 if (current_tcp->outf != stderr)
575 perror_msg("%s", outfname);
580 tprints_comment(const char *const str)
583 tprintf(" /* %s */", str);
587 tprintf_comment(const char *fmt, ...)
601 flush_tcp_output(const struct tcb *const tcp)
603 if (fflush(tcp->outf) && tcp->outf != stderr)
604 perror_msg("%s", outfname);
611 current_tcp->curcol = 0;
612 flush_tcp_output(current_tcp);
615 printing_tcp->curcol = 0;
621 printleader(struct tcb *tcp)
623 /* If -ff, "previous tcb we printed" is always the same as current,
624 * because we have per-tcb output files.
630 current_tcp = printing_tcp;
631 if (printing_tcp->curcol != 0 && (followfork < 2 || printing_tcp == tcp)) {
633 * case 1: we have a shared log (i.e. not -ff), and last line
634 * wasn't finished (same or different tcb, doesn't matter).
635 * case 2: split log, we are the same tcb, but our last line
636 * didn't finish ("SIGKILL nuked us after syscall entry" etc).
638 tprints(" <unfinished ...>\n");
639 printing_tcp->curcol = 0;
645 current_tcp->curcol = 0;
648 tprintf("%-5d ", tcp->pid);
649 else if (nprocs > 1 && !outfname)
650 tprintf("[pid %5u] ", tcp->pid);
653 char str[sizeof("HH:MM:SS")];
654 struct timeval tv, dtv;
655 static struct timeval otv;
657 gettimeofday(&tv, NULL);
661 tv_sub(&dtv, &tv, &otv);
662 tprintf("%6ld.%06ld ",
663 (long) dtv.tv_sec, (long) dtv.tv_usec);
665 } else if (tflag > 2) {
666 tprintf("%ld.%06ld ",
667 (long) tv.tv_sec, (long) tv.tv_usec);
669 time_t local = tv.tv_sec;
670 strftime(str, sizeof(str), "%T", localtime(&local));
672 tprintf("%s.%06ld ", str, (long) tv.tv_usec);
684 if (current_tcp->curcol < acolumn)
685 tprints(acolumn_spaces + current_tcp->curcol);
688 /* Should be only called directly *after successful attach* to a tracee.
689 * Otherwise, "strace -oFILE -ff -p<nonexistant_pid>"
690 * may create bogus empty FILE.<nonexistant_pid>, and then die.
693 newoutf(struct tcb *tcp)
695 tcp->outf = shared_log; /* if not -ff mode, the same file is for all */
696 if (followfork >= 2) {
698 xsprintf(name, "%s.%u", outfname, tcp->pid);
699 tcp->outf = strace_fopen(name);
706 /* Allocate some (more) TCBs (and expand the table).
707 We don't want to relocate the TCBs because our
708 callers have pointers and it would be a pain.
709 So tcbtab is a table of pointers. Since we never
710 free the TCBs, we allocate a single chunk of many. */
711 size_t old_tcbtabsize;
713 struct tcb **tcb_ptr;
715 old_tcbtabsize = tcbtabsize;
717 tcbtab = xgrowarray(tcbtab, &tcbtabsize, sizeof(tcbtab[0]));
718 newtcbs = xcalloc(tcbtabsize - old_tcbtabsize, sizeof(newtcbs[0]));
720 for (tcb_ptr = tcbtab + old_tcbtabsize;
721 tcb_ptr < tcbtab + tcbtabsize; tcb_ptr++, newtcbs++)
731 if (nprocs == tcbtabsize)
734 for (i = 0; i < tcbtabsize; i++) {
737 memset(tcp, 0, sizeof(*tcp));
739 #if SUPPORTED_PERSONALITIES > 1
740 tcp->currpers = current_personality;
744 if (stack_trace_enabled)
745 unwind_tcb_init(tcp);
749 debug_msg("new tcb for pid %d, active tcbs:%d",
754 error_msg_and_die("bug in alloctcb");
758 get_tcb_priv_data(const struct tcb *tcp)
760 return tcp->_priv_data;
764 set_tcb_priv_data(struct tcb *tcp, void *const priv_data,
765 void (*const free_priv_data)(void *))
770 tcp->_free_priv_data = free_priv_data;
771 tcp->_priv_data = priv_data;
777 free_tcb_priv_data(struct tcb *tcp)
779 if (tcp->_priv_data) {
780 if (tcp->_free_priv_data) {
781 tcp->_free_priv_data(tcp->_priv_data);
782 tcp->_free_priv_data = NULL;
784 tcp->_priv_data = NULL;
789 droptcb(struct tcb *tcp)
795 for (p = 0; p < SUPPORTED_PERSONALITIES; ++p)
796 free(tcp->inject_vec[p]);
798 free_tcb_priv_data(tcp);
801 if (stack_trace_enabled) {
807 debug_msg("dropped tcb for pid %d, %d remain", tcp->pid, nprocs);
810 if (followfork >= 2) {
811 if (tcp->curcol != 0)
812 fprintf(tcp->outf, " <detached ...>\n");
815 if (printing_tcp == tcp && tcp->curcol != 0)
816 fprintf(tcp->outf, " <detached ...>\n");
817 flush_tcp_output(tcp);
821 if (current_tcp == tcp)
823 if (printing_tcp == tcp)
826 memset(tcp, 0, sizeof(*tcp));
829 /* Detach traced process.
830 * Never call DETACH twice on the same process as both unattached and
831 * attached-unstopped processes give the same ESRCH. For unattached process we
832 * would SIGSTOP it and wait for its SIGSTOP notification forever.
835 detach(struct tcb *tcp)
841 * Linux wrongly insists the child be stopped
842 * before detaching. Arghh. We go through hoops
843 * to make a clean break of things.
846 if (!(tcp->flags & TCB_ATTACHED))
849 /* We attached but possibly didn't see the expected SIGSTOP.
850 * We must catch exactly one as otherwise the detached process
851 * would be left stopped (process state T).
853 if (tcp->flags & TCB_IGNORE_ONE_SIGSTOP)
856 error = ptrace(PTRACE_DETACH, tcp->pid, 0, 0);
858 /* On a clear day, you can see forever. */
861 if (errno != ESRCH) {
862 /* Shouldn't happen. */
863 perror_func_msg("ptrace(PTRACE_DETACH,%u)", tcp->pid);
866 /* ESRCH: process is either not stopped or doesn't exist. */
867 if (my_tkill(tcp->pid, 0) < 0) {
869 /* Shouldn't happen. */
870 perror_func_msg("tkill(%u,0)", tcp->pid);
871 /* else: process doesn't exist. */
874 /* Process is not stopped, need to stop it. */
877 * With SEIZE, tracee can be in group-stop already.
878 * In this state sending it another SIGSTOP does nothing.
879 * Need to use INTERRUPT.
880 * Testcase: trying to ^C a "strace -p <stopped_process>".
882 error = ptrace(PTRACE_INTERRUPT, tcp->pid, 0, 0);
886 perror_func_msg("ptrace(PTRACE_INTERRUPT,%u)", tcp->pid);
888 error = my_tkill(tcp->pid, SIGSTOP);
892 perror_func_msg("tkill(%u,SIGSTOP)", tcp->pid);
894 /* Either process doesn't exist, or some weird error. */
898 /* We end up here in three cases:
899 * 1. We sent PTRACE_INTERRUPT (use_seize case)
900 * 2. We sent SIGSTOP (!use_seize)
901 * 3. Attach SIGSTOP was already pending (TCB_IGNORE_ONE_SIGSTOP set)
905 if (waitpid(tcp->pid, &status, __WALL) < 0) {
909 * if (errno == ECHILD) break;
910 * ^^^ WRONG! We expect this PID to exist,
911 * and want to emit a message otherwise:
913 perror_func_msg("waitpid(%u)", tcp->pid);
916 if (!WIFSTOPPED(status)) {
918 * Tracee exited or was killed by signal.
919 * We shouldn't normally reach this place:
920 * we don't want to consume exit status.
921 * Consider "strace -p PID" being ^C-ed:
922 * we want merely to detach from PID.
924 * However, we _can_ end up here if tracee
929 sig = WSTOPSIG(status);
930 debug_msg("detach wait: event:%d sig:%d",
931 (unsigned) status >> 16, sig);
933 unsigned event = (unsigned)status >> 16;
934 if (event == PTRACE_EVENT_STOP /*&& sig == SIGTRAP*/) {
936 * sig == SIGTRAP: PTRACE_INTERRUPT stop.
937 * sig == other: process was already stopped
938 * with this stopping sig (see tests/detach-stopped).
939 * Looks like re-injecting this sig is not necessary
940 * in DETACH for the tracee to remain stopped.
945 * PTRACE_INTERRUPT is not guaranteed to produce
946 * the above event if other ptrace-stop is pending.
947 * See tests/detach-sleeping testcase:
948 * strace got SIGINT while tracee is sleeping.
949 * We sent PTRACE_INTERRUPT.
950 * We see syscall exit, not PTRACE_INTERRUPT stop.
951 * We won't get PTRACE_INTERRUPT stop
952 * if we would CONT now. Need to DETACH.
954 if (sig == syscall_trap_sig)
956 /* else: not sure in which case we can be here.
957 * Signal stop? Inject it while detaching.
959 ptrace_restart(PTRACE_DETACH, tcp, sig);
962 /* Note: this check has to be after use_seize check */
963 /* (else, in use_seize case SIGSTOP will be mistreated) */
964 if (sig == SIGSTOP) {
965 /* Detach, suppressing SIGSTOP */
966 ptrace_restart(PTRACE_DETACH, tcp, 0);
969 if (sig == syscall_trap_sig)
971 /* Can't detach just yet, may need to wait for SIGSTOP */
972 error = ptrace_restart(PTRACE_CONT, tcp, sig);
974 /* Should not happen.
975 * Note: ptrace_restart returns 0 on ESRCH, so it's not it.
976 * ptrace_restart already emitted error message.
983 if (!qflag && (tcp->flags & TCB_ATTACHED))
984 error_msg("Process %u detached", tcp->pid);
990 process_opt_p_list(char *opt)
994 * We accept -p PID,PID; -p "`pidof PROG`"; -p "`pgrep PROG`".
995 * pidof uses space as delim, pgrep uses newline. :(
998 char *delim = opt + strcspn(opt, "\n\t ,");
1002 pid = string_to_uint(opt);
1004 error_msg_and_die("Invalid process id: '%s'", opt);
1006 if (pid == strace_tracer_pid) {
1007 error_msg_and_die("I'm sorry, I can't let you do that, Dave.");
1018 attach_tcb(struct tcb *const tcp)
1020 if (ptrace_attach_or_seize(tcp->pid) < 0) {
1021 perror_msg("attach: ptrace(%s, %d)",
1022 ptrace_attach_cmd, tcp->pid);
1027 tcp->flags |= TCB_ATTACHED | TCB_GRABBED | TCB_STARTUP |
1028 post_attach_sigstop;
1030 debug_msg("attach to pid %d (main) succeeded", tcp->pid);
1032 static const char task_path[] = "/proc/%d/task";
1033 char procdir[sizeof(task_path) + sizeof(int) * 3];
1035 unsigned int ntid = 0, nerr = 0;
1037 if (followfork && tcp->pid != strace_child &&
1038 xsprintf(procdir, task_path, tcp->pid) > 0 &&
1039 (dir = opendir(procdir)) != NULL) {
1042 while ((de = read_dir(dir)) != NULL) {
1043 if (de->d_fileno == 0)
1046 int tid = string_to_uint(de->d_name);
1047 if (tid <= 0 || tid == tcp->pid)
1051 if (ptrace_attach_or_seize(tid) < 0) {
1053 debug_perror_msg("attach: ptrace(%s, %d)",
1054 ptrace_attach_cmd, tid);
1057 debug_msg("attach to pid %d succeeded", tid);
1059 struct tcb *tid_tcp = alloctcb(tid);
1060 tid_tcp->flags |= TCB_ATTACHED | TCB_GRABBED |
1061 TCB_STARTUP | post_attach_sigstop;
1070 error_msg("Process %u attached"
1072 tcp->pid, ntid - nerr + 1);
1074 error_msg("Process %u attached",
1080 startup_attach(void)
1082 pid_t parent_pid = strace_tracer_pid;
1087 * Block user interruptions as we would leave the traced
1088 * process stopped (process state T) if we would terminate in
1089 * between PTRACE_ATTACH and wait4() on SIGSTOP.
1090 * We rely on cleanup() from this point on.
1093 sigprocmask(SIG_SETMASK, &blocked_set, NULL);
1095 if (daemonized_tracer) {
1098 perror_func_msg_and_die("fork");
1100 if (pid) { /* parent */
1102 * Wait for grandchild to attach to straced process
1103 * (grandparent). Grandchild SIGKILLs us after it attached.
1104 * Grandparent's wait() is unblocked by our death,
1105 * it proceeds to exec the straced program.
1108 _exit(0); /* paranoia */
1111 /* We will be the tracer process. Remember our new pid: */
1112 strace_tracer_pid = getpid();
1115 for (tcbi = 0; tcbi < tcbtabsize; tcbi++) {
1121 /* Is this a process we should attach to, but not yet attached? */
1122 if (tcp->flags & TCB_ATTACHED)
1123 continue; /* no, we already attached it */
1125 if (tcp->pid == parent_pid || tcp->pid == strace_tracer_pid) {
1127 perror_msg("attach: pid %d", tcp->pid);
1135 sigprocmask(SIG_SETMASK, &start_set, NULL);
1138 sigprocmask(SIG_SETMASK, &blocked_set, NULL);
1140 } /* for each tcbtab[] */
1142 if (daemonized_tracer) {
1144 * Make parent go away.
1145 * Also makes grandparent's wait() unblock.
1147 kill(parent_pid, SIGKILL);
1153 sigprocmask(SIG_SETMASK, &start_set, NULL);
1156 /* Stack-o-phobic exec helper, in the hope to work around
1157 * NOMMU + "daemonized tracer" difficulty.
1159 struct exec_params {
1165 struct sigaction child_sa;
1167 static struct exec_params params_for_tracee;
1169 static void ATTRIBUTE_NOINLINE ATTRIBUTE_NORETURN
1172 struct exec_params *params = ¶ms_for_tracee;
1174 if (params->fd_to_close >= 0)
1175 close(params->fd_to_close);
1176 if (!daemonized_tracer && !use_seize) {
1177 if (ptrace(PTRACE_TRACEME, 0L, 0L, 0L) < 0) {
1178 perror_msg_and_die("ptrace(PTRACE_TRACEME, ...)");
1182 if (username != NULL) {
1184 * It is important to set groups before we
1185 * lose privileges on setuid.
1187 if (initgroups(username, run_gid) < 0) {
1188 perror_msg_and_die("initgroups");
1190 if (setregid(run_gid, params->run_egid) < 0) {
1191 perror_msg_and_die("setregid");
1193 if (setreuid(run_uid, params->run_euid) < 0) {
1194 perror_msg_and_die("setreuid");
1196 } else if (geteuid() != 0)
1197 if (setreuid(run_uid, run_uid) < 0) {
1198 perror_msg_and_die("setreuid");
1201 if (!daemonized_tracer) {
1203 * Induce a ptrace stop. Tracer (our parent)
1204 * will resume us with PTRACE_SYSCALL and display
1205 * the immediately following execve syscall.
1206 * Can't do this on NOMMU systems, we are after
1207 * vfork: parent is blocked, stopping would deadlock.
1210 kill(getpid(), SIGSTOP);
1213 /* we depend on SIGCHLD set to SIG_DFL by init code */
1214 /* if it happens to be SIG_IGN'ed, wait won't block */
1219 if (params_for_tracee.child_sa.sa_handler != SIG_DFL)
1220 sigaction(SIGCHLD, ¶ms_for_tracee.child_sa, NULL);
1222 execv(params->pathname, params->argv);
1223 perror_msg_and_die("exec");
1227 * Open a dummy descriptor for use as a placeholder.
1228 * The descriptor is O_RDONLY with FD_CLOEXEC flag set.
1229 * A read attempt from such descriptor ends with EOF,
1230 * a write attempt is rejected with EBADF.
1233 open_dummy_desc(void)
1238 perror_func_msg_and_die("pipe");
1240 set_cloexec_flag(fds[0]);
1244 /* placeholder fds status for stdin and stdout */
1245 static bool fd_is_placeholder[2];
1248 * Ensure that all standard file descriptors are open by opening placeholder
1249 * file descriptors for those standard file descriptors that are not open.
1251 * The information which descriptors have been made open is saved
1252 * in fd_is_placeholder for later use.
1255 ensure_standard_fds_opened(void)
1259 while ((fd = open_dummy_desc()) <= 2) {
1262 fd_is_placeholder[fd] = true;
1270 * Redirect stdin and stdout unless they have been opened earlier
1271 * by ensure_standard_fds_opened as placeholders.
1274 redirect_standard_fds(void)
1279 * It might be a good idea to redirect stderr as well,
1280 * but we sometimes need to print error messages.
1282 for (i = 0; i <= 1; ++i) {
1283 if (!fd_is_placeholder[i]) {
1291 startup_child(char **argv)
1293 struct_stat statbuf;
1294 const char *filename;
1295 size_t filename_len;
1296 char pathname[PATH_MAX];
1301 filename_len = strlen(filename);
1303 if (filename_len > sizeof(pathname) - 1) {
1304 errno = ENAMETOOLONG;
1305 perror_msg_and_die("exec");
1307 if (strchr(filename, '/')) {
1308 strcpy(pathname, filename);
1310 #ifdef USE_DEBUGGING_EXEC
1312 * Debuggers customarily check the current directory
1313 * first regardless of the path but doing that gives
1314 * security geeks a panic attack.
1316 else if (stat_file(filename, &statbuf) == 0)
1317 strcpy(pathname, filename);
1318 #endif /* USE_DEBUGGING_EXEC */
1323 for (path = getenv("PATH"); path && *path; path += m) {
1324 const char *colon = strchr(path, ':');
1329 m = n = strlen(path);
1331 if (!getcwd(pathname, PATH_MAX))
1333 len = strlen(pathname);
1334 } else if (n > sizeof(pathname) - 1)
1337 strncpy(pathname, path, n);
1340 if (len && pathname[len - 1] != '/')
1341 pathname[len++] = '/';
1342 if (filename_len + len > sizeof(pathname) - 1)
1344 strcpy(pathname + len, filename);
1345 if (stat_file(pathname, &statbuf) == 0 &&
1346 /* Accept only regular files
1347 with some execute bits set.
1348 XXX not perfect, might still fail */
1349 S_ISREG(statbuf.st_mode) &&
1350 (statbuf.st_mode & 0111))
1353 if (!path || !*path)
1356 if (stat_file(pathname, &statbuf) < 0) {
1357 perror_msg_and_die("Can't stat '%s'", filename);
1360 params_for_tracee.fd_to_close = (shared_log != stderr) ? fileno(shared_log) : -1;
1361 params_for_tracee.run_euid = (statbuf.st_mode & S_ISUID) ? statbuf.st_uid : run_uid;
1362 params_for_tracee.run_egid = (statbuf.st_mode & S_ISGID) ? statbuf.st_gid : run_gid;
1363 params_for_tracee.argv = argv;
1365 * On NOMMU, can be safely freed only after execve in tracee.
1366 * It's hard to know when that happens, so we just leak it.
1368 params_for_tracee.pathname = NOMMU_SYSTEM ? xstrdup(pathname) : pathname;
1370 #if defined HAVE_PRCTL && defined PR_SET_PTRACER && defined PR_SET_PTRACER_ANY
1371 if (daemonized_tracer)
1372 prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY);
1377 perror_func_msg_and_die("fork");
1379 if ((pid != 0 && daemonized_tracer)
1380 || (pid == 0 && !daemonized_tracer)
1382 /* We are to become the tracee. Two cases:
1384 * not -D: we are child
1389 /* We are the tracer */
1391 if (!daemonized_tracer) {
1394 /* child did PTRACE_TRACEME, nothing to do in parent */
1396 if (!NOMMU_SYSTEM) {
1397 /* Wait until child stopped itself */
1399 while (waitpid(pid, &status, WSTOPPED) < 0) {
1402 perror_msg_and_die("waitpid");
1404 if (!WIFSTOPPED(status) || WSTOPSIG(status) != SIGSTOP) {
1405 kill_save_errno(pid, SIGKILL);
1406 perror_msg_and_die("Unexpected wait status %#x",
1410 /* Else: NOMMU case, we have no way to sync.
1411 * Just attach to it as soon as possible.
1412 * This means that we may miss a few first syscalls...
1415 if (ptrace_attach_or_seize(pid)) {
1416 kill_save_errno(pid, SIGKILL);
1417 perror_msg_and_die("attach: ptrace(%s, %d)",
1418 ptrace_attach_cmd, pid);
1423 tcp = alloctcb(pid);
1424 tcp->flags |= TCB_ATTACHED | TCB_STARTUP
1425 | TCB_SKIP_DETACH_ON_FIRST_EXEC
1426 | (NOMMU_SYSTEM ? 0 : (TCB_HIDE_LOG | post_attach_sigstop));
1429 /* With -D, we are *child* here, the tracee is our parent. */
1430 strace_child = strace_tracer_pid;
1431 strace_tracer_pid = getpid();
1432 tcp = alloctcb(strace_child);
1433 tcp->flags |= TCB_SKIP_DETACH_ON_FIRST_EXEC | TCB_HIDE_LOG;
1434 /* attaching will be done later, by startup_attach */
1435 /* note: we don't do newoutf(tcp) here either! */
1437 /* NOMMU BUG! -D mode is active, we (child) return,
1438 * and we will scribble over parent's stack!
1439 * When parent later unpauses, it segfaults.
1442 * (1) by declaring exec_or_die() NORETURN,
1443 * hopefully compiler will just jump to it
1444 * instead of call (won't push anything to stack),
1445 * (2) by trying very hard in exec_or_die()
1446 * to not use any stack,
1447 * (3) having a really big (PATH_MAX) stack object
1448 * in this function, which creates a "buffer" between
1449 * child's and parent's stack pointers.
1450 * This may save us if (1) and (2) failed
1451 * and compiler decided to use stack in exec_or_die() anyway
1452 * (happens on i386 because of stack parameter passing).
1454 * A cleaner solution is to use makecontext + setcontext
1455 * to create a genuine separate stack and execute on it.
1459 * A case where straced process is part of a pipe:
1460 * { sleep 1; yes | head -n99999; } | strace -o/dev/null sh -c 'exec <&-; sleep 9'
1461 * If strace won't close its fd#0, closing it in tracee is not enough:
1462 * the pipe is still open, it has a reader. Thus, "head" will not get its
1463 * SIGPIPE at once, on the first write.
1465 * Preventing it by redirecting strace's stdin/out.
1466 * (Don't leave fds 0 and 1 closed, this is bad practice: future opens
1467 * will reuse them, unexpectedly making a newly opened object "stdin").
1469 redirect_standard_fds();
1474 test_ptrace_seize(void)
1478 /* Need fork for test. NOMMU has no forks */
1480 post_attach_sigstop = 0; /* this sets use_seize to 1 */
1486 perror_func_msg_and_die("fork");
1493 /* PTRACE_SEIZE, unlike ATTACH, doesn't force tracee to trap. After
1494 * attaching tracee continues to run unless a trap condition occurs.
1495 * PTRACE_SEIZE doesn't affect signal or group stop state.
1497 if (ptrace(PTRACE_SEIZE, pid, 0, 0) == 0) {
1498 post_attach_sigstop = 0; /* this sets use_seize to 1 */
1500 debug_msg("PTRACE_SEIZE doesn't work");
1506 int status, tracee_pid;
1509 tracee_pid = waitpid(pid, &status, 0);
1510 if (tracee_pid <= 0) {
1513 perror_func_msg_and_die("unexpected wait result %d",
1516 if (WIFSIGNALED(status))
1519 error_func_msg_and_die("unexpected wait status %#x", status);
1522 #else /* !USE_SEIZE */
1523 # define test_ptrace_seize() ((void)0)
1527 get_os_release(void)
1533 perror_msg_and_die("uname");
1534 /* u.release has this form: "3.2.9[-some-garbage]" */
1538 if (!(*p >= '0' && *p <= '9'))
1539 error_msg_and_die("Bad OS release string: '%s'", u.release);
1540 /* Note: this open-codes KERNEL_VERSION(): */
1541 rel = (rel << 8) | atoi(p);
1542 if (rel >= KERNEL_VERSION(1, 0, 0))
1544 while (*p >= '0' && *p <= '9')
1547 if (rel >= KERNEL_VERSION(0, 1, 0)) {
1548 /* "X.Y-something" means "X.Y.0" */
1552 error_msg_and_die("Bad OS release string: '%s'", u.release);
1560 set_sighandler(int signo, void (*sighandler)(int), struct sigaction *oldact)
1562 /* if signal handler is a function, add the signal to blocked_set */
1563 if (sighandler != SIG_IGN && sighandler != SIG_DFL)
1564 sigaddset(&blocked_set, signo);
1566 const struct sigaction sa = { .sa_handler = sighandler };
1567 sigaction(signo, &sa, oldact);
1571 * Initialization part of main() was eating much stack (~0.5k),
1572 * which was unused after init.
1573 * We can reuse it if we move init code into a separate function.
1575 * Don't want main() to inline us and defeat the reason
1576 * we have a separate function.
1578 static void ATTRIBUTE_NOINLINE
1579 init(int argc, char *argv[])
1584 if (!program_invocation_name || !*program_invocation_name) {
1585 static char name[] = "strace";
1586 program_invocation_name =
1587 (argc > 0 && argv[0] && *argv[0]) ? argv[0] : name;
1590 strace_tracer_pid = getpid();
1592 os_release = get_os_release();
1594 shared_log = stderr;
1595 set_sortby(DEFAULT_SORTBY);
1596 set_personality(DEFAULT_PERSONALITY);
1597 qualify("trace=all");
1598 qualify("abbrev=all");
1599 qualify("verbose=all");
1600 #if DEFAULT_QUAL_FLAGS != (QUAL_TRACE | QUAL_ABBREV | QUAL_VERBOSE)
1601 # error Bug in DEFAULT_QUAL_FLAGS
1603 qualify("signal=all");
1604 while ((c = getopt(argc, argv, "+"
1605 #ifdef USE_LIBUNWIND
1608 "a:b:cCdDe:E:fFhiI:o:O:p:P:qrs:S:tTu:vVwxyz")) != EOF) {
1611 acolumn = string_to_uint(optarg);
1613 error_opt_arg(c, optarg);
1616 if (strcmp(optarg, "execve") != 0)
1617 error_msg_and_die("Syscall '%s' for -b isn't supported",
1619 detach_on_execve = 1;
1622 if (cflag == CFLAG_BOTH) {
1623 error_msg_and_help("-c and -C are mutually exclusive");
1625 cflag = CFLAG_ONLY_STATS;
1628 if (cflag == CFLAG_ONLY_STATS) {
1629 error_msg_and_help("-c and -C are mutually exclusive");
1637 daemonized_tracer = 1;
1643 if (putenv(optarg) < 0)
1644 perror_msg_and_die("putenv");
1659 opt_intr = string_to_uint_upto(optarg, NUM_INTR_OPTS - 1);
1661 error_opt_arg(c, optarg);
1663 #ifdef USE_LIBUNWIND
1665 stack_trace_enabled = true;
1672 i = string_to_uint(optarg);
1674 error_opt_arg(c, optarg);
1678 process_opt_p_list(optarg);
1681 pathtrace_select(optarg);
1690 i = string_to_uint(optarg);
1691 if (i < 0 || (unsigned int) i > -1U / 4)
1692 error_opt_arg(c, optarg);
1708 qualify("abbrev=none");
1715 count_wallclock = 1;
1724 not_failing_only = 1;
1727 error_msg_and_help(NULL);
1735 if (argc < 0 || (!nprocs && !argc)) {
1736 error_msg_and_help("must have PROG [ARGS] or -p PID");
1739 if (!argc && daemonized_tracer) {
1740 error_msg_and_help("PROG [ARGS] must be specified with -D");
1745 error_msg("deprecated option -F ignored");
1747 error_msg("option -F is deprecated, "
1748 "please use -f instead");
1753 if (followfork >= 2 && cflag) {
1754 error_msg_and_help("(-c or -C) and -ff are mutually exclusive");
1757 if (count_wallclock && !cflag) {
1758 error_msg_and_help("-w must be given with (-c or -C)");
1761 if (cflag == CFLAG_ONLY_STATS) {
1763 error_msg("-%c has no effect with -c", 'i');
1764 #ifdef USE_LIBUNWIND
1765 if (stack_trace_enabled)
1766 error_msg("-%c has no effect with -c", 'k');
1769 error_msg("-%c has no effect with -c", 'r');
1771 error_msg("-%c has no effect with -c", 't');
1773 error_msg("-%c has no effect with -c", 'T');
1775 error_msg("-%c has no effect with -c", 'y');
1780 error_msg("-tt has no effect with -r");
1784 acolumn_spaces = xmalloc(acolumn + 1);
1785 memset(acolumn_spaces, ' ', acolumn);
1786 acolumn_spaces[acolumn] = '\0';
1788 sigprocmask(SIG_SETMASK, NULL, &start_set);
1789 memcpy(&blocked_set, &start_set, sizeof(blocked_set));
1791 set_sighandler(SIGCHLD, SIG_DFL, ¶ms_for_tracee.child_sa);
1793 #ifdef USE_LIBUNWIND
1794 if (stack_trace_enabled) {
1798 for (tcbi = 0; tcbi < tcbtabsize; ++tcbi) {
1799 unwind_tcb_init(tcbtab[tcbi]);
1804 /* See if they want to run as another user. */
1805 if (username != NULL) {
1806 struct passwd *pent;
1808 if (getuid() != 0 || geteuid() != 0) {
1809 error_msg_and_die("You must be root to use the -u option");
1811 pent = getpwnam(username);
1813 error_msg_and_die("Cannot find user '%s'", username);
1815 run_uid = pent->pw_uid;
1816 run_gid = pent->pw_gid;
1823 ptrace_setoptions |= PTRACE_O_TRACECLONE |
1824 PTRACE_O_TRACEFORK |
1825 PTRACE_O_TRACEVFORK;
1826 debug_msg("ptrace_setoptions = %#x", ptrace_setoptions);
1827 test_ptrace_seize();
1830 * Is something weird with our stdin and/or stdout -
1831 * for example, may they be not open? In this case,
1832 * ensure that none of the future opens uses them.
1834 * This was seen in the wild when /proc/sys/kernel/core_pattern
1835 * was set to "|/bin/strace -o/tmp/LOG PROG":
1836 * kernel runs coredump helper with fd#0 open but fd#1 closed (!),
1837 * therefore LOG gets opened to fd#1, and fd#1 is closed by
1838 * "don't hold up stdin/out open" code soon after.
1840 ensure_standard_fds_opened();
1842 /* Check if they want to redirect the output. */
1844 /* See if they want to pipe the output. */
1845 if (outfname[0] == '|' || outfname[0] == '!') {
1847 * We can't do the <outfname>.PID funny business
1848 * when using popen, so prohibit it.
1850 if (followfork >= 2)
1851 error_msg_and_help("piping the output and -ff "
1852 "are mutually exclusive");
1853 shared_log = strace_popen(outfname + 1);
1854 } else if (followfork < 2) {
1855 shared_log = strace_fopen(outfname);
1856 } else if (strlen(outfname) >= PATH_MAX - sizeof(int) * 3) {
1857 errno = ENAMETOOLONG;
1858 perror_msg_and_die("%s", outfname);
1861 /* -ff without -o FILE is the same as single -f */
1862 if (followfork >= 2)
1866 if (!outfname || outfname[0] == '|' || outfname[0] == '!') {
1867 setvbuf(shared_log, NULL, _IOLBF, 0);
1871 * argv[0] -pPID -oFILE Default interactive setting
1872 * yes * 0 INTR_WHILE_WAIT
1873 * no 1 0 INTR_WHILE_WAIT
1874 * yes * 1 INTR_NEVER
1875 * no 1 1 INTR_WHILE_WAIT
1878 if (outfname && argc) {
1880 opt_intr = INTR_NEVER;
1885 opt_intr = INTR_WHILE_WAIT;
1888 * startup_child() must be called before the signal handlers get
1889 * installed below as they are inherited into the spawned process.
1890 * Also we do not need to be protected by them as during interruption
1891 * in the startup_child() mode we kill the spawned process anyway.
1894 startup_child(argv);
1897 set_sighandler(SIGTTOU, SIG_IGN, NULL);
1898 set_sighandler(SIGTTIN, SIG_IGN, NULL);
1899 if (opt_intr != INTR_ANYWHERE) {
1900 if (opt_intr == INTR_BLOCK_TSTP_TOO)
1901 set_sighandler(SIGTSTP, SIG_IGN, NULL);
1903 * In interactive mode (if no -o OUTFILE, or -p PID is used),
1904 * fatal signals are blocked while syscall stop is processed,
1905 * and acted on in between, when waiting for new syscall stops.
1906 * In non-interactive mode, signals are ignored.
1908 set_sighandler(SIGHUP, interactive ? interrupt : SIG_IGN, NULL);
1909 set_sighandler(SIGINT, interactive ? interrupt : SIG_IGN, NULL);
1910 set_sighandler(SIGQUIT, interactive ? interrupt : SIG_IGN, NULL);
1911 set_sighandler(SIGPIPE, interactive ? interrupt : SIG_IGN, NULL);
1912 set_sighandler(SIGTERM, interactive ? interrupt : SIG_IGN, NULL);
1915 if (nprocs != 0 || daemonized_tracer)
1918 /* Do we want pids printed in our -o OUTFILE?
1919 * -ff: no (every pid has its own file); or
1920 * -f: yes (there can be more pids in the future); or
1921 * -p PID1,PID2: yes (there are already more than one pid)
1923 print_pid_pfx = (outfname && followfork < 2 && (followfork == 1 || nprocs > 1));
1934 for (i = 0; i < tcbtabsize; i++) {
1935 struct tcb *tcp = tcbtab[i];
1936 if (tcp->pid == pid)
1950 /* 'interrupted' is a volatile object, fetch it only once */
1951 fatal_sig = interrupted;
1953 fatal_sig = SIGTERM;
1955 for (i = 0; i < tcbtabsize; i++) {
1959 debug_func_msg("looking at pid %u", tcp->pid);
1960 if (tcp->pid == strace_child) {
1961 kill(tcp->pid, SIGCONT);
1962 kill(tcp->pid, fatal_sig);
1967 call_summary(shared_log);
1977 print_debug_info(const int pid, int status)
1979 const unsigned int event = (unsigned int) status >> 16;
1980 char buf[sizeof("WIFEXITED,exitcode=%u") + sizeof(int)*3 /*paranoia:*/ + 16];
1981 char evbuf[sizeof(",EVENT_VFORK_DONE (%u)") + sizeof(int)*3 /*paranoia:*/ + 16];
1984 if (WIFSIGNALED(status))
1986 xsprintf(buf, "WIFSIGNALED,%ssig=%s",
1987 WCOREDUMP(status) ? "core," : "",
1988 signame(WTERMSIG(status)));
1990 xsprintf(buf, "WIFSIGNALED,sig=%s",
1991 signame(WTERMSIG(status)));
1993 if (WIFEXITED(status))
1994 xsprintf(buf, "WIFEXITED,exitcode=%u", WEXITSTATUS(status));
1995 if (WIFSTOPPED(status))
1996 xsprintf(buf, "WIFSTOPPED,sig=%s", signame(WSTOPSIG(status)));
1999 static const char *const event_names[] = {
2000 [PTRACE_EVENT_CLONE] = "CLONE",
2001 [PTRACE_EVENT_FORK] = "FORK",
2002 [PTRACE_EVENT_VFORK] = "VFORK",
2003 [PTRACE_EVENT_VFORK_DONE] = "VFORK_DONE",
2004 [PTRACE_EVENT_EXEC] = "EXEC",
2005 [PTRACE_EVENT_EXIT] = "EXIT",
2006 /* [PTRACE_EVENT_STOP (=128)] would make biggish array */
2008 const char *e = "??";
2009 if (event < ARRAY_SIZE(event_names))
2010 e = event_names[event];
2011 else if (event == PTRACE_EVENT_STOP)
2013 xsprintf(evbuf, ",EVENT_%s (%u)", e, event);
2015 error_msg("[wait(0x%06x) = %u] %s%s", status, pid, buf, evbuf);
2019 maybe_allocate_tcb(const int pid, int status)
2021 if (!WIFSTOPPED(status)) {
2022 if (detach_on_execve && pid == strace_child) {
2023 /* example: strace -bexecve sh -c 'exec true' */
2028 * This can happen if we inherited an unknown child.
2029 * Example: (sleep 1 & exec strace true)
2031 error_msg("Exit of unknown pid %u ignored", pid);
2035 /* We assume it's a fork/vfork/clone child */
2036 struct tcb *tcp = alloctcb(pid);
2037 tcp->flags |= TCB_ATTACHED | TCB_STARTUP | post_attach_sigstop;
2040 error_msg("Process %d attached", pid);
2044 * This can happen if a clone call misused CLONE_PTRACE itself.
2046 * There used to be a dance around possible re-injection of
2047 * WSTOPSIG(status), but it was later removed as the only
2048 * observable stop here is the initial ptrace-stop.
2050 ptrace(PTRACE_DETACH, pid, NULL, 0L);
2051 error_msg("Detached unknown pid %d", pid);
2057 maybe_switch_tcbs(struct tcb *tcp, const int pid)
2060 struct tcb *execve_thread;
2063 if (ptrace(PTRACE_GETEVENTMSG, pid, NULL, &old_pid) < 0)
2065 /* Avoid truncation in pid2tcb() param passing */
2066 if (old_pid <= 0 || old_pid == pid)
2068 if ((unsigned long) old_pid > UINT_MAX)
2070 execve_thread = pid2tcb(old_pid);
2071 /* It should be !NULL, but I feel paranoid */
2075 if (execve_thread->curcol != 0) {
2077 * One case we are here is -ff:
2078 * try "strace -oLOG -ff test/threaded_execve"
2080 fprintf(execve_thread->outf, " <pid changed to %d ...>\n", pid);
2081 /*execve_thread->curcol = 0; - no need, see code below */
2083 /* Swap output FILEs (needed for -ff) */
2084 fp = execve_thread->outf;
2085 execve_thread->outf = tcp->outf;
2087 /* And their column positions */
2088 execve_thread->curcol = tcp->curcol;
2090 /* Drop leader, but close execve'd thread outfile (if -ff) */
2092 /* Switch to the thread, reusing leader's outfile and pid */
2093 tcp = execve_thread;
2095 if (cflag != CFLAG_ONLY_STATS) {
2097 tprintf("+++ superseded by execve in pid %lu +++\n", old_pid);
2099 tcp->flags |= TCB_REPRINT;
2106 print_signalled(struct tcb *tcp, const int pid, int status)
2108 if (pid == strace_child) {
2109 exit_code = 0x100 | WTERMSIG(status);
2113 if (cflag != CFLAG_ONLY_STATS
2114 && is_number_in_set(WTERMSIG(status), signal_set)) {
2117 tprintf("+++ killed by %s %s+++\n",
2118 signame(WTERMSIG(status)),
2119 WCOREDUMP(status) ? "(core dumped) " : "");
2121 tprintf("+++ killed by %s +++\n",
2122 signame(WTERMSIG(status)));
2129 print_exited(struct tcb *tcp, const int pid, int status)
2131 if (pid == strace_child) {
2132 exit_code = WEXITSTATUS(status);
2136 if (cflag != CFLAG_ONLY_STATS &&
2139 tprintf("+++ exited with %d +++\n", WEXITSTATUS(status));
2145 print_stopped(struct tcb *tcp, const siginfo_t *si, const unsigned int sig)
2147 if (cflag != CFLAG_ONLY_STATS
2149 && is_number_in_set(sig, signal_set)) {
2152 tprintf("--- %s ", signame(sig));
2156 tprintf("--- stopped by %s ---\n", signame(sig));
2162 startup_tcb(struct tcb *tcp)
2164 debug_msg("pid %d has TCB_STARTUP, initializing it", tcp->pid);
2166 tcp->flags &= ~TCB_STARTUP;
2169 debug_msg("setting opts 0x%x on pid %d",
2170 ptrace_setoptions, tcp->pid);
2171 if (ptrace(PTRACE_SETOPTIONS, tcp->pid, NULL, ptrace_setoptions) < 0) {
2172 if (errno != ESRCH) {
2173 /* Should never happen, really */
2174 perror_msg_and_die("PTRACE_SETOPTIONS");
2179 if ((tcp->flags & TCB_GRABBED) && (get_scno(tcp) == 1))
2180 tcp->s_prev_ent = tcp->s_ent;
2184 print_event_exit(struct tcb *tcp)
2186 if (entering(tcp) || filtered(tcp) || hide_log(tcp)
2187 || cflag == CFLAG_ONLY_STATS) {
2191 if (followfork < 2 && printing_tcp && printing_tcp != tcp
2192 && printing_tcp->curcol != 0) {
2193 current_tcp = printing_tcp;
2194 tprints(" <unfinished ...>\n");
2195 flush_tcp_output(printing_tcp);
2196 printing_tcp->curcol = 0;
2200 if ((followfork < 2 && printing_tcp != tcp)
2201 || (tcp->flags & TCB_REPRINT)) {
2202 tcp->flags &= ~TCB_REPRINT;
2204 tprintf("<... %s resumed>", tcp->s_ent->sys_name);
2207 if (!(tcp->sys_func_rval & RVAL_DECODED)) {
2209 * The decoder has probably decided to print something
2210 * on exiting syscall which is not going to happen.
2212 tprints(" <unfinished ...>");
2220 static enum trace_event
2221 next_event(int *pstatus, siginfo_t *si)
2233 * Used to exit simply when nprocs hits zero, but in this testcase:
2234 * int main(void) { _exit(!!fork()); }
2235 * under strace -f, parent sometimes (rarely) manages
2236 * to exit before we see the first stop of the child,
2237 * and we are losing track of it:
2238 * 19923 clone(...) = 19924
2239 * 19923 exit_group(1) = ?
2240 * 19923 +++ exited with 1 +++
2241 * Exiting only when wait() returns ECHILD works better.
2243 if (popen_pid != 0) {
2244 /* However, if -o|logger is in use, we can't do that.
2245 * Can work around that by double-forking the logger,
2246 * but that loses the ability to wait for its completion
2247 * on exit. Oh well...
2254 sigprocmask(SIG_SETMASK, &start_set, NULL);
2255 pid = wait4(-1, pstatus, __WALL, (cflag ? &ru : NULL));
2258 sigprocmask(SIG_SETMASK, &blocked_set, NULL);
2261 if (wait_errno == EINTR)
2263 if (nprocs == 0 && wait_errno == ECHILD)
2266 * If nprocs > 0, ECHILD is not expected,
2267 * treat it as any other error here:
2270 perror_msg_and_die("wait4(__WALL)");
2275 if (pid == popen_pid) {
2276 if (!WIFSTOPPED(status))
2282 print_debug_info(pid, status);
2284 /* Look up 'pid' in our table. */
2288 tcp = maybe_allocate_tcb(pid, status);
2295 /* Set current output file */
2299 tv_sub(&tcp->dtime, &ru.ru_stime, &tcp->stime);
2300 tcp->stime = ru.ru_stime;
2303 if (WIFSIGNALED(status))
2304 return TE_SIGNALLED;
2306 if (WIFEXITED(status))
2310 * As WCONTINUED flag has not been specified to wait4,
2311 * it cannot be WIFCONTINUED(status), so the only case
2312 * that remains is WIFSTOPPED(status).
2315 /* Is this the very first time we see this tracee stopped? */
2316 if (tcp->flags & TCB_STARTUP)
2319 const unsigned int sig = WSTOPSIG(status);
2320 const unsigned int event = (unsigned int) status >> 16;
2325 * Is this post-attach SIGSTOP?
2326 * Interestingly, the process may stop
2327 * with STOPSIG equal to some other signal
2328 * than SIGSTOP if we happened to attach
2329 * just before the process takes a signal.
2331 if (sig == SIGSTOP && (tcp->flags & TCB_IGNORE_ONE_SIGSTOP)) {
2332 debug_func_msg("ignored SIGSTOP on pid %d", tcp->pid);
2333 tcp->flags &= ~TCB_IGNORE_ONE_SIGSTOP;
2335 } else if (sig == syscall_trap_sig) {
2336 return TE_SYSCALL_STOP;
2338 *si = (siginfo_t) {};
2340 * True if tracee is stopped by signal
2341 * (as opposed to "tracee received signal").
2342 * TODO: shouldn't we check for errno == EINVAL too?
2343 * We can get ESRCH instead, you know...
2345 bool stopped = ptrace(PTRACE_GETSIGINFO, pid, 0, si) < 0;
2346 return stopped ? TE_GROUP_STOP : TE_SIGNAL_DELIVERY_STOP;
2350 case PTRACE_EVENT_STOP:
2352 * PTRACE_INTERRUPT-stop or group-stop.
2353 * PTRACE_INTERRUPT-stop has sig == SIGTRAP here.
2360 return TE_GROUP_STOP;
2364 case PTRACE_EVENT_EXEC:
2365 return TE_STOP_BEFORE_EXECVE;
2366 case PTRACE_EVENT_EXIT:
2367 return TE_STOP_BEFORE_EXIT;
2374 trace_syscall(struct tcb *tcp, unsigned int *sig)
2376 if (entering(tcp)) {
2377 int res = syscall_entering_decode(tcp);
2382 res = syscall_entering_trace(tcp, sig);
2384 syscall_entering_finish(tcp, res);
2387 struct timeval tv = {};
2388 int res = syscall_exiting_decode(tcp, &tv);
2390 res = syscall_exiting_trace(tcp, tv, res);
2392 syscall_exiting_finish(tcp);
2397 /* Returns true iff the main trace loop has to continue. */
2399 dispatch_event(enum trace_event ret, int *pstatus, siginfo_t *si)
2401 unsigned int restart_op = PTRACE_SYSCALL;
2402 unsigned int restart_sig = 0;
2414 case TE_SYSCALL_STOP:
2415 if (trace_syscall(current_tcp, &restart_sig) < 0) {
2417 * ptrace() failed in trace_syscall().
2418 * Likely a result of process disappearing mid-flight.
2419 * Observed case: exit_group() or SIGKILL terminating
2420 * all processes in thread group.
2421 * We assume that ptrace error was caused by process death.
2422 * We used to detach(current_tcp) here, but since we no
2423 * longer implement "detach before death" policy/hack,
2424 * we can let this process to report its death to us
2425 * normally, via WIFEXITED or WIFSIGNALED wait status.
2431 case TE_SIGNAL_DELIVERY_STOP:
2432 restart_sig = WSTOPSIG(*pstatus);
2433 print_stopped(current_tcp, si, restart_sig);
2437 print_signalled(current_tcp, current_tcp->pid, *pstatus);
2438 droptcb(current_tcp);
2442 restart_sig = WSTOPSIG(*pstatus);
2443 print_stopped(current_tcp, NULL, restart_sig);
2446 * This ends ptrace-stop, but does *not* end group-stop.
2447 * This makes stopping signals work properly on straced
2448 * process (that is, process really stops. It used to
2451 restart_op = PTRACE_LISTEN;
2457 print_exited(current_tcp, current_tcp->pid, *pstatus);
2458 droptcb(current_tcp);
2461 case TE_STOP_BEFORE_EXECVE:
2463 * Under Linux, execve changes pid to thread leader's pid,
2464 * and we see this changed pid on EVENT_EXEC and later,
2465 * execve sysexit. Leader "disappears" without exit
2466 * notification. Let user know that, drop leader's tcb,
2467 * and fix up pid in execve thread's tcb.
2468 * Effectively, execve thread's tcb replaces leader's tcb.
2470 * BTW, leader is 'stuck undead' (doesn't report WIFEXITED
2471 * on exit syscall) in multithreaded programs exactly
2472 * in order to handle this case.
2474 * PTRACE_GETEVENTMSG returns old pid starting from Linux 3.0.
2475 * On 2.6 and earlier, it can return garbage.
2477 if (os_release >= KERNEL_VERSION(3, 0, 0))
2478 current_tcp = maybe_switch_tcbs(current_tcp, current_tcp->pid);
2480 if (detach_on_execve) {
2481 if (current_tcp->flags & TCB_SKIP_DETACH_ON_FIRST_EXEC) {
2482 current_tcp->flags &= ~TCB_SKIP_DETACH_ON_FIRST_EXEC;
2484 detach(current_tcp); /* do "-b execve" thingy */
2490 case TE_STOP_BEFORE_EXIT:
2491 print_event_exit(current_tcp);
2495 /* We handled quick cases, we are permitted to interrupt now. */
2499 if (ptrace_restart(restart_op, current_tcp, restart_sig) < 0) {
2500 /* Note: ptrace_restart emitted error message */
2507 #ifdef ENABLE_COVERAGE_GCOV
2508 extern void __gcov_flush(void);
2511 static void ATTRIBUTE_NORETURN
2516 if (shared_log != stderr)
2519 while (waitpid(popen_pid, NULL, 0) < 0 && errno == EINTR)
2522 if (exit_code > 0xff) {
2523 /* Avoid potential core file clobbering. */
2524 struct_rlimit rlim = {0, 0};
2525 set_rlimit(RLIMIT_CORE, &rlim);
2527 /* Child was killed by a signal, mimic that. */
2529 signal(exit_code, SIG_DFL);
2530 #ifdef ENABLE_COVERAGE_GCOV
2535 /* Unblock the signal. */
2538 sigaddset(&mask, exit_code);
2539 #ifdef ENABLE_COVERAGE_GCOV
2542 sigprocmask(SIG_UNBLOCK, &mask, NULL);
2544 /* Paranoia - what if this signal is not fatal?
2545 Exit with 128 + signo then. */
2552 main(int argc, char *argv[])
2556 exit_code = !nprocs;
2560 while (dispatch_event(next_event(&status, &si), &status, &si))