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-2018 The strace developers.
9 * SPDX-License-Identifier: LGPL-2.1-or-later
18 #include <sys/resource.h>
27 #include <sys/utsname.h>
29 # include <sys/prctl.h>
31 #include <asm/unistd.h>
33 #include "kill_save_errno.h"
34 #include "largefile_wrappers.h"
35 #include "mmap_cache.h"
36 #include "number_set.h"
37 #include "ptrace_syscall_info.h"
39 #include "printsiginfo.h"
40 #include "trace_event.h"
45 /* In some libc, these aren't declared. Do it ourself: */
46 extern char **environ;
50 #ifdef ENABLE_STACKTRACE
51 /* if this is true do the stack trace for every system call */
52 bool stack_trace_enabled;
55 #define my_tkill(tid, sig) syscall(__NR_tkill, (tid), (sig))
57 /* Glue for systems without a MMU that cannot provide fork() */
58 #if !defined(HAVE_FORK)
60 # define NOMMU_SYSTEM 1
63 # define fork() vfork()
66 const unsigned int syscall_trap_sig = SIGTRAP | 0x80;
68 cflag_t cflag = CFLAG_NONE;
69 unsigned int followfork;
70 unsigned int ptrace_setoptions = PTRACE_O_TRACESYSGOOD | PTRACE_O_TRACEEXEC
78 static unsigned int tflag;
80 static bool print_pid_pfx;
85 INTR_ANYWHERE = 1, /* don't block/ignore any signals */
86 INTR_WHILE_WAIT = 2, /* block fatal signals while decoding syscall. default */
87 INTR_NEVER = 3, /* block fatal signals. default if '-o FILE PROG' */
88 INTR_BLOCK_TSTP_TOO = 4, /* block fatal signals and SIGTSTP (^Z) */
92 /* We play with signal mask only if this mode is active: */
93 #define interactive (opt_intr == INTR_WHILE_WAIT)
96 * daemonized_tracer supports -D option.
97 * With this option, strace forks twice.
98 * Unlike normal case, with -D *grandparent* process exec's,
99 * becoming a traced process. Child exits (this prevents traced process
100 * from having children it doesn't expect to have), and grandchild
101 * attaches to grandparent similarly to strace -p PID.
102 * This allows for more transparent interaction in cases
103 * when process and its parent are communicating via signals,
104 * wait() etc. Without -D, strace process gets lodged in between,
105 * disrupting parent<->child link.
107 static bool daemonized_tracer;
109 static int post_attach_sigstop = TCB_IGNORE_ONE_SIGSTOP;
110 #define use_seize (post_attach_sigstop == 0)
112 /* Sometimes we want to print only succeeding syscalls. */
113 bool not_failing_only;
115 /* Show path associated with fd arguments */
116 unsigned int show_fd_path;
118 static bool detach_on_execve;
120 static int exit_code;
121 static int strace_child;
122 static int strace_tracer_pid;
124 static const char *username;
125 static uid_t run_uid;
126 static gid_t run_gid;
128 unsigned int max_strlen = DEFAULT_STRLEN;
129 static int acolumn = DEFAULT_ACOLUMN;
130 static char *acolumn_spaces;
132 /* Default output style for xlat entities */
133 enum xlat_style xlat_verbosity = XLAT_STYLE_ABBREV;
135 static const char *outfname;
136 /* If -ff, points to stderr. Else, it's our common output log */
137 static FILE *shared_log;
138 static bool open_append;
140 struct tcb *printing_tcp;
141 static struct tcb *current_tcp;
143 struct tcb_wait_data {
144 enum trace_event te; /**< Event passed to dispatch_event() */
145 int status; /**< status, returned by wait4() */
146 siginfo_t si; /**< siginfo, returned by PTRACE_GETSIGINFO */
149 static struct tcb **tcbtab;
150 static unsigned int nprocs;
151 static size_t tcbtabsize;
153 #ifndef HAVE_PROGRAM_INVOCATION_NAME
154 char *program_invocation_name;
157 unsigned os_release; /* generated from uname()'s u.release */
159 static void detach(struct tcb *tcp);
160 static void cleanup(void);
161 static void interrupt(int sig);
163 #ifdef HAVE_SIG_ATOMIC_T
164 static volatile sig_atomic_t interrupted, restart_failed;
166 static volatile int interrupted, restart_failed;
169 static sigset_t timer_set;
170 static void timer_sighandler(int);
172 #ifndef HAVE_STRERROR
174 #if !HAVE_DECL_SYS_ERRLIST
176 extern char *sys_errlist[];
182 static char buf[sizeof("Unknown error %d") + sizeof(int)*3];
184 if (err_no < 1 || err_no >= sys_nerr) {
185 xsprintf(buf, "Unknown error %d", err_no);
188 return sys_errlist[err_no];
191 #endif /* HAVE_STERRROR */
196 static const char features[] =
197 #ifdef ENABLE_STACKTRACE
198 " stack-trace=" USE_UNWINDER
203 #if SUPPORTED_PERSONALITIES > 1
204 # if defined HAVE_M32_MPERS
209 #endif /* SUPPORTED_PERSONALITIES > 1 */
210 #if SUPPORTED_PERSONALITIES > 2
211 # if defined HAVE_MX32_MPERS
216 #endif /* SUPPORTED_PERSONALITIES > 2 */
219 printf("%s -- version %s\n"
220 "Copyright (c) 1991-%s The strace developers <%s>.\n"
221 "This is free software; see the source for copying conditions. There is NO\n"
222 "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n",
223 PACKAGE_NAME, PACKAGE_VERSION, COPYRIGHT_YEAR, PACKAGE_URL);
224 printf("\nOptional features enabled:%s\n",
225 features[0] ? features : " (none)");
232 usage: strace [-CdffhiqrtttTvVwxxy] [-I n] [-e expr]...\n\
233 [-a column] [-o file] [-s strsize] [-P path]...\n\
234 -p pid... / [-D] [-E var=val]... [-u username] PROG [ARGS]\n\
235 or: strace -c[dfw] [-I n] [-e expr]... [-O overhead] [-S sortby]\n\
236 -p pid... / [-D] [-E var=val]... [-u username] PROG [ARGS]\n\
239 -a column alignment COLUMN for printing syscall results (default %d)\n\
240 -i print instruction pointer at time of syscall\n\
242 #ifdef ENABLE_STACKTRACE
244 -k obtain stack trace between each syscall\n\
248 -o file send trace output to FILE instead of stderr\n\
249 -q suppress messages about attaching, detaching, etc.\n\
250 -r print relative timestamp\n\
251 -s strsize limit length of print strings to STRSIZE chars (default %d)\n\
252 -t print absolute timestamp\n\
253 -tt print absolute timestamp with usecs\n\
254 -T print time spent in each syscall\n\
255 -x print non-ascii strings in hex\n\
256 -xx print all strings in hex\n\
257 -X format set the format for printing of named constants and flags\n\
258 -y print paths associated with file descriptor arguments\n\
259 -yy print protocol specific information associated with socket file descriptors\n\
262 -c count time, calls, and errors for each syscall and report summary\n\
263 -C like -c but also print regular output\n\
264 -O overhead set overhead for tracing syscalls to OVERHEAD usecs\n\
265 -S sortby sort syscall counts by: time, calls, name, nothing (default %s)\n\
266 -w summarise syscall latency (default is system time)\n\
269 -e expr a qualifying expression: option=[!]all or option=[!]val1[,val2]...\n\
270 options: trace, abbrev, verbose, raw, signal, read, write, fault, inject, kvm"
272 -P path trace accesses to path\n\
275 -b execve detach on execve syscall\n\
276 -D run tracer process as a detached grandchild, not as parent\n\
278 -ff follow forks with output into separate files\n\
280 1: no signals are blocked\n\
281 2: fatal signals are blocked while decoding syscall (default)\n\
282 3: fatal signals are always blocked (default if '-o FILE PROG')\n\
283 4: fatal signals and SIGTSTP (^Z) are always blocked\n\
284 (useful to make 'strace -o FILE PROG' not stop on ^Z)\n\
287 -E var remove var from the environment for command\n\
288 -E var=val put var=val in the environment for command\n\
289 -p pid trace process with process id PID, may be repeated\n\
290 -u username run command as username handling setuid and/or setgid\n\
293 -d enable debug output to stderr\n\
294 -v verbose mode: print unabbreviated argv, stat, termios, etc. args\n\
295 -h print help message\n\
298 /* ancient, no one should use it
299 -F -- attempt to follow vforks (deprecated, use -f)\n\
301 /* this is broken, so don't document it
302 -z -- print only succeeding syscalls\n\
304 , DEFAULT_ACOLUMN, DEFAULT_STRLEN, DEFAULT_SORTBY);
308 void ATTRIBUTE_NORETURN
311 if (strace_tracer_pid == getpid()) {
321 error_opt_arg(int opt, const char *arg)
323 error_msg_and_help("invalid -%c argument: '%s'", opt, arg);
326 static const char *ptrace_attach_cmd;
329 ptrace_attach_or_seize(int pid)
333 return ptrace_attach_cmd = "PTRACE_ATTACH",
334 ptrace(PTRACE_ATTACH, pid, 0L, 0L);
335 r = ptrace(PTRACE_SEIZE, pid, 0L, (unsigned long) ptrace_setoptions);
337 return ptrace_attach_cmd = "PTRACE_SEIZE", r;
338 r = ptrace(PTRACE_INTERRUPT, pid, 0L, 0L);
339 return ptrace_attach_cmd = "PTRACE_INTERRUPT", r;
343 * Used when we want to unblock stopped traced process.
344 * Should be only used with PTRACE_CONT, PTRACE_DETACH and PTRACE_SYSCALL.
345 * Returns 0 on success or if error was ESRCH
346 * (presumably process was killed while we talk to it).
347 * Otherwise prints error message and returns -1.
350 ptrace_restart(const unsigned int op, struct tcb *const tcp, unsigned int sig)
356 ptrace(op, tcp->pid, 0L, (unsigned long) sig);
376 * Why curcol != 0? Otherwise sometimes we get this:
378 * 10252 kill(10253, SIGKILL) = 0
379 * <ptrace(SYSCALL,10252):No such process>10253 ...next decode...
381 * 10252 died after we retrieved syscall exit data,
382 * but before we tried to restart it. Log looks ugly.
384 if (current_tcp && current_tcp->curcol != 0) {
385 tprintf(" <ptrace(%s):%s>\n", msg, strerror(err));
391 perror_msg("ptrace(PTRACE_%s,pid:%d,sig:%u)", msg, tcp->pid, sig);
396 set_cloexec_flag(int fd)
400 flags = fcntl(fd, F_GETFD);
402 /* Can happen only if fd is bad.
403 * Should never happen: if it does, we have a bug
404 * in the caller. Therefore we just abort
405 * instead of propagating the error.
407 perror_msg_and_die("fcntl(%d, F_GETFD)", fd);
410 newflags = flags | FD_CLOEXEC;
411 if (flags == newflags)
414 if (fcntl(fd, F_SETFD, newflags)) /* never fails */
415 perror_msg_and_die("fcntl(%d, F_SETFD, %#x)", fd, newflags);
419 * When strace is setuid executable, we have to swap uids
420 * before and after filesystem and process management operations.
425 int euid = geteuid(), uid = getuid();
427 if (euid != uid && setreuid(euid, uid) < 0) {
428 perror_msg_and_die("setreuid");
433 strace_fopen(const char *path)
438 fp = fopen_stream(path, open_append ? "a" : "w");
440 perror_msg_and_die("Can't fopen '%s'", path);
442 set_cloexec_flag(fileno(fp));
446 static int popen_pid;
449 # define _PATH_BSHELL "/bin/sh"
453 * We cannot use standard popen(3) here because we have to distinguish
454 * popen child process from other processes we trace, and standard popen(3)
455 * does not export its child's pid.
458 strace_popen(const char *command)
466 perror_msg_and_die("pipe");
468 set_cloexec_flag(fds[1]); /* never fails */
472 perror_msg_and_die("vfork");
479 perror_msg_and_die("dup2");
482 execl(_PATH_BSHELL, "sh", "-c", command, NULL);
483 perror_msg_and_die("Can't execute '%s'", _PATH_BSHELL);
490 fp = fdopen(fds[1], "w");
492 perror_msg_and_die("fdopen");
497 outf_perror(const struct tcb * const tcp)
499 if (tcp->outf == stderr)
502 /* This is ugly, but we don't store separate file names */
504 perror_msg("%s.%u", outfname, tcp->pid);
506 perror_msg("%s", outfname);
509 ATTRIBUTE_FORMAT((printf, 1, 0))
511 tvprintf(const char *const fmt, va_list args)
514 int n = vfprintf(current_tcp->outf, fmt, args);
516 /* very unlikely due to vfprintf buffering */
517 outf_perror(current_tcp);
519 current_tcp->curcol += n;
524 tprintf(const char *fmt, ...)
532 #ifndef HAVE_FPUTS_UNLOCKED
533 # define fputs_unlocked fputs
537 tprints(const char *str)
540 int n = fputs_unlocked(str, current_tcp->outf);
542 current_tcp->curcol += strlen(str);
545 /* very unlikely due to fputs_unlocked buffering */
546 outf_perror(current_tcp);
551 tprints_comment(const char *const str)
554 tprintf(" /* %s */", str);
558 tprintf_comment(const char *fmt, ...)
572 flush_tcp_output(const struct tcb *const tcp)
574 if (fflush(tcp->outf))
582 current_tcp->curcol = 0;
583 flush_tcp_output(current_tcp);
586 printing_tcp->curcol = 0;
592 set_current_tcp(const struct tcb *tcp)
594 current_tcp = (struct tcb *) tcp;
596 /* Sync current_personality and stuff */
598 set_personality(current_tcp->currpers);
602 printleader(struct tcb *tcp)
604 /* If -ff, "previous tcb we printed" is always the same as current,
605 * because we have per-tcb output files.
611 set_current_tcp(printing_tcp);
612 if (printing_tcp->curcol != 0 && (followfork < 2 || printing_tcp == tcp)) {
614 * case 1: we have a shared log (i.e. not -ff), and last line
615 * wasn't finished (same or different tcb, doesn't matter).
616 * case 2: split log, we are the same tcb, but our last line
617 * didn't finish ("SIGKILL nuked us after syscall entry" etc).
619 tprints(" <unfinished ...>\n");
620 printing_tcp->curcol = 0;
625 set_current_tcp(tcp);
626 current_tcp->curcol = 0;
629 tprintf("%-5d ", tcp->pid);
630 else if (nprocs > 1 && !outfname)
631 tprintf("[pid %5u] ", tcp->pid);
635 clock_gettime(CLOCK_REALTIME, &ts);
638 tprintf("%lld.%06ld ",
639 (long long) ts.tv_sec, (long) ts.tv_nsec / 1000);
641 time_t local = ts.tv_sec;
642 char str[MAX(sizeof("HH:MM:SS"), sizeof(ts.tv_sec) * 3)];
643 struct tm *tm = localtime(&local);
646 strftime(str, sizeof(str), "%T", tm);
648 xsprintf(str, "%lld", (long long) local);
651 str, (long) ts.tv_nsec / 1000);
659 clock_gettime(CLOCK_MONOTONIC, &ts);
661 static struct timespec ots;
666 ts_sub(&dts, &ts, &ots);
669 tprintf("%s%6ld.%06ld%s ",
671 (long) dts.tv_sec, (long) dts.tv_nsec / 1000,
676 print_instruction_pointer(tcp);
682 if (current_tcp->curcol < acolumn)
683 tprints(acolumn_spaces + current_tcp->curcol);
686 /* Should be only called directly *after successful attach* to a tracee.
687 * Otherwise, "strace -oFILE -ff -p<nonexistant_pid>"
688 * may create bogus empty FILE.<nonexistant_pid>, and then die.
691 after_successful_attach(struct tcb *tcp, const unsigned int flags)
693 tcp->flags |= TCB_ATTACHED | TCB_STARTUP | flags;
694 tcp->outf = shared_log; /* if not -ff mode, the same file is for all */
695 if (followfork >= 2) {
697 xsprintf(name, "%s.%u", outfname, tcp->pid);
698 tcp->outf = strace_fopen(name);
701 #ifdef ENABLE_STACKTRACE
702 if (stack_trace_enabled)
703 unwind_tcb_init(tcp);
710 /* Allocate some (more) TCBs (and expand the table).
711 We don't want to relocate the TCBs because our
712 callers have pointers and it would be a pain.
713 So tcbtab is a table of pointers. Since we never
714 free the TCBs, we allocate a single chunk of many. */
715 size_t old_tcbtabsize;
717 struct tcb **tcb_ptr;
719 old_tcbtabsize = tcbtabsize;
721 tcbtab = xgrowarray(tcbtab, &tcbtabsize, sizeof(tcbtab[0]));
722 newtcbs = xcalloc(tcbtabsize - old_tcbtabsize, sizeof(newtcbs[0]));
724 for (tcb_ptr = tcbtab + old_tcbtabsize;
725 tcb_ptr < tcbtab + tcbtabsize; tcb_ptr++, newtcbs++)
735 if (nprocs == tcbtabsize)
738 for (i = 0; i < tcbtabsize; i++) {
741 memset(tcp, 0, sizeof(*tcp));
743 #if SUPPORTED_PERSONALITIES > 1
744 tcp->currpers = current_personality;
747 debug_msg("new tcb for pid %d, active tcbs:%d",
752 error_msg_and_die("bug in alloctcb");
756 get_tcb_priv_data(const struct tcb *tcp)
758 return tcp->_priv_data;
762 set_tcb_priv_data(struct tcb *tcp, void *const priv_data,
763 void (*const free_priv_data)(void *))
768 tcp->_free_priv_data = free_priv_data;
769 tcp->_priv_data = priv_data;
775 free_tcb_priv_data(struct tcb *tcp)
777 if (tcp->_priv_data) {
778 if (tcp->_free_priv_data) {
779 tcp->_free_priv_data(tcp->_priv_data);
780 tcp->_free_priv_data = NULL;
782 tcp->_priv_data = NULL;
787 droptcb(struct tcb *tcp)
793 for (p = 0; p < SUPPORTED_PERSONALITIES; ++p)
794 free(tcp->inject_vec[p]);
796 free_tcb_priv_data(tcp);
798 #ifdef ENABLE_STACKTRACE
799 if (stack_trace_enabled)
803 #ifdef HAVE_LINUX_KVM_H
804 kvm_vcpu_info_free(tcp);
808 tcp->mmap_cache->free_fn(tcp, __func__);
811 debug_msg("dropped tcb for pid %d, %d remain", tcp->pid, nprocs);
814 if (followfork >= 2) {
815 if (tcp->curcol != 0)
816 fprintf(tcp->outf, " <detached ...>\n");
819 if (printing_tcp == tcp && tcp->curcol != 0)
820 fprintf(tcp->outf, " <detached ...>\n");
821 flush_tcp_output(tcp);
825 if (current_tcp == tcp)
826 set_current_tcp(NULL);
827 if (printing_tcp == tcp)
830 memset(tcp, 0, sizeof(*tcp));
833 /* Detach traced process.
834 * Never call DETACH twice on the same process as both unattached and
835 * attached-unstopped processes give the same ESRCH. For unattached process we
836 * would SIGSTOP it and wait for its SIGSTOP notification forever.
839 detach(struct tcb *tcp)
845 * Linux wrongly insists the child be stopped
846 * before detaching. Arghh. We go through hoops
847 * to make a clean break of things.
850 if (!(tcp->flags & TCB_ATTACHED))
853 /* We attached but possibly didn't see the expected SIGSTOP.
854 * We must catch exactly one as otherwise the detached process
855 * would be left stopped (process state T).
857 if (tcp->flags & TCB_IGNORE_ONE_SIGSTOP)
860 error = ptrace(PTRACE_DETACH, tcp->pid, 0, 0);
862 /* On a clear day, you can see forever. */
865 if (errno != ESRCH) {
866 /* Shouldn't happen. */
867 perror_func_msg("ptrace(PTRACE_DETACH,%u)", tcp->pid);
870 /* ESRCH: process is either not stopped or doesn't exist. */
871 if (my_tkill(tcp->pid, 0) < 0) {
873 /* Shouldn't happen. */
874 perror_func_msg("tkill(%u,0)", tcp->pid);
875 /* else: process doesn't exist. */
878 /* Process is not stopped, need to stop it. */
881 * With SEIZE, tracee can be in group-stop already.
882 * In this state sending it another SIGSTOP does nothing.
883 * Need to use INTERRUPT.
884 * Testcase: trying to ^C a "strace -p <stopped_process>".
886 error = ptrace(PTRACE_INTERRUPT, tcp->pid, 0, 0);
890 perror_func_msg("ptrace(PTRACE_INTERRUPT,%u)", tcp->pid);
892 error = my_tkill(tcp->pid, SIGSTOP);
896 perror_func_msg("tkill(%u,SIGSTOP)", tcp->pid);
898 /* Either process doesn't exist, or some weird error. */
902 /* We end up here in three cases:
903 * 1. We sent PTRACE_INTERRUPT (use_seize case)
904 * 2. We sent SIGSTOP (!use_seize)
905 * 3. Attach SIGSTOP was already pending (TCB_IGNORE_ONE_SIGSTOP set)
909 if (waitpid(tcp->pid, &status, __WALL) < 0) {
913 * if (errno == ECHILD) break;
914 * ^^^ WRONG! We expect this PID to exist,
915 * and want to emit a message otherwise:
917 perror_func_msg("waitpid(%u)", tcp->pid);
920 if (!WIFSTOPPED(status)) {
922 * Tracee exited or was killed by signal.
923 * We shouldn't normally reach this place:
924 * we don't want to consume exit status.
925 * Consider "strace -p PID" being ^C-ed:
926 * we want merely to detach from PID.
928 * However, we _can_ end up here if tracee
933 sig = WSTOPSIG(status);
934 debug_msg("detach wait: event:%d sig:%d",
935 (unsigned) status >> 16, sig);
937 unsigned event = (unsigned)status >> 16;
938 if (event == PTRACE_EVENT_STOP /*&& sig == SIGTRAP*/) {
940 * sig == SIGTRAP: PTRACE_INTERRUPT stop.
941 * sig == other: process was already stopped
942 * with this stopping sig (see tests/detach-stopped).
943 * Looks like re-injecting this sig is not necessary
944 * in DETACH for the tracee to remain stopped.
949 * PTRACE_INTERRUPT is not guaranteed to produce
950 * the above event if other ptrace-stop is pending.
951 * See tests/detach-sleeping testcase:
952 * strace got SIGINT while tracee is sleeping.
953 * We sent PTRACE_INTERRUPT.
954 * We see syscall exit, not PTRACE_INTERRUPT stop.
955 * We won't get PTRACE_INTERRUPT stop
956 * if we would CONT now. Need to DETACH.
958 if (sig == syscall_trap_sig)
960 /* else: not sure in which case we can be here.
961 * Signal stop? Inject it while detaching.
963 ptrace_restart(PTRACE_DETACH, tcp, sig);
966 /* Note: this check has to be after use_seize check */
967 /* (else, in use_seize case SIGSTOP will be mistreated) */
968 if (sig == SIGSTOP) {
969 /* Detach, suppressing SIGSTOP */
970 ptrace_restart(PTRACE_DETACH, tcp, 0);
973 if (sig == syscall_trap_sig)
975 /* Can't detach just yet, may need to wait for SIGSTOP */
976 error = ptrace_restart(PTRACE_CONT, tcp, sig);
978 /* Should not happen.
979 * Note: ptrace_restart returns 0 on ESRCH, so it's not it.
980 * ptrace_restart already emitted error message.
987 if (!qflag && (tcp->flags & TCB_ATTACHED))
988 error_msg("Process %u detached", tcp->pid);
994 process_opt_p_list(char *opt)
998 * We accept -p PID,PID; -p "`pidof PROG`"; -p "`pgrep PROG`".
999 * pidof uses space as delim, pgrep uses newline. :(
1002 char *delim = opt + strcspn(opt, "\n\t ,");
1006 pid = string_to_uint(opt);
1008 error_msg_and_die("Invalid process id: '%s'", opt);
1010 if (pid == strace_tracer_pid) {
1011 error_msg_and_die("I'm sorry, I can't let you do that, Dave.");
1022 attach_tcb(struct tcb *const tcp)
1024 if (ptrace_attach_or_seize(tcp->pid) < 0) {
1025 perror_msg("attach: ptrace(%s, %d)",
1026 ptrace_attach_cmd, tcp->pid);
1031 after_successful_attach(tcp, TCB_GRABBED | post_attach_sigstop);
1032 debug_msg("attach to pid %d (main) succeeded", tcp->pid);
1034 static const char task_path[] = "/proc/%d/task";
1035 char procdir[sizeof(task_path) + sizeof(int) * 3];
1037 unsigned int ntid = 0, nerr = 0;
1039 if (followfork && tcp->pid != strace_child &&
1040 xsprintf(procdir, task_path, tcp->pid) > 0 &&
1041 (dir = opendir(procdir)) != NULL) {
1044 while ((de = read_dir(dir)) != NULL) {
1045 if (de->d_fileno == 0)
1048 int tid = string_to_uint(de->d_name);
1049 if (tid <= 0 || tid == tcp->pid)
1053 if (ptrace_attach_or_seize(tid) < 0) {
1055 debug_perror_msg("attach: ptrace(%s, %d)",
1056 ptrace_attach_cmd, tid);
1060 after_successful_attach(alloctcb(tid),
1061 TCB_GRABBED | post_attach_sigstop);
1062 debug_msg("attach to pid %d succeeded", tid);
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;
1086 if (daemonized_tracer) {
1089 perror_func_msg_and_die("fork");
1091 if (pid) { /* parent */
1093 * Wait for grandchild to attach to straced process
1094 * (grandparent). Grandchild SIGKILLs us after it attached.
1095 * Grandparent's wait() is unblocked by our death,
1096 * it proceeds to exec the straced program.
1099 _exit(0); /* paranoia */
1102 /* We will be the tracer process. Remember our new pid: */
1103 strace_tracer_pid = getpid();
1106 for (tcbi = 0; tcbi < tcbtabsize; tcbi++) {
1112 /* Is this a process we should attach to, but not yet attached? */
1113 if (tcp->flags & TCB_ATTACHED)
1114 continue; /* no, we already attached it */
1116 if (tcp->pid == parent_pid || tcp->pid == strace_tracer_pid) {
1118 perror_msg("attach: pid %d", tcp->pid);
1127 } /* for each tcbtab[] */
1129 if (daemonized_tracer) {
1131 * Make parent go away.
1132 * Also makes grandparent's wait() unblock.
1134 kill(parent_pid, SIGKILL);
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 after_successful_attach(tcp, TCB_SKIP_DETACH_ON_FIRST_EXEC
1410 | 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;
1418 * Attaching will be done later, by startup_attach.
1419 * Note: we don't do after_successful_attach() here either!
1422 /* NOMMU BUG! -D mode is active, we (child) return,
1423 * and we will scribble over parent's stack!
1424 * When parent later unpauses, it segfaults.
1427 * (1) by declaring exec_or_die() NORETURN,
1428 * hopefully compiler will just jump to it
1429 * instead of call (won't push anything to stack),
1430 * (2) by trying very hard in exec_or_die()
1431 * to not use any stack,
1432 * (3) having a really big (PATH_MAX) stack object
1433 * in this function, which creates a "buffer" between
1434 * child's and parent's stack pointers.
1435 * This may save us if (1) and (2) failed
1436 * and compiler decided to use stack in exec_or_die() anyway
1437 * (happens on i386 because of stack parameter passing).
1439 * A cleaner solution is to use makecontext + setcontext
1440 * to create a genuine separate stack and execute on it.
1444 * A case where straced process is part of a pipe:
1445 * { sleep 1; yes | head -n99999; } | strace -o/dev/null sh -c 'exec <&-; sleep 9'
1446 * If strace won't close its fd#0, closing it in tracee is not enough:
1447 * the pipe is still open, it has a reader. Thus, "head" will not get its
1448 * SIGPIPE at once, on the first write.
1450 * Preventing it by redirecting strace's stdin/out.
1451 * (Don't leave fds 0 and 1 closed, this is bad practice: future opens
1452 * will reuse them, unexpectedly making a newly opened object "stdin").
1454 redirect_standard_fds();
1458 test_ptrace_seize(void)
1462 /* Need fork for test. NOMMU has no forks */
1464 post_attach_sigstop = 0; /* this sets use_seize to 1 */
1470 perror_func_msg_and_die("fork");
1477 /* PTRACE_SEIZE, unlike ATTACH, doesn't force tracee to trap. After
1478 * attaching tracee continues to run unless a trap condition occurs.
1479 * PTRACE_SEIZE doesn't affect signal or group stop state.
1481 if (ptrace(PTRACE_SEIZE, pid, 0, 0) == 0) {
1482 post_attach_sigstop = 0; /* this sets use_seize to 1 */
1484 debug_msg("PTRACE_SEIZE doesn't work");
1490 int status, tracee_pid;
1493 tracee_pid = waitpid(pid, &status, 0);
1494 if (tracee_pid <= 0) {
1497 perror_func_msg_and_die("unexpected wait result %d",
1500 if (WIFSIGNALED(status))
1503 error_func_msg_and_die("unexpected wait status %#x", status);
1508 get_os_release(void)
1514 perror_msg_and_die("uname");
1515 /* u.release has this form: "3.2.9[-some-garbage]" */
1519 if (!(*p >= '0' && *p <= '9'))
1520 error_msg_and_die("Bad OS release string: '%s'", u.release);
1521 /* Note: this open-codes KERNEL_VERSION(): */
1522 rel = (rel << 8) | atoi(p);
1523 if (rel >= KERNEL_VERSION(1, 0, 0))
1525 while (*p >= '0' && *p <= '9')
1528 if (rel >= KERNEL_VERSION(0, 1, 0)) {
1529 /* "X.Y-something" means "X.Y.0" */
1533 error_msg_and_die("Bad OS release string: '%s'", u.release);
1541 set_sighandler(int signo, void (*sighandler)(int), struct sigaction *oldact)
1543 const struct sigaction sa = { .sa_handler = sighandler };
1544 sigaction(signo, &sa, oldact);
1548 * Initialization part of main() was eating much stack (~0.5k),
1549 * which was unused after init.
1550 * We can reuse it if we move init code into a separate function.
1552 * Don't want main() to inline us and defeat the reason
1553 * we have a separate function.
1555 static void ATTRIBUTE_NOINLINE
1556 init(int argc, char *argv[])
1561 if (!program_invocation_name || !*program_invocation_name) {
1562 static char name[] = "strace";
1563 program_invocation_name =
1564 (argc > 0 && argv[0] && *argv[0]) ? argv[0] : name;
1567 strace_tracer_pid = getpid();
1569 os_release = get_os_release();
1571 shared_log = stderr;
1572 set_sortby(DEFAULT_SORTBY);
1573 set_personality(DEFAULT_PERSONALITY);
1574 qualify("trace=all");
1575 qualify("abbrev=all");
1576 qualify("verbose=all");
1577 #if DEFAULT_QUAL_FLAGS != (QUAL_TRACE | QUAL_ABBREV | QUAL_VERBOSE)
1578 # error Bug in DEFAULT_QUAL_FLAGS
1580 qualify("signal=all");
1581 while ((c = getopt(argc, argv, "+"
1582 #ifdef ENABLE_STACKTRACE
1585 "a:Ab:cCdDe:E:fFhiI:o:O:p:P:qrs:S:tTu:vVwxX:yz")) != EOF) {
1588 acolumn = string_to_uint(optarg);
1590 error_opt_arg(c, optarg);
1596 if (strcmp(optarg, "execve") != 0)
1597 error_msg_and_die("Syscall '%s' for -b isn't supported",
1599 detach_on_execve = 1;
1602 if (cflag == CFLAG_BOTH) {
1603 error_msg_and_help("-c and -C are mutually exclusive");
1605 cflag = CFLAG_ONLY_STATS;
1608 if (cflag == CFLAG_ONLY_STATS) {
1609 error_msg_and_help("-c and -C are mutually exclusive");
1617 daemonized_tracer = 1;
1623 if (putenv(optarg) < 0)
1624 perror_msg_and_die("putenv");
1639 opt_intr = string_to_uint_upto(optarg, NUM_INTR_OPTS - 1);
1641 error_opt_arg(c, optarg);
1643 #ifdef ENABLE_STACKTRACE
1645 stack_trace_enabled = true;
1652 i = string_to_uint(optarg);
1654 error_opt_arg(c, optarg);
1658 process_opt_p_list(optarg);
1661 pathtrace_select(optarg);
1670 i = string_to_uint(optarg);
1671 if (i < 0 || (unsigned int) i > -1U / 4)
1672 error_opt_arg(c, optarg);
1688 qualify("abbrev=none");
1695 count_wallclock = 1;
1701 if (!strcmp(optarg, "raw"))
1702 xlat_verbosity = XLAT_STYLE_RAW;
1703 else if (!strcmp(optarg, "abbrev"))
1704 xlat_verbosity = XLAT_STYLE_ABBREV;
1705 else if (!strcmp(optarg, "verbose"))
1706 xlat_verbosity = XLAT_STYLE_VERBOSE;
1708 error_opt_arg(c, optarg);
1714 not_failing_only = 1;
1717 error_msg_and_help(NULL);
1725 if (argc < 0 || (!nprocs && !argc)) {
1726 error_msg_and_help("must have PROG [ARGS] or -p PID");
1729 if (!argc && daemonized_tracer) {
1730 error_msg_and_help("PROG [ARGS] must be specified with -D");
1735 error_msg("deprecated option -F ignored");
1737 error_msg("option -F is deprecated, "
1738 "please use -f instead");
1743 if (followfork >= 2 && cflag) {
1744 error_msg_and_help("(-c or -C) and -ff are mutually exclusive");
1747 if (count_wallclock && !cflag) {
1748 error_msg_and_help("-w must be given with (-c or -C)");
1751 if (cflag == CFLAG_ONLY_STATS) {
1753 error_msg("-%c has no effect with -c", 'i');
1754 #ifdef ENABLE_STACKTRACE
1755 if (stack_trace_enabled)
1756 error_msg("-%c has no effect with -c", 'k');
1759 error_msg("-%c has no effect with -c", 'r');
1761 error_msg("-%c has no effect with -c", 't');
1763 error_msg("-%c has no effect with -c", 'T');
1765 error_msg("-%c has no effect with -c", 'y');
1768 acolumn_spaces = xmalloc(acolumn + 1);
1769 memset(acolumn_spaces, ' ', acolumn);
1770 acolumn_spaces[acolumn] = '\0';
1772 set_sighandler(SIGCHLD, SIG_DFL, ¶ms_for_tracee.child_sa);
1774 #ifdef ENABLE_STACKTRACE
1775 if (stack_trace_enabled)
1779 /* See if they want to run as another user. */
1780 if (username != NULL) {
1781 struct passwd *pent;
1783 if (getuid() != 0 || geteuid() != 0) {
1784 error_msg_and_die("You must be root to use the -u option");
1786 pent = getpwnam(username);
1788 error_msg_and_die("Cannot find user '%s'", username);
1790 run_uid = pent->pw_uid;
1791 run_gid = pent->pw_gid;
1798 ptrace_setoptions |= PTRACE_O_TRACECLONE |
1799 PTRACE_O_TRACEFORK |
1800 PTRACE_O_TRACEVFORK;
1801 debug_msg("ptrace_setoptions = %#x", ptrace_setoptions);
1802 test_ptrace_seize();
1805 * NOMMU provides no forks necessary for PTRACE_GET_SYSCALL_INFO test,
1806 * leave the default unchanged.
1809 test_ptrace_get_syscall_info();
1812 * Is something weird with our stdin and/or stdout -
1813 * for example, may they be not open? In this case,
1814 * ensure that none of the future opens uses them.
1816 * This was seen in the wild when /proc/sys/kernel/core_pattern
1817 * was set to "|/bin/strace -o/tmp/LOG PROG":
1818 * kernel runs coredump helper with fd#0 open but fd#1 closed (!),
1819 * therefore LOG gets opened to fd#1, and fd#1 is closed by
1820 * "don't hold up stdin/out open" code soon after.
1822 ensure_standard_fds_opened();
1824 /* Check if they want to redirect the output. */
1826 /* See if they want to pipe the output. */
1827 if (outfname[0] == '|' || outfname[0] == '!') {
1829 * We can't do the <outfname>.PID funny business
1830 * when using popen, so prohibit it.
1832 if (followfork >= 2)
1833 error_msg_and_help("piping the output and -ff "
1834 "are mutually exclusive");
1835 shared_log = strace_popen(outfname + 1);
1836 } else if (followfork < 2) {
1837 shared_log = strace_fopen(outfname);
1838 } else if (strlen(outfname) >= PATH_MAX - sizeof(int) * 3) {
1839 errno = ENAMETOOLONG;
1840 perror_msg_and_die("%s", outfname);
1843 /* -ff without -o FILE is the same as single -f */
1844 if (followfork >= 2)
1848 if (!outfname || outfname[0] == '|' || outfname[0] == '!') {
1849 setvbuf(shared_log, NULL, _IOLBF, 0);
1853 * argv[0] -pPID -oFILE Default interactive setting
1854 * yes * 0 INTR_WHILE_WAIT
1855 * no 1 0 INTR_WHILE_WAIT
1856 * yes * 1 INTR_NEVER
1857 * no 1 1 INTR_WHILE_WAIT
1860 if (outfname && argc) {
1862 opt_intr = INTR_NEVER;
1867 opt_intr = INTR_WHILE_WAIT;
1870 * startup_child() must be called before the signal handlers get
1871 * installed below as they are inherited into the spawned process.
1872 * Also we do not need to be protected by them as during interruption
1873 * in the startup_child() mode we kill the spawned process anyway.
1876 startup_child(argv);
1879 set_sighandler(SIGTTOU, SIG_IGN, NULL);
1880 set_sighandler(SIGTTIN, SIG_IGN, NULL);
1881 if (opt_intr != INTR_ANYWHERE) {
1882 if (opt_intr == INTR_BLOCK_TSTP_TOO)
1883 set_sighandler(SIGTSTP, SIG_IGN, NULL);
1885 * In interactive mode (if no -o OUTFILE, or -p PID is used),
1886 * fatal signals are handled asynchronously and acted
1887 * when waiting for process state changes.
1888 * In non-interactive mode these signals are ignored.
1890 set_sighandler(SIGHUP, interactive ? interrupt : SIG_IGN, NULL);
1891 set_sighandler(SIGINT, interactive ? interrupt : SIG_IGN, NULL);
1892 set_sighandler(SIGQUIT, interactive ? interrupt : SIG_IGN, NULL);
1893 set_sighandler(SIGPIPE, interactive ? interrupt : SIG_IGN, NULL);
1894 set_sighandler(SIGTERM, interactive ? interrupt : SIG_IGN, NULL);
1897 sigemptyset(&timer_set);
1898 sigaddset(&timer_set, SIGALRM);
1899 sigprocmask(SIG_BLOCK, &timer_set, NULL);
1900 set_sighandler(SIGALRM, timer_sighandler, NULL);
1902 if (nprocs != 0 || daemonized_tracer)
1905 /* Do we want pids printed in our -o OUTFILE?
1906 * -ff: no (every pid has its own file); or
1907 * -f: yes (there can be more pids in the future); or
1908 * -p PID1,PID2: yes (there are already more than one pid)
1910 print_pid_pfx = (outfname && followfork < 2 && (followfork == 1 || nprocs > 1));
1914 pid2tcb(const int pid)
1919 #define PID2TCB_CACHE_SIZE 1024U
1920 #define PID2TCB_CACHE_MASK (PID2TCB_CACHE_SIZE - 1)
1922 static struct tcb *pid2tcb_cache[PID2TCB_CACHE_SIZE];
1923 struct tcb **const ptcp = &pid2tcb_cache[pid & PID2TCB_CACHE_MASK];
1924 struct tcb *tcp = *ptcp;
1926 if (tcp && tcp->pid == pid)
1929 for (unsigned int i = 0; i < tcbtabsize; ++i) {
1931 if (tcp->pid == pid)
1945 /* 'interrupted' is a volatile object, fetch it only once */
1946 fatal_sig = interrupted;
1948 fatal_sig = SIGTERM;
1950 for (i = 0; i < tcbtabsize; i++) {
1954 debug_func_msg("looking at pid %u", tcp->pid);
1955 if (tcp->pid == strace_child) {
1956 kill(tcp->pid, SIGCONT);
1957 kill(tcp->pid, fatal_sig);
1962 call_summary(shared_log);
1972 print_debug_info(const int pid, int status)
1974 const unsigned int event = (unsigned int) status >> 16;
1975 char buf[sizeof("WIFEXITED,exitcode=%u") + sizeof(int)*3 /*paranoia:*/ + 16];
1976 char evbuf[sizeof(",EVENT_VFORK_DONE (%u)") + sizeof(int)*3 /*paranoia:*/ + 16];
1979 if (WIFSIGNALED(status))
1980 xsprintf(buf, "WIFSIGNALED,%ssig=%s",
1981 WCOREDUMP(status) ? "core," : "",
1982 sprintsigname(WTERMSIG(status)));
1983 if (WIFEXITED(status))
1984 xsprintf(buf, "WIFEXITED,exitcode=%u", WEXITSTATUS(status));
1985 if (WIFSTOPPED(status))
1986 xsprintf(buf, "WIFSTOPPED,sig=%s",
1987 sprintsigname(WSTOPSIG(status)));
1990 static const char *const event_names[] = {
1991 [PTRACE_EVENT_CLONE] = "CLONE",
1992 [PTRACE_EVENT_FORK] = "FORK",
1993 [PTRACE_EVENT_VFORK] = "VFORK",
1994 [PTRACE_EVENT_VFORK_DONE] = "VFORK_DONE",
1995 [PTRACE_EVENT_EXEC] = "EXEC",
1996 [PTRACE_EVENT_EXIT] = "EXIT",
1997 /* [PTRACE_EVENT_STOP (=128)] would make biggish array */
1999 const char *e = "??";
2000 if (event < ARRAY_SIZE(event_names))
2001 e = event_names[event];
2002 else if (event == PTRACE_EVENT_STOP)
2004 xsprintf(evbuf, ",EVENT_%s (%u)", e, event);
2006 error_msg("[wait(0x%06x) = %u] %s%s", status, pid, buf, evbuf);
2010 maybe_allocate_tcb(const int pid, int status)
2012 if (!WIFSTOPPED(status)) {
2013 if (detach_on_execve && pid == strace_child) {
2014 /* example: strace -bexecve sh -c 'exec true' */
2019 * This can happen if we inherited an unknown child.
2020 * Example: (sleep 1 & exec strace true)
2022 error_msg("Exit of unknown pid %u ignored", pid);
2026 /* We assume it's a fork/vfork/clone child */
2027 struct tcb *tcp = alloctcb(pid);
2028 after_successful_attach(tcp, post_attach_sigstop);
2030 error_msg("Process %d attached", pid);
2034 * This can happen if a clone call misused CLONE_PTRACE itself.
2036 * There used to be a dance around possible re-injection of
2037 * WSTOPSIG(status), but it was later removed as the only
2038 * observable stop here is the initial ptrace-stop.
2040 ptrace(PTRACE_DETACH, pid, NULL, 0L);
2041 error_msg("Detached unknown pid %d", pid);
2047 maybe_switch_tcbs(struct tcb *tcp, const int pid)
2050 struct tcb *execve_thread;
2053 if (ptrace(PTRACE_GETEVENTMSG, pid, NULL, &old_pid) < 0)
2055 /* Avoid truncation in pid2tcb() param passing */
2056 if (old_pid <= 0 || old_pid == pid)
2058 if ((unsigned long) old_pid > UINT_MAX)
2060 execve_thread = pid2tcb(old_pid);
2061 /* It should be !NULL, but I feel paranoid */
2065 if (execve_thread->curcol != 0) {
2067 * One case we are here is -ff:
2068 * try "strace -oLOG -ff test/threaded_execve"
2070 fprintf(execve_thread->outf, " <pid changed to %d ...>\n", pid);
2071 /*execve_thread->curcol = 0; - no need, see code below */
2073 /* Swap output FILEs (needed for -ff) */
2074 fp = execve_thread->outf;
2075 execve_thread->outf = tcp->outf;
2077 /* And their column positions */
2078 execve_thread->curcol = tcp->curcol;
2080 /* Drop leader, but close execve'd thread outfile (if -ff) */
2082 /* Switch to the thread, reusing leader's outfile and pid */
2083 tcp = execve_thread;
2085 if (cflag != CFLAG_ONLY_STATS) {
2087 tprintf("+++ superseded by execve in pid %lu +++\n", old_pid);
2089 tcp->flags |= TCB_REPRINT;
2096 print_signalled(struct tcb *tcp, const int pid, int status)
2098 if (pid == strace_child) {
2099 exit_code = 0x100 | WTERMSIG(status);
2103 if (cflag != CFLAG_ONLY_STATS
2104 && is_number_in_set(WTERMSIG(status), signal_set)) {
2106 tprintf("+++ killed by %s %s+++\n",
2107 sprintsigname(WTERMSIG(status)),
2108 WCOREDUMP(status) ? "(core dumped) " : "");
2114 print_exited(struct tcb *tcp, const int pid, int status)
2116 if (pid == strace_child) {
2117 exit_code = WEXITSTATUS(status);
2121 if (cflag != CFLAG_ONLY_STATS &&
2124 tprintf("+++ exited with %d +++\n", WEXITSTATUS(status));
2130 print_stopped(struct tcb *tcp, const siginfo_t *si, const unsigned int sig)
2132 if (cflag != CFLAG_ONLY_STATS
2134 && is_number_in_set(sig, signal_set)) {
2137 tprintf("--- %s ", sprintsigname(sig));
2141 tprintf("--- stopped by %s ---\n", sprintsigname(sig));
2144 #ifdef ENABLE_STACKTRACE
2145 if (stack_trace_enabled)
2146 unwind_tcb_print(tcp);
2152 startup_tcb(struct tcb *tcp)
2154 debug_msg("pid %d has TCB_STARTUP, initializing it", tcp->pid);
2156 tcp->flags &= ~TCB_STARTUP;
2159 debug_msg("setting opts 0x%x on pid %d",
2160 ptrace_setoptions, tcp->pid);
2161 if (ptrace(PTRACE_SETOPTIONS, tcp->pid, NULL, ptrace_setoptions) < 0) {
2162 if (errno != ESRCH) {
2163 /* Should never happen, really */
2164 perror_msg_and_die("PTRACE_SETOPTIONS");
2169 if ((tcp->flags & TCB_GRABBED) && (get_scno(tcp) == 1))
2170 tcp->s_prev_ent = tcp->s_ent;
2174 print_event_exit(struct tcb *tcp)
2176 if (entering(tcp) || filtered(tcp) || hide_log(tcp)
2177 || cflag == CFLAG_ONLY_STATS) {
2181 if (followfork < 2 && printing_tcp && printing_tcp != tcp
2182 && printing_tcp->curcol != 0) {
2183 set_current_tcp(printing_tcp);
2184 tprints(" <unfinished ...>\n");
2185 flush_tcp_output(printing_tcp);
2186 printing_tcp->curcol = 0;
2187 set_current_tcp(tcp);
2190 if ((followfork < 2 && printing_tcp != tcp)
2191 || (tcp->flags & TCB_REPRINT)) {
2192 tcp->flags &= ~TCB_REPRINT;
2194 tprintf("<... %s resumed>", tcp->s_ent->sys_name);
2197 if (!(tcp->sys_func_rval & RVAL_DECODED)) {
2199 * The decoder has probably decided to print something
2200 * on exiting syscall which is not going to happen.
2202 tprints(" <unfinished ...>");
2212 static const struct tcb_wait_data *
2215 static struct tcb_wait_data wait_data;
2220 struct tcb_wait_data *wd = &wait_data;
2227 * Used to exit simply when nprocs hits zero, but in this testcase:
2228 * int main(void) { _exit(!!fork()); }
2229 * under strace -f, parent sometimes (rarely) manages
2230 * to exit before we see the first stop of the child,
2231 * and we are losing track of it:
2232 * 19923 clone(...) = 19924
2233 * 19923 exit_group(1) = ?
2234 * 19923 +++ exited with 1 +++
2235 * Exiting only when wait() returns ECHILD works better.
2237 if (popen_pid != 0) {
2238 /* However, if -o|logger is in use, we can't do that.
2239 * Can work around that by double-forking the logger,
2240 * but that loses the ability to wait for its completion
2241 * on exit. Oh well...
2247 const bool unblock_delay_timer = is_delay_timer_armed();
2250 * The window of opportunity to handle expirations
2251 * of the delay timer opens here.
2253 * Unblock the signal handler for the delay timer
2254 * iff the delay timer is already created.
2256 if (unblock_delay_timer)
2257 sigprocmask(SIG_UNBLOCK, &timer_set, NULL);
2260 * If the delay timer has expired, then its expiration
2261 * has been handled already by the signal handler.
2263 * If the delay timer expires during wait4(),
2264 * then the system call will be interrupted and
2265 * the expiration will be handled by the signal handler.
2267 pid = wait4(-1, &status, __WALL, (cflag ? &ru : NULL));
2268 const int wait_errno = errno;
2271 * The window of opportunity to handle expirations
2272 * of the delay timer closes here.
2274 * Block the signal handler for the delay timer
2275 * iff it was unblocked earlier.
2277 if (unblock_delay_timer) {
2278 sigprocmask(SIG_BLOCK, &timer_set, NULL);
2285 if (wait_errno == EINTR) {
2289 if (nprocs == 0 && wait_errno == ECHILD)
2292 * If nprocs > 0, ECHILD is not expected,
2293 * treat it as any other error here:
2296 perror_msg_and_die("wait4(__WALL)");
2299 wd->status = status;
2301 if (pid == popen_pid) {
2302 if (!WIFSTOPPED(status))
2309 print_debug_info(pid, status);
2311 /* Look up 'pid' in our table. */
2315 tcp = maybe_allocate_tcb(pid, status);
2324 /* Set current output file */
2325 set_current_tcp(tcp);
2328 struct timespec stime = {
2329 .tv_sec = ru.ru_stime.tv_sec,
2330 .tv_nsec = ru.ru_stime.tv_usec * 1000
2332 ts_sub(&tcp->dtime, &stime, &tcp->stime);
2336 if (WIFSIGNALED(status)) {
2337 wd->te = TE_SIGNALLED;
2341 if (WIFEXITED(status)) {
2347 * As WCONTINUED flag has not been specified to wait4,
2348 * it cannot be WIFCONTINUED(status), so the only case
2349 * that remains is WIFSTOPPED(status).
2352 /* Is this the very first time we see this tracee stopped? */
2353 if (tcp->flags & TCB_STARTUP)
2356 const unsigned int sig = WSTOPSIG(status);
2357 const unsigned int event = (unsigned int) status >> 16;
2362 * Is this post-attach SIGSTOP?
2363 * Interestingly, the process may stop
2364 * with STOPSIG equal to some other signal
2365 * than SIGSTOP if we happened to attach
2366 * just before the process takes a signal.
2368 if (sig == SIGSTOP && (tcp->flags & TCB_IGNORE_ONE_SIGSTOP)) {
2369 debug_func_msg("ignored SIGSTOP on pid %d", tcp->pid);
2370 tcp->flags &= ~TCB_IGNORE_ONE_SIGSTOP;
2371 wd->te = TE_RESTART;
2372 } else if (sig == syscall_trap_sig) {
2373 wd->te = TE_SYSCALL_STOP;
2375 memset(&wd->si, 0, sizeof(wd->si));
2377 * True if tracee is stopped by signal
2378 * (as opposed to "tracee received signal").
2379 * TODO: shouldn't we check for errno == EINVAL too?
2380 * We can get ESRCH instead, you know...
2382 bool stopped = ptrace(PTRACE_GETSIGINFO, pid, 0, &wd->si) < 0;
2383 wd->te = stopped ? TE_GROUP_STOP : TE_SIGNAL_DELIVERY_STOP;
2386 case PTRACE_EVENT_STOP:
2388 * PTRACE_INTERRUPT-stop or group-stop.
2389 * PTRACE_INTERRUPT-stop has sig == SIGTRAP here.
2396 wd->te = TE_GROUP_STOP;
2399 wd->te = TE_RESTART;
2402 case PTRACE_EVENT_EXEC:
2403 wd->te = TE_STOP_BEFORE_EXECVE;
2405 case PTRACE_EVENT_EXIT:
2406 wd->te = TE_STOP_BEFORE_EXIT;
2409 wd->te = TE_RESTART;
2416 trace_syscall(struct tcb *tcp, unsigned int *sig)
2418 if (entering(tcp)) {
2419 int res = syscall_entering_decode(tcp);
2424 res = syscall_entering_trace(tcp, sig);
2426 syscall_entering_finish(tcp, res);
2429 struct timespec ts = {};
2430 int res = syscall_exiting_decode(tcp, &ts);
2432 res = syscall_exiting_trace(tcp, &ts, res);
2434 syscall_exiting_finish(tcp);
2439 /* Returns true iff the main trace loop has to continue. */
2441 dispatch_event(const struct tcb_wait_data *wd)
2443 unsigned int restart_op = PTRACE_SYSCALL;
2444 unsigned int restart_sig = 0;
2445 enum trace_event te = wd ? wd->te : TE_BREAK;
2447 * Copy wd->status to a non-const variable to workaround glibc bugs
2448 * around union wait fixed by glibc commit glibc-2.24~391
2450 int status = wd ? wd->status : 0;
2462 case TE_SYSCALL_STOP:
2463 if (trace_syscall(current_tcp, &restart_sig) < 0) {
2465 * ptrace() failed in trace_syscall().
2466 * Likely a result of process disappearing mid-flight.
2467 * Observed case: exit_group() or SIGKILL terminating
2468 * all processes in thread group.
2469 * We assume that ptrace error was caused by process death.
2470 * We used to detach(current_tcp) here, but since we no
2471 * longer implement "detach before death" policy/hack,
2472 * we can let this process to report its death to us
2473 * normally, via WIFEXITED or WIFSIGNALED wait status.
2479 case TE_SIGNAL_DELIVERY_STOP:
2480 restart_sig = WSTOPSIG(status);
2481 print_stopped(current_tcp, &wd->si, restart_sig);
2485 print_signalled(current_tcp, current_tcp->pid, status);
2486 droptcb(current_tcp);
2490 restart_sig = WSTOPSIG(status);
2491 print_stopped(current_tcp, NULL, restart_sig);
2494 * This ends ptrace-stop, but does *not* end group-stop.
2495 * This makes stopping signals work properly on straced
2496 * process (that is, process really stops. It used to
2499 restart_op = PTRACE_LISTEN;
2505 print_exited(current_tcp, current_tcp->pid, status);
2506 droptcb(current_tcp);
2509 case TE_STOP_BEFORE_EXECVE:
2510 /* The syscall succeeded, clear the flag. */
2511 current_tcp->flags &= ~TCB_CHECK_EXEC_SYSCALL;
2513 * Check that we are inside syscall now (next event after
2514 * PTRACE_EVENT_EXEC should be for syscall exiting). If it is
2515 * not the case, we might have a situation when we attach to a
2516 * process and the first thing we see is a PTRACE_EVENT_EXEC
2517 * and all the following syscall state tracking is screwed up
2520 if (entering(current_tcp)) {
2523 error_msg("Stray PTRACE_EVENT_EXEC from pid %d"
2524 ", trying to recover...",
2527 current_tcp->flags |= TCB_RECOVERING;
2528 ret = trace_syscall(current_tcp, &restart_sig);
2529 current_tcp->flags &= ~TCB_RECOVERING;
2532 /* The reason is described in TE_SYSCALL_STOP */
2538 * Under Linux, execve changes pid to thread leader's pid,
2539 * and we see this changed pid on EVENT_EXEC and later,
2540 * execve sysexit. Leader "disappears" without exit
2541 * notification. Let user know that, drop leader's tcb,
2542 * and fix up pid in execve thread's tcb.
2543 * Effectively, execve thread's tcb replaces leader's tcb.
2545 * BTW, leader is 'stuck undead' (doesn't report WIFEXITED
2546 * on exit syscall) in multithreaded programs exactly
2547 * in order to handle this case.
2549 * PTRACE_GETEVENTMSG returns old pid starting from Linux 3.0.
2550 * On 2.6 and earlier, it can return garbage.
2552 if (os_release >= KERNEL_VERSION(3, 0, 0))
2553 set_current_tcp(maybe_switch_tcbs(current_tcp,
2556 if (detach_on_execve) {
2557 if (current_tcp->flags & TCB_SKIP_DETACH_ON_FIRST_EXEC) {
2558 current_tcp->flags &= ~TCB_SKIP_DETACH_ON_FIRST_EXEC;
2560 detach(current_tcp); /* do "-b execve" thingy */
2566 case TE_STOP_BEFORE_EXIT:
2567 print_event_exit(current_tcp);
2571 /* We handled quick cases, we are permitted to interrupt now. */
2575 /* If the process is being delayed, do not ptrace_restart just yet */
2576 if (syscall_delayed(current_tcp))
2579 if (ptrace_restart(restart_op, current_tcp, restart_sig) < 0) {
2580 /* Note: ptrace_restart emitted error message */
2588 restart_delayed_tcb(struct tcb *const tcp)
2590 const struct tcb_wait_data wd = { .te = TE_RESTART };
2592 debug_func_msg("pid %d", tcp->pid);
2594 tcp->flags &= ~TCB_DELAYED;
2596 struct tcb *const prev_tcp = current_tcp;
2598 bool ret = dispatch_event(&wd);
2599 current_tcp = prev_tcp;
2605 restart_delayed_tcbs(void)
2607 struct tcb *tcp_next = NULL;
2608 struct timespec ts_now;
2610 clock_gettime(CLOCK_MONOTONIC, &ts_now);
2612 for (size_t i = 0; i < tcbtabsize; i++) {
2613 struct tcb *tcp = tcbtab[i];
2615 if (tcp->pid && syscall_delayed(tcp)) {
2616 if (ts_cmp(&ts_now, &tcp->delay_expiration_time) > 0) {
2617 if (!restart_delayed_tcb(tcp))
2620 /* Check whether this tcb is the next. */
2622 ts_cmp(&tcp_next->delay_expiration_time,
2623 &tcp->delay_expiration_time) > 0) {
2631 arm_delay_timer(tcp_next);
2637 * As this signal handler does a lot of work that is not suitable
2638 * for signal handlers, extra care must be taken to ensure that
2639 * it is enabled only in those places where it's safe.
2642 timer_sighandler(int sig)
2644 delay_timer_expired();
2649 int saved_errno = errno;
2651 if (!restart_delayed_tcbs())
2654 errno = saved_errno;
2657 #ifdef ENABLE_COVERAGE_GCOV
2658 extern void __gcov_flush(void);
2661 static void ATTRIBUTE_NORETURN
2666 if (shared_log != stderr)
2669 while (waitpid(popen_pid, NULL, 0) < 0 && errno == EINTR)
2673 exit_code = 0x100 | interrupted;
2675 if (exit_code > 0xff) {
2676 /* Avoid potential core file clobbering. */
2677 struct_rlimit rlim = {0, 0};
2678 set_rlimit(RLIMIT_CORE, &rlim);
2680 /* Child was killed by a signal, mimic that. */
2682 signal(exit_code, SIG_DFL);
2683 #ifdef ENABLE_COVERAGE_GCOV
2688 /* Unblock the signal. */
2691 sigaddset(&mask, exit_code);
2692 #ifdef ENABLE_COVERAGE_GCOV
2695 sigprocmask(SIG_UNBLOCK, &mask, NULL);
2697 /* Paranoia - what if this signal is not fatal?
2698 Exit with 128 + signo then. */
2705 main(int argc, char *argv[])
2707 setlocale(LC_ALL, "");
2710 exit_code = !nprocs;
2712 while (dispatch_event(next_event()))