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-2019 The strace developers.
9 * SPDX-License-Identifier: LGPL-2.1-or-later
18 #include <sys/resource.h>
28 #include <sys/utsname.h>
30 # include <sys/prctl.h>
33 #include "kill_save_errno.h"
34 #include "filter_seccomp.h"
35 #include "largefile_wrappers.h"
36 #include "mmap_cache.h"
37 #include "number_set.h"
38 #include "ptrace_syscall_info.h"
40 #include "printsiginfo.h"
41 #include "trace_event.h"
46 /* In some libc, these aren't declared. Do it ourself: */
47 extern char **environ;
51 #ifdef ENABLE_STACKTRACE
52 /* if this is true do the stack trace for every system call */
53 bool stack_trace_enabled;
56 #define my_tkill(tid, sig) syscall(__NR_tkill, (tid), (sig))
58 /* Glue for systems without a MMU that cannot provide fork() */
59 #if !defined(HAVE_FORK)
61 # define NOMMU_SYSTEM 1
64 # define fork() vfork()
67 const unsigned int syscall_trap_sig = SIGTRAP | 0x80;
69 cflag_t cflag = CFLAG_NONE;
70 unsigned int followfork;
71 unsigned int ptrace_setoptions = PTRACE_O_TRACESYSGOOD | PTRACE_O_TRACEEXEC
79 static unsigned int tflag;
81 static bool print_pid_pfx;
86 INTR_ANYWHERE = 1, /* don't block/ignore any signals */
87 INTR_WHILE_WAIT = 2, /* block fatal signals while decoding syscall. default */
88 INTR_NEVER = 3, /* block fatal signals. default if '-o FILE PROG' */
89 INTR_BLOCK_TSTP_TOO = 4, /* block fatal signals and SIGTSTP (^Z); default if -D */
93 /* We play with signal mask only if this mode is active: */
94 #define interactive (opt_intr == INTR_WHILE_WAIT)
98 DAEMONIZE_GRANDCHILD = 1,
99 DAEMONIZE_NEW_PGROUP = 2,
100 DAEMONIZE_NEW_SESSION = 3,
102 DAEMONIZE_OPTS_GUARD__,
103 MAX_DAEMONIZE_OPTS = DAEMONIZE_OPTS_GUARD__ - 1
106 * daemonized_tracer supports -D option.
107 * With this option, strace forks twice.
108 * Unlike normal case, with -D *grandparent* process exec's,
109 * becoming a traced process. Child exits (this prevents traced process
110 * from having children it doesn't expect to have), and grandchild
111 * attaches to grandparent similarly to strace -p PID.
112 * This allows for more transparent interaction in cases
113 * when process and its parent are communicating via signals,
114 * wait() etc. Without -D, strace process gets lodged in between,
115 * disrupting parent<->child link.
117 static unsigned int daemonized_tracer;
119 static int post_attach_sigstop = TCB_IGNORE_ONE_SIGSTOP;
120 #define use_seize (post_attach_sigstop == 0)
122 /* Show path associated with fd arguments */
123 unsigned int show_fd_path;
125 static bool detach_on_execve;
127 static int exit_code;
128 static int strace_child;
129 static int strace_tracer_pid;
131 static const char *username;
132 static uid_t run_uid;
133 static gid_t run_gid;
135 unsigned int max_strlen = DEFAULT_STRLEN;
136 static int acolumn = DEFAULT_ACOLUMN;
137 static char *acolumn_spaces;
139 /* Default output style for xlat entities */
140 enum xlat_style xlat_verbosity = XLAT_STYLE_ABBREV;
142 static const char *outfname;
143 /* If -ff, points to stderr. Else, it's our common output log */
144 static FILE *shared_log;
145 static bool open_append;
147 struct tcb *printing_tcp;
148 static struct tcb *current_tcp;
150 struct tcb_wait_data {
151 enum trace_event te; /**< Event passed to dispatch_event() */
152 int status; /**< status, returned by wait4() */
153 unsigned long msg; /**< Value returned by PTRACE_GETEVENTMSG */
154 siginfo_t si; /**< siginfo, returned by PTRACE_GETSIGINFO */
157 static struct tcb **tcbtab;
158 static unsigned int nprocs;
159 static size_t tcbtabsize;
161 static struct tcb_wait_data *tcb_wait_tab;
162 static size_t tcb_wait_tab_size;
165 #ifndef HAVE_PROGRAM_INVOCATION_NAME
166 char *program_invocation_name;
169 unsigned os_release; /* generated from uname()'s u.release */
171 static void detach(struct tcb *tcp);
172 static void cleanup(int sig);
173 static void interrupt(int sig);
175 #ifdef HAVE_SIG_ATOMIC_T
176 static volatile sig_atomic_t interrupted, restart_failed;
178 static volatile int interrupted, restart_failed;
181 static sigset_t timer_set;
182 static void timer_sighandler(int);
184 #ifndef HAVE_STRERROR
186 # if !HAVE_DECL_SYS_ERRLIST
188 extern char *sys_errlist[];
194 static char buf[sizeof("Unknown error %d") + sizeof(int)*3];
196 if (err_no < 1 || err_no >= sys_nerr) {
197 xsprintf(buf, "Unknown error %d", err_no);
200 return sys_errlist[err_no];
203 #endif /* HAVE_STERRROR */
208 static const char features[] =
209 #ifdef ENABLE_STACKTRACE
210 " stack-trace=" USE_UNWINDER
215 #if SUPPORTED_PERSONALITIES > 1
216 # if defined HAVE_M32_MPERS
221 #endif /* SUPPORTED_PERSONALITIES > 1 */
222 #if SUPPORTED_PERSONALITIES > 2
223 # if defined HAVE_MX32_MPERS
228 #endif /* SUPPORTED_PERSONALITIES > 2 */
231 printf("%s -- version %s\n"
232 "Copyright (c) 1991-%s The strace developers <%s>.\n"
233 "This is free software; see the source for copying conditions. There is NO\n"
234 "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n",
235 PACKAGE_NAME, PACKAGE_VERSION, COPYRIGHT_YEAR, PACKAGE_URL);
236 printf("\nOptional features enabled:%s\n",
237 features[0] ? features : " (none)");
243 #ifdef ENABLE_STACKTRACE
250 usage: strace [-ACdffhi" K_OPT "qqrtttTvVwxxyyzZ] [-I n] [-b execve] [-e expr]...\n\
251 [-a column] [-o file] [-s strsize] [-X format] [-P path]...\n\
252 [-p pid]... [--seccomp-bpf]\n\
253 { -p pid | [-DDD] [-E var=val]... [-u username] PROG [ARGS] }\n\
254 or: strace -c[dfwzZ] [-I n] [-b execve] [-e expr]... [-O overhead]\n\
255 [-S sortby] [-P path]... [-p pid]... [--seccomp-bpf]\n\
256 { -p pid | [-DDD] [-E var=val]... [-u username] PROG [ARGS] }\n\
259 -A open the file provided in the -o option in append mode\n\
260 -a column alignment COLUMN for printing syscall results (default %d)\n\
261 -i print instruction pointer at time of syscall\n\
263 #ifdef ENABLE_STACKTRACE
265 -k obtain stack trace between each syscall\n\
269 -o file send trace output to FILE instead of stderr\n\
270 -q suppress messages about attaching, detaching, etc.\n\
271 -qq suppress messages about process exit status as well.\n\
272 -r print relative timestamp\n\
273 -s strsize limit length of print strings to STRSIZE chars (default %d)\n\
274 -t print absolute timestamp\n\
275 -tt print absolute timestamp with usecs\n\
276 -T print time spent in each syscall\n\
277 -v verbose mode: print entities unabbreviated\n\
278 -x print non-ascii strings in hex\n\
279 -xx print all strings in hex\n\
280 -X format set the format for printing of named constants and flags\n\
281 -y print paths associated with file descriptor arguments\n\
282 -yy print protocol specific information associated with socket\n\
286 -c count time, calls, and errors for each syscall and report\n\
288 -C like -c but also print regular output\n\
289 -O overhead set overhead for tracing syscalls to OVERHEAD usecs\n\
290 -S sortby sort syscall counts by: time, calls, errors, name, nothing\n\
292 -w summarise syscall latency (default is system time)\n\
295 -e expr a qualifying expression: option=[!]all or option=[!]val1[,val2]...\n\
296 options: trace, abbrev, verbose, raw, signal, read, write, fault,\n\
297 inject, status, kvm\n\
298 -P path trace accesses to path\n\
299 -z print only syscalls that returned without an error code\n\
300 -Z print only syscalls that returned with an error code\n\
303 -b execve detach on execve syscall\n\
304 -D run tracer process as a grandchild, not as a parent\n\
305 -DD run tracer process in a separate process group\n\
306 -DDD run tracer process in a separate session\n\
308 -ff follow forks with output into separate files\n\
310 1: no signals are blocked\n\
311 2: fatal signals are blocked while decoding syscall (default)\n\
312 3: fatal signals are always blocked (default if '-o FILE PROG')\n\
313 4: fatal signals and SIGTSTP (^Z) are always blocked\n\
314 (useful to make 'strace -o FILE PROG' not stop on ^Z)\n\
317 -E var remove var from the environment for command\n\
318 -E var=val put var=val in the environment for command\n\
319 -p pid trace process with process id PID, may be repeated\n\
320 -u username run command as username handling setuid and/or setgid\n\
323 --seccomp-bpf enable seccomp-bpf filtering\n\
324 -d enable debug output to stderr\n\
325 -h, --help print help message\n\
326 -V, --version print version\n\
328 /* ancient, no one should use it
329 -F -- attempt to follow vforks (deprecated, use -f)\n\
331 , DEFAULT_ACOLUMN, DEFAULT_STRLEN, DEFAULT_SORTBY);
337 void ATTRIBUTE_NORETURN
340 if (strace_tracer_pid == getpid()) {
349 error_opt_arg(int opt, const char *arg)
351 error_msg_and_help("invalid -%c argument: '%s'", opt, arg);
354 static const char *ptrace_attach_cmd;
357 ptrace_attach_or_seize(int pid)
361 return ptrace_attach_cmd = "PTRACE_ATTACH",
362 ptrace(PTRACE_ATTACH, pid, 0L, 0L);
363 r = ptrace(PTRACE_SEIZE, pid, 0L, (unsigned long) ptrace_setoptions);
365 return ptrace_attach_cmd = "PTRACE_SEIZE", r;
366 r = ptrace(PTRACE_INTERRUPT, pid, 0L, 0L);
367 return ptrace_attach_cmd = "PTRACE_INTERRUPT", r;
371 ptrace_op_str(unsigned int op)
373 const char *str = xlookup(ptrace_cmds, op);
377 static char buf[sizeof(op) * 3];
378 xsprintf(buf, "%u", op);
383 * Used when we want to unblock stopped traced process.
384 * Should be only used with PTRACE_CONT, PTRACE_DETACH and PTRACE_SYSCALL.
385 * Returns 0 on success or if error was ESRCH
386 * (presumably process was killed while we talk to it).
387 * Otherwise prints error message and returns -1.
390 ptrace_restart(const unsigned int op, struct tcb *const tcp, unsigned int sig)
395 ptrace(op, tcp->pid, 0L, (unsigned long) sig);
397 if (!err || err == ESRCH)
401 * Why curcol != 0? Otherwise sometimes we get this:
403 * 10252 kill(10253, SIGKILL) = 0
404 * <ptrace(SYSCALL,10252):No such process>10253 ...next decode...
406 * 10252 died after we retrieved syscall exit data,
407 * but before we tried to restart it. Log looks ugly.
409 if (current_tcp && current_tcp->curcol != 0) {
410 tprintf(" <Cannot restart pid %d with ptrace(%s): %s>\n",
411 tcp->pid, ptrace_op_str(op), strerror(err));
415 perror_msg("ptrace(%s,pid:%d,sig:%u)",
416 ptrace_op_str(op), tcp->pid, sig);
421 set_cloexec_flag(int fd)
425 flags = fcntl(fd, F_GETFD);
427 /* Can happen only if fd is bad.
428 * Should never happen: if it does, we have a bug
429 * in the caller. Therefore we just abort
430 * instead of propagating the error.
432 perror_msg_and_die("fcntl(%d, F_GETFD)", fd);
435 newflags = flags | FD_CLOEXEC;
436 if (flags == newflags)
439 if (fcntl(fd, F_SETFD, newflags)) /* never fails */
440 perror_msg_and_die("fcntl(%d, F_SETFD, %#x)", fd, newflags);
444 * When strace is setuid executable, we have to swap uids
445 * before and after filesystem and process management operations.
450 int euid = geteuid(), uid = getuid();
452 if (euid != uid && setreuid(euid, uid) < 0) {
453 perror_msg_and_die("setreuid");
458 strace_fopen(const char *path)
463 fp = fopen_stream(path, open_append ? "a" : "w");
465 perror_msg_and_die("Can't fopen '%s'", path);
467 set_cloexec_flag(fileno(fp));
471 static int popen_pid;
474 # define _PATH_BSHELL "/bin/sh"
478 * We cannot use standard popen(3) here because we have to distinguish
479 * popen child process from other processes we trace, and standard popen(3)
480 * does not export its child's pid.
483 strace_popen(const char *command)
491 perror_msg_and_die("pipe");
493 set_cloexec_flag(fds[1]); /* never fails */
497 perror_msg_and_die("vfork");
504 perror_msg_and_die("dup2");
507 execl(_PATH_BSHELL, "sh", "-c", command, NULL);
508 perror_msg_and_die("Can't execute '%s'", _PATH_BSHELL);
515 fp = fdopen(fds[1], "w");
517 perror_msg_and_die("fdopen");
522 outf_perror(const struct tcb * const tcp)
524 if (tcp->outf == stderr)
527 /* This is ugly, but we don't store separate file names */
529 perror_msg("%s.%u", outfname, tcp->pid);
531 perror_msg("%s", outfname);
534 ATTRIBUTE_FORMAT((printf, 1, 0))
536 tvprintf(const char *const fmt, va_list args)
539 int n = vfprintf(current_tcp->outf, fmt, args);
541 /* very unlikely due to vfprintf buffering */
542 outf_perror(current_tcp);
544 current_tcp->curcol += n;
549 tprintf(const char *fmt, ...)
557 #ifndef HAVE_FPUTS_UNLOCKED
558 # define fputs_unlocked fputs
562 tprints(const char *str)
565 int n = fputs_unlocked(str, current_tcp->outf);
567 current_tcp->curcol += strlen(str);
570 /* very unlikely due to fputs_unlocked buffering */
571 outf_perror(current_tcp);
576 tprints_comment(const char *const str)
579 tprintf(" /* %s */", str);
583 tprintf_comment(const char *fmt, ...)
597 flush_tcp_output(const struct tcb *const tcp)
599 if (fflush(tcp->outf))
607 current_tcp->curcol = 0;
608 flush_tcp_output(current_tcp);
611 printing_tcp->curcol = 0;
617 set_current_tcp(const struct tcb *tcp)
619 current_tcp = (struct tcb *) tcp;
621 /* Sync current_personality and stuff */
623 set_personality(current_tcp->currpers);
627 printleader(struct tcb *tcp)
629 /* If -ff, "previous tcb we printed" is always the same as current,
630 * because we have per-tcb output files.
636 set_current_tcp(printing_tcp);
637 if (!tcp->staged_output_data && printing_tcp->curcol != 0 &&
638 (followfork < 2 || printing_tcp == tcp)) {
640 * case 1: we have a shared log (i.e. not -ff), and last line
641 * wasn't finished (same or different tcb, doesn't matter).
642 * case 2: split log, we are the same tcb, but our last line
643 * didn't finish ("SIGKILL nuked us after syscall entry" etc).
645 tprints(" <unfinished ...>\n");
646 printing_tcp->curcol = 0;
651 set_current_tcp(tcp);
652 current_tcp->curcol = 0;
655 tprintf("%-5d ", tcp->pid);
656 else if (nprocs > 1 && !outfname)
657 tprintf("[pid %5u] ", tcp->pid);
661 clock_gettime(CLOCK_REALTIME, &ts);
664 tprintf("%lld.%06ld ",
665 (long long) ts.tv_sec, (long) ts.tv_nsec / 1000);
667 time_t local = ts.tv_sec;
668 char str[MAX(sizeof("HH:MM:SS"), sizeof(ts.tv_sec) * 3)];
669 struct tm *tm = localtime(&local);
672 strftime(str, sizeof(str), "%T", tm);
674 xsprintf(str, "%lld", (long long) local);
677 str, (long) ts.tv_nsec / 1000);
685 clock_gettime(CLOCK_MONOTONIC, &ts);
687 static struct timespec ots;
692 ts_sub(&dts, &ts, &ots);
695 tprintf("%s%6ld.%06ld%s ",
697 (long) dts.tv_sec, (long) dts.tv_nsec / 1000,
702 print_instruction_pointer(tcp);
708 if (current_tcp->curcol < acolumn)
709 tprints(acolumn_spaces + current_tcp->curcol);
712 /* Should be only called directly *after successful attach* to a tracee.
713 * Otherwise, "strace -oFILE -ff -p<nonexistant_pid>"
714 * may create bogus empty FILE.<nonexistant_pid>, and then die.
717 after_successful_attach(struct tcb *tcp, const unsigned int flags)
719 tcp->flags |= TCB_ATTACHED | TCB_STARTUP | flags;
720 tcp->outf = shared_log; /* if not -ff mode, the same file is for all */
721 if (followfork >= 2) {
723 xsprintf(name, "%s.%u", outfname, tcp->pid);
724 tcp->outf = strace_fopen(name);
727 #ifdef ENABLE_STACKTRACE
728 if (stack_trace_enabled)
729 unwind_tcb_init(tcp);
736 /* Allocate some (more) TCBs (and expand the table).
737 We don't want to relocate the TCBs because our
738 callers have pointers and it would be a pain.
739 So tcbtab is a table of pointers. Since we never
740 free the TCBs, we allocate a single chunk of many. */
741 size_t old_tcbtabsize;
743 struct tcb **tcb_ptr;
745 old_tcbtabsize = tcbtabsize;
747 tcbtab = xgrowarray(tcbtab, &tcbtabsize, sizeof(tcbtab[0]));
748 newtcbs = xcalloc(tcbtabsize - old_tcbtabsize, sizeof(newtcbs[0]));
750 for (tcb_ptr = tcbtab + old_tcbtabsize;
751 tcb_ptr < tcbtab + tcbtabsize; tcb_ptr++, newtcbs++)
761 if (nprocs == tcbtabsize)
764 for (i = 0; i < tcbtabsize; i++) {
767 memset(tcp, 0, sizeof(*tcp));
768 list_init(&tcp->wait_list);
770 #if SUPPORTED_PERSONALITIES > 1
771 tcp->currpers = current_personality;
774 debug_msg("new tcb for pid %d, active tcbs:%d",
779 error_msg_and_die("bug in alloctcb");
783 get_tcb_priv_data(const struct tcb *tcp)
785 return tcp->_priv_data;
789 set_tcb_priv_data(struct tcb *tcp, void *const priv_data,
790 void (*const free_priv_data)(void *))
795 tcp->_free_priv_data = free_priv_data;
796 tcp->_priv_data = priv_data;
802 free_tcb_priv_data(struct tcb *tcp)
804 if (tcp->_priv_data) {
805 if (tcp->_free_priv_data) {
806 tcp->_free_priv_data(tcp->_priv_data);
807 tcp->_free_priv_data = NULL;
809 tcp->_priv_data = NULL;
814 droptcb(struct tcb *tcp)
819 if (cflag && debug_flag) {
822 ts_sub(&dt, &tcp->stime, &tcp->atime);
823 debug_func_msg("pid %d: %.9f seconds of system time spent "
824 "since attach", tcp->pid, ts_float(&dt));
828 for (p = 0; p < SUPPORTED_PERSONALITIES; ++p)
829 free(tcp->inject_vec[p]);
831 free_tcb_priv_data(tcp);
833 #ifdef ENABLE_STACKTRACE
834 if (stack_trace_enabled)
838 #ifdef HAVE_LINUX_KVM_H
839 kvm_vcpu_info_free(tcp);
843 tcp->mmap_cache->free_fn(tcp, __func__);
846 debug_msg("dropped tcb for pid %d, %d remain", tcp->pid, nprocs);
850 if (!is_complete_set(status_set, NUMBER_OF_STATUSES)) {
851 publish = is_number_in_set(STATUS_DETACHED, status_set);
852 strace_close_memstream(tcp, publish);
855 if (followfork >= 2) {
856 if (tcp->curcol != 0 && publish)
857 fprintf(tcp->outf, " <detached ...>\n");
860 if (printing_tcp == tcp && tcp->curcol != 0 && publish)
861 fprintf(tcp->outf, " <detached ...>\n");
862 flush_tcp_output(tcp);
866 if (current_tcp == tcp)
867 set_current_tcp(NULL);
868 if (printing_tcp == tcp)
871 list_remove(&tcp->wait_list);
873 memset(tcp, 0, sizeof(*tcp));
876 /* Detach traced process.
877 * Never call DETACH twice on the same process as both unattached and
878 * attached-unstopped processes give the same ESRCH. For unattached process we
879 * would SIGSTOP it and wait for its SIGSTOP notification forever.
882 detach(struct tcb *tcp)
888 * Linux wrongly insists the child be stopped
889 * before detaching. Arghh. We go through hoops
890 * to make a clean break of things.
893 if (!(tcp->flags & TCB_ATTACHED))
896 /* We attached but possibly didn't see the expected SIGSTOP.
897 * We must catch exactly one as otherwise the detached process
898 * would be left stopped (process state T).
900 if (tcp->flags & TCB_IGNORE_ONE_SIGSTOP)
903 error = ptrace(PTRACE_DETACH, tcp->pid, 0, 0);
905 /* On a clear day, you can see forever. */
908 if (errno != ESRCH) {
909 /* Shouldn't happen. */
910 perror_func_msg("ptrace(PTRACE_DETACH,%u)", tcp->pid);
913 /* ESRCH: process is either not stopped or doesn't exist. */
914 if (my_tkill(tcp->pid, 0) < 0) {
916 /* Shouldn't happen. */
917 perror_func_msg("tkill(%u,0)", tcp->pid);
918 /* else: process doesn't exist. */
921 /* Process is not stopped, need to stop it. */
924 * With SEIZE, tracee can be in group-stop already.
925 * In this state sending it another SIGSTOP does nothing.
926 * Need to use INTERRUPT.
927 * Testcase: trying to ^C a "strace -p <stopped_process>".
929 error = ptrace(PTRACE_INTERRUPT, tcp->pid, 0, 0);
933 perror_func_msg("ptrace(PTRACE_INTERRUPT,%u)", tcp->pid);
935 error = my_tkill(tcp->pid, SIGSTOP);
939 perror_func_msg("tkill(%u,SIGSTOP)", tcp->pid);
941 /* Either process doesn't exist, or some weird error. */
945 /* We end up here in three cases:
946 * 1. We sent PTRACE_INTERRUPT (use_seize case)
947 * 2. We sent SIGSTOP (!use_seize)
948 * 3. Attach SIGSTOP was already pending (TCB_IGNORE_ONE_SIGSTOP set)
952 if (waitpid(tcp->pid, &status, __WALL) < 0) {
956 * if (errno == ECHILD) break;
957 * ^^^ WRONG! We expect this PID to exist,
958 * and want to emit a message otherwise:
960 perror_func_msg("waitpid(%u)", tcp->pid);
963 if (!WIFSTOPPED(status)) {
965 * Tracee exited or was killed by signal.
966 * We shouldn't normally reach this place:
967 * we don't want to consume exit status.
968 * Consider "strace -p PID" being ^C-ed:
969 * we want merely to detach from PID.
971 * However, we _can_ end up here if tracee
976 sig = WSTOPSIG(status);
977 debug_msg("detach wait: event:%d sig:%d",
978 (unsigned) status >> 16, sig);
980 unsigned event = (unsigned)status >> 16;
981 if (event == PTRACE_EVENT_STOP /*&& sig == SIGTRAP*/) {
983 * sig == SIGTRAP: PTRACE_INTERRUPT stop.
984 * sig == other: process was already stopped
985 * with this stopping sig (see tests/detach-stopped).
986 * Looks like re-injecting this sig is not necessary
987 * in DETACH for the tracee to remain stopped.
992 * PTRACE_INTERRUPT is not guaranteed to produce
993 * the above event if other ptrace-stop is pending.
994 * See tests/detach-sleeping testcase:
995 * strace got SIGINT while tracee is sleeping.
996 * We sent PTRACE_INTERRUPT.
997 * We see syscall exit, not PTRACE_INTERRUPT stop.
998 * We won't get PTRACE_INTERRUPT stop
999 * if we would CONT now. Need to DETACH.
1001 if (sig == syscall_trap_sig)
1003 /* else: not sure in which case we can be here.
1004 * Signal stop? Inject it while detaching.
1006 ptrace_restart(PTRACE_DETACH, tcp, sig);
1009 /* Note: this check has to be after use_seize check */
1010 /* (else, in use_seize case SIGSTOP will be mistreated) */
1011 if (sig == SIGSTOP) {
1012 /* Detach, suppressing SIGSTOP */
1013 ptrace_restart(PTRACE_DETACH, tcp, 0);
1016 if (sig == syscall_trap_sig)
1018 /* Can't detach just yet, may need to wait for SIGSTOP */
1019 error = ptrace_restart(PTRACE_CONT, tcp, sig);
1021 /* Should not happen.
1022 * Note: ptrace_restart returns 0 on ESRCH, so it's not it.
1023 * ptrace_restart already emitted error message.
1030 if (!qflag && (tcp->flags & TCB_ATTACHED))
1031 error_msg("Process %u detached", tcp->pid);
1037 process_opt_p_list(char *opt)
1041 * We accept -p PID,PID; -p "`pidof PROG`"; -p "`pgrep PROG`".
1042 * pidof uses space as delim, pgrep uses newline. :(
1045 char *delim = opt + strcspn(opt, "\n\t ,");
1049 pid = string_to_uint(opt);
1051 error_msg_and_die("Invalid process id: '%s'", opt);
1053 if (pid == strace_tracer_pid) {
1054 error_msg_and_die("I'm sorry, I can't let you do that, Dave.");
1065 attach_tcb(struct tcb *const tcp)
1067 if (ptrace_attach_or_seize(tcp->pid) < 0) {
1068 perror_msg("attach: ptrace(%s, %d)",
1069 ptrace_attach_cmd, tcp->pid);
1074 after_successful_attach(tcp, TCB_GRABBED | post_attach_sigstop);
1075 debug_msg("attach to pid %d (main) succeeded", tcp->pid);
1077 static const char task_path[] = "/proc/%d/task";
1078 char procdir[sizeof(task_path) + sizeof(int) * 3];
1080 unsigned int ntid = 0, nerr = 0;
1082 if (followfork && tcp->pid != strace_child &&
1083 xsprintf(procdir, task_path, tcp->pid) > 0 &&
1084 (dir = opendir(procdir)) != NULL) {
1087 while ((de = read_dir(dir)) != NULL) {
1088 if (de->d_fileno == 0)
1091 int tid = string_to_uint(de->d_name);
1092 if (tid <= 0 || tid == tcp->pid)
1096 if (ptrace_attach_or_seize(tid) < 0) {
1098 debug_perror_msg("attach: ptrace(%s, %d)",
1099 ptrace_attach_cmd, tid);
1103 after_successful_attach(alloctcb(tid),
1104 TCB_GRABBED | post_attach_sigstop);
1105 debug_msg("attach to pid %d succeeded", tid);
1113 error_msg("Process %u attached"
1115 tcp->pid, ntid - nerr + 1);
1117 error_msg("Process %u attached",
1123 startup_attach(void)
1125 pid_t parent_pid = strace_tracer_pid;
1129 if (daemonized_tracer) {
1132 perror_func_msg_and_die("fork");
1134 if (pid) { /* parent */
1136 * Wait for grandchild to attach to straced process
1137 * (grandparent). Grandchild SIGKILLs us after it attached.
1138 * Grandparent's wait() is unblocked by our death,
1139 * it proceeds to exec the straced program.
1142 _exit(0); /* paranoia */
1145 /* We will be the tracer process. Remember our new pid: */
1146 strace_tracer_pid = getpid();
1148 switch (daemonized_tracer) {
1149 case DAEMONIZE_NEW_PGROUP:
1151 * If -D is passed twice, create a new process group,
1152 * so we won't be killed by kill(0, ...).
1154 if (setpgid(0, 0) < 0)
1155 perror_msg_and_die("Cannot create a new"
1158 case DAEMONIZE_NEW_SESSION:
1160 * If -D is passed thrice, create a new session,
1161 * so we won't be killed upon session termination.
1164 perror_msg_and_die("Cannot create a new"
1170 for (tcbi = 0; tcbi < tcbtabsize; tcbi++) {
1176 /* Is this a process we should attach to, but not yet attached? */
1177 if (tcp->flags & TCB_ATTACHED)
1178 continue; /* no, we already attached it */
1180 if (tcp->pid == parent_pid || tcp->pid == strace_tracer_pid) {
1182 perror_msg("attach: pid %d", tcp->pid);
1191 } /* for each tcbtab[] */
1193 if (daemonized_tracer) {
1195 * Make parent go away.
1196 * Also makes grandparent's wait() unblock.
1198 kill(parent_pid, SIGKILL);
1203 /* Stack-o-phobic exec helper, in the hope to work around
1204 * NOMMU + "daemonized tracer" difficulty.
1206 struct exec_params {
1212 struct sigaction child_sa;
1214 static struct exec_params params_for_tracee;
1216 static void ATTRIBUTE_NOINLINE ATTRIBUTE_NORETURN
1219 struct exec_params *params = ¶ms_for_tracee;
1221 if (params->fd_to_close >= 0)
1222 close(params->fd_to_close);
1223 if (!daemonized_tracer && !use_seize) {
1224 if (ptrace(PTRACE_TRACEME, 0L, 0L, 0L) < 0) {
1225 perror_msg_and_die("ptrace(PTRACE_TRACEME, ...)");
1229 if (username != NULL) {
1231 * It is important to set groups before we
1232 * lose privileges on setuid.
1234 if (initgroups(username, run_gid) < 0) {
1235 perror_msg_and_die("initgroups");
1237 if (setregid(run_gid, params->run_egid) < 0) {
1238 perror_msg_and_die("setregid");
1240 if (setreuid(run_uid, params->run_euid) < 0) {
1241 perror_msg_and_die("setreuid");
1243 } else if (geteuid() != 0)
1244 if (setreuid(run_uid, run_uid) < 0) {
1245 perror_msg_and_die("setreuid");
1248 if (!daemonized_tracer) {
1250 * Induce a ptrace stop. Tracer (our parent)
1251 * will resume us with PTRACE_SYSCALL and display
1252 * the immediately following execve syscall.
1253 * Can't do this on NOMMU systems, we are after
1254 * vfork: parent is blocked, stopping would deadlock.
1257 kill(getpid(), SIGSTOP);
1260 /* we depend on SIGCHLD set to SIG_DFL by init code */
1261 /* if it happens to be SIG_IGN'ed, wait won't block */
1266 if (params_for_tracee.child_sa.sa_handler != SIG_DFL)
1267 sigaction(SIGCHLD, ¶ms_for_tracee.child_sa, NULL);
1269 debug_msg("seccomp filter %s",
1270 seccomp_filtering ? "enabled" : "disabled");
1271 if (seccomp_filtering)
1272 init_seccomp_filter();
1273 execv(params->pathname, params->argv);
1274 perror_msg_and_die("exec");
1278 * Open a dummy descriptor for use as a placeholder.
1279 * The descriptor is O_RDONLY with FD_CLOEXEC flag set.
1280 * A read attempt from such descriptor ends with EOF,
1281 * a write attempt is rejected with EBADF.
1284 open_dummy_desc(void)
1289 perror_func_msg_and_die("pipe");
1291 set_cloexec_flag(fds[0]);
1295 /* placeholder fds status for stdin and stdout */
1296 static bool fd_is_placeholder[2];
1299 * Ensure that all standard file descriptors are open by opening placeholder
1300 * file descriptors for those standard file descriptors that are not open.
1302 * The information which descriptors have been made open is saved
1303 * in fd_is_placeholder for later use.
1306 ensure_standard_fds_opened(void)
1310 while ((fd = open_dummy_desc()) <= 2) {
1313 fd_is_placeholder[fd] = true;
1321 * Redirect stdin and stdout unless they have been opened earlier
1322 * by ensure_standard_fds_opened as placeholders.
1325 redirect_standard_fds(void)
1330 * It might be a good idea to redirect stderr as well,
1331 * but we sometimes need to print error messages.
1333 for (i = 0; i <= 1; ++i) {
1334 if (!fd_is_placeholder[i]) {
1342 startup_child(char **argv)
1344 strace_stat_t statbuf;
1345 const char *filename;
1346 size_t filename_len;
1347 char pathname[PATH_MAX];
1352 filename_len = strlen(filename);
1354 if (filename_len > sizeof(pathname) - 1) {
1355 errno = ENAMETOOLONG;
1356 perror_msg_and_die("exec");
1358 if (strchr(filename, '/')) {
1359 strcpy(pathname, filename);
1361 #ifdef USE_DEBUGGING_EXEC
1363 * Debuggers customarily check the current directory
1364 * first regardless of the path but doing that gives
1365 * security geeks a panic attack.
1367 else if (stat_file(filename, &statbuf) == 0)
1368 strcpy(pathname, filename);
1369 #endif /* USE_DEBUGGING_EXEC */
1374 for (path = getenv("PATH"); path && *path; path += m) {
1375 const char *colon = strchr(path, ':');
1380 m = n = strlen(path);
1382 if (!getcwd(pathname, PATH_MAX))
1384 len = strlen(pathname);
1385 } else if (n > sizeof(pathname) - 1)
1388 strncpy(pathname, path, n);
1391 if (len && pathname[len - 1] != '/')
1392 pathname[len++] = '/';
1393 if (filename_len + len > sizeof(pathname) - 1)
1395 strcpy(pathname + len, filename);
1396 if (stat_file(pathname, &statbuf) == 0 &&
1397 /* Accept only regular files
1398 with some execute bits set.
1399 XXX not perfect, might still fail */
1400 S_ISREG(statbuf.st_mode) &&
1401 (statbuf.st_mode & 0111))
1404 if (!path || !*path)
1407 if (stat_file(pathname, &statbuf) < 0) {
1408 perror_msg_and_die("Can't stat '%s'", filename);
1411 params_for_tracee.fd_to_close = (shared_log != stderr) ? fileno(shared_log) : -1;
1412 params_for_tracee.run_euid = (statbuf.st_mode & S_ISUID) ? statbuf.st_uid : run_uid;
1413 params_for_tracee.run_egid = (statbuf.st_mode & S_ISGID) ? statbuf.st_gid : run_gid;
1414 params_for_tracee.argv = argv;
1416 * On NOMMU, can be safely freed only after execve in tracee.
1417 * It's hard to know when that happens, so we just leak it.
1419 params_for_tracee.pathname = NOMMU_SYSTEM ? xstrdup(pathname) : pathname;
1421 #if defined HAVE_PRCTL && defined PR_SET_PTRACER && defined PR_SET_PTRACER_ANY
1422 if (daemonized_tracer)
1423 prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY);
1428 perror_func_msg_and_die("fork");
1430 if ((pid != 0 && daemonized_tracer)
1431 || (pid == 0 && !daemonized_tracer)
1433 /* We are to become the tracee. Two cases:
1435 * not -D: we are child
1440 /* We are the tracer */
1442 if (!daemonized_tracer) {
1445 /* child did PTRACE_TRACEME, nothing to do in parent */
1447 if (!NOMMU_SYSTEM) {
1448 /* Wait until child stopped itself */
1450 while (waitpid(pid, &status, WSTOPPED) < 0) {
1453 perror_msg_and_die("waitpid");
1455 if (!WIFSTOPPED(status) || WSTOPSIG(status) != SIGSTOP) {
1456 kill_save_errno(pid, SIGKILL);
1457 perror_msg_and_die("Unexpected wait status %#x",
1461 /* Else: NOMMU case, we have no way to sync.
1462 * Just attach to it as soon as possible.
1463 * This means that we may miss a few first syscalls...
1466 if (ptrace_attach_or_seize(pid)) {
1467 kill_save_errno(pid, SIGKILL);
1468 perror_msg_and_die("attach: ptrace(%s, %d)",
1469 ptrace_attach_cmd, pid);
1474 tcp = alloctcb(pid);
1475 after_successful_attach(tcp, TCB_SKIP_DETACH_ON_FIRST_EXEC
1478 | post_attach_sigstop)));
1480 /* With -D, we are *child* here, the tracee is our parent. */
1481 strace_child = strace_tracer_pid;
1482 strace_tracer_pid = getpid();
1483 tcp = alloctcb(strace_child);
1484 tcp->flags |= TCB_SKIP_DETACH_ON_FIRST_EXEC | TCB_HIDE_LOG;
1486 * Attaching will be done later, by startup_attach.
1487 * Note: we don't do after_successful_attach() here either!
1490 /* NOMMU BUG! -D mode is active, we (child) return,
1491 * and we will scribble over parent's stack!
1492 * When parent later unpauses, it segfaults.
1495 * (1) by declaring exec_or_die() NORETURN,
1496 * hopefully compiler will just jump to it
1497 * instead of call (won't push anything to stack),
1498 * (2) by trying very hard in exec_or_die()
1499 * to not use any stack,
1500 * (3) having a really big (PATH_MAX) stack object
1501 * in this function, which creates a "buffer" between
1502 * child's and parent's stack pointers.
1503 * This may save us if (1) and (2) failed
1504 * and compiler decided to use stack in exec_or_die() anyway
1505 * (happens on i386 because of stack parameter passing).
1507 * A cleaner solution is to use makecontext + setcontext
1508 * to create a genuine separate stack and execute on it.
1512 if (seccomp_filtering)
1513 tcp->flags |= TCB_SECCOMP_FILTER;
1516 * A case where straced process is part of a pipe:
1517 * { sleep 1; yes | head -n99999; } | strace -o/dev/null sh -c 'exec <&-; sleep 9'
1518 * If strace won't close its fd#0, closing it in tracee is not enough:
1519 * the pipe is still open, it has a reader. Thus, "head" will not get its
1520 * SIGPIPE at once, on the first write.
1522 * Preventing it by redirecting strace's stdin/out.
1523 * (Don't leave fds 0 and 1 closed, this is bad practice: future opens
1524 * will reuse them, unexpectedly making a newly opened object "stdin").
1526 redirect_standard_fds();
1530 test_ptrace_seize(void)
1534 /* Need fork for test. NOMMU has no forks */
1536 post_attach_sigstop = 0; /* this sets use_seize to 1 */
1542 perror_func_msg_and_die("fork");
1549 /* PTRACE_SEIZE, unlike ATTACH, doesn't force tracee to trap. After
1550 * attaching tracee continues to run unless a trap condition occurs.
1551 * PTRACE_SEIZE doesn't affect signal or group stop state.
1553 if (ptrace(PTRACE_SEIZE, pid, 0, 0) == 0) {
1554 post_attach_sigstop = 0; /* this sets use_seize to 1 */
1556 debug_msg("PTRACE_SEIZE doesn't work");
1562 int status, tracee_pid;
1565 tracee_pid = waitpid(pid, &status, 0);
1566 if (tracee_pid <= 0) {
1569 perror_func_msg_and_die("unexpected wait result %d",
1572 if (WIFSIGNALED(status))
1575 error_func_msg_and_die("unexpected wait status %#x", status);
1580 get_os_release(void)
1584 perror_msg_and_die("uname");
1586 * u.release string consists of at most three parts
1587 * and normally has this form: "3.2.9[-some-garbage]",
1588 * "X.Y-something" means "X.Y.0".
1590 const char *p = u.release;
1591 unsigned int rel = 0;
1592 for (unsigned int parts = 0; parts < 3; ++parts) {
1594 for (; (*p >= '0') && (*p <= '9'); ++p) {
1607 set_sighandler(int signo, void (*sighandler)(int), struct sigaction *oldact)
1609 const struct sigaction sa = { .sa_handler = sighandler };
1610 sigaction(signo, &sa, oldact);
1614 * Initialization part of main() was eating much stack (~0.5k),
1615 * which was unused after init.
1616 * We can reuse it if we move init code into a separate function.
1618 * Don't want main() to inline us and defeat the reason
1619 * we have a separate function.
1621 static void ATTRIBUTE_NOINLINE
1622 init(int argc, char *argv[])
1625 int optF = 0, zflags = 0;
1627 if (!program_invocation_name || !*program_invocation_name) {
1628 static char name[] = "strace";
1629 program_invocation_name =
1630 (argc > 0 && argv[0] && *argv[0]) ? argv[0] : name;
1633 strace_tracer_pid = getpid();
1635 os_release = get_os_release();
1637 shared_log = stderr;
1638 set_sortby(DEFAULT_SORTBY);
1639 set_personality(DEFAULT_PERSONALITY);
1640 qualify("trace=all");
1641 qualify("abbrev=all");
1642 qualify("verbose=all");
1643 qualify("status=all");
1644 #if DEFAULT_QUAL_FLAGS != (QUAL_TRACE | QUAL_ABBREV | QUAL_VERBOSE)
1645 # error Bug in DEFAULT_QUAL_FLAGS
1647 qualify("signal=all");
1649 static const char optstring[] = "+"
1650 #ifdef ENABLE_STACKTRACE
1653 "a:Ab:cCdDe:E:fFhiI:o:O:p:P:qrs:S:tTu:vVwxX:yzZ";
1656 SECCOMP_OPTION = 0x100
1658 static const struct option longopts[] = {
1659 { "seccomp-bpf", no_argument, 0, SECCOMP_OPTION },
1660 { "help", no_argument, 0, 'h' },
1661 { "version", no_argument, 0, 'V' },
1665 while ((c = getopt_long(argc, argv, optstring, longopts, NULL)) != EOF) {
1668 acolumn = string_to_uint(optarg);
1670 error_opt_arg(c, optarg);
1676 if (strcmp(optarg, "execve") != 0)
1677 error_msg_and_die("Syscall '%s' for -b isn't supported",
1679 detach_on_execve = 1;
1682 if (cflag == CFLAG_BOTH) {
1683 error_msg_and_help("-c and -C are mutually exclusive");
1685 cflag = CFLAG_ONLY_STATS;
1688 if (cflag == CFLAG_ONLY_STATS) {
1689 error_msg_and_help("-c and -C are mutually exclusive");
1697 daemonized_tracer++;
1703 if (putenv(optarg) < 0)
1704 perror_msg_and_die("putenv");
1719 opt_intr = string_to_uint_upto(optarg, NUM_INTR_OPTS - 1);
1721 error_opt_arg(c, optarg);
1723 #ifdef ENABLE_STACKTRACE
1725 stack_trace_enabled = true;
1732 if (set_overhead(optarg) < 0)
1733 error_opt_arg(c, optarg);
1736 process_opt_p_list(optarg);
1739 pathtrace_select(optarg);
1748 i = string_to_uint(optarg);
1749 if (i < 0 || (unsigned int) i > -1U / 4)
1750 error_opt_arg(c, optarg);
1766 qualify("abbrev=none");
1773 count_wallclock = 1;
1779 if (!strcmp(optarg, "raw"))
1780 xlat_verbosity = XLAT_STYLE_RAW;
1781 else if (!strcmp(optarg, "abbrev"))
1782 xlat_verbosity = XLAT_STYLE_ABBREV;
1783 else if (!strcmp(optarg, "verbose"))
1784 xlat_verbosity = XLAT_STYLE_VERBOSE;
1786 error_opt_arg(c, optarg);
1792 clear_number_set_array(status_set, 1);
1793 add_number_to_set(STATUS_SUCCESSFUL, status_set);
1797 clear_number_set_array(status_set, 1);
1798 add_number_to_set(STATUS_FAILED, status_set);
1801 case SECCOMP_OPTION:
1802 seccomp_filtering = true;
1805 error_msg_and_help(NULL);
1813 if (argc < 0 || (!nprocs && !argc)) {
1814 error_msg_and_help("must have PROG [ARGS] or -p PID");
1817 if (!argc && daemonized_tracer) {
1818 error_msg_and_help("PROG [ARGS] must be specified with -D");
1821 if (daemonized_tracer > (unsigned int) MAX_DAEMONIZE_OPTS)
1822 error_msg_and_help("Too many -D's (%u), maximum supported -D "
1824 daemonized_tracer, MAX_DAEMONIZE_OPTS);
1826 if (seccomp_filtering && detach_on_execve) {
1827 error_msg("--seccomp-bpf is not enabled because"
1828 " it is not compatible with -b");
1829 seccomp_filtering = false;
1832 if (seccomp_filtering) {
1833 if (nprocs && (!argc || debug_flag))
1834 error_msg("--seccomp-bpf is not enabled for processes"
1835 " attached with -p");
1837 error_msg("--seccomp-bpf implies -f");
1844 error_msg("deprecated option -F ignored");
1846 error_msg("option -F is deprecated, "
1847 "please use -f instead");
1852 if (followfork >= 2 && cflag) {
1853 error_msg_and_help("(-c or -C) and -ff are mutually exclusive");
1856 if (count_wallclock && !cflag) {
1857 error_msg_and_help("-w must be given with (-c or -C)");
1860 if (cflag == CFLAG_ONLY_STATS) {
1862 error_msg("-%c has no effect with -c", 'i');
1863 if (stack_trace_enabled)
1864 error_msg("-%c has no effect with -c", 'k');
1866 error_msg("-%c has no effect with -c", 'r');
1868 error_msg("-%c has no effect with -c", 't');
1870 error_msg("-%c has no effect with -c", 'T');
1872 error_msg("-%c has no effect with -c", 'y');
1875 #ifndef HAVE_OPEN_MEMSTREAM
1876 if (!is_complete_set(status_set, NUMBER_OF_STATUSES))
1877 error_msg_and_help("open_memstream is required to use -z, -Z, or -e status");
1881 error_msg("Only the last of -z/-Z options will take effect. "
1882 "See status qualifier for more complex filters.");
1884 acolumn_spaces = xmalloc(acolumn + 1);
1885 memset(acolumn_spaces, ' ', acolumn);
1886 acolumn_spaces[acolumn] = '\0';
1888 set_sighandler(SIGCHLD, SIG_DFL, ¶ms_for_tracee.child_sa);
1890 #ifdef ENABLE_STACKTRACE
1891 if (stack_trace_enabled)
1895 /* See if they want to run as another user. */
1896 if (username != NULL) {
1897 struct passwd *pent;
1899 if (getuid() != 0 || geteuid() != 0) {
1900 error_msg_and_die("You must be root to use the -u option");
1902 pent = getpwnam(username);
1904 error_msg_and_die("Cannot find user '%s'", username);
1906 run_uid = pent->pw_uid;
1907 run_gid = pent->pw_gid;
1914 ptrace_setoptions |= PTRACE_O_TRACECLONE |
1915 PTRACE_O_TRACEFORK |
1916 PTRACE_O_TRACEVFORK;
1918 if (seccomp_filtering)
1919 check_seccomp_filter();
1920 if (seccomp_filtering)
1921 ptrace_setoptions |= PTRACE_O_TRACESECCOMP;
1923 debug_msg("ptrace_setoptions = %#x", ptrace_setoptions);
1924 test_ptrace_seize();
1925 test_ptrace_get_syscall_info();
1928 * Is something weird with our stdin and/or stdout -
1929 * for example, may they be not open? In this case,
1930 * ensure that none of the future opens uses them.
1932 * This was seen in the wild when /proc/sys/kernel/core_pattern
1933 * was set to "|/bin/strace -o/tmp/LOG PROG":
1934 * kernel runs coredump helper with fd#0 open but fd#1 closed (!),
1935 * therefore LOG gets opened to fd#1, and fd#1 is closed by
1936 * "don't hold up stdin/out open" code soon after.
1938 ensure_standard_fds_opened();
1940 /* Check if they want to redirect the output. */
1942 /* See if they want to pipe the output. */
1943 if (outfname[0] == '|' || outfname[0] == '!') {
1945 * We can't do the <outfname>.PID funny business
1946 * when using popen, so prohibit it.
1948 if (followfork >= 2)
1949 error_msg_and_help("piping the output and -ff "
1950 "are mutually exclusive");
1951 shared_log = strace_popen(outfname + 1);
1952 } else if (followfork < 2) {
1953 shared_log = strace_fopen(outfname);
1954 } else if (strlen(outfname) >= PATH_MAX - sizeof(int) * 3) {
1955 errno = ENAMETOOLONG;
1956 perror_msg_and_die("%s", outfname);
1959 /* -ff without -o FILE is the same as single -f */
1960 if (followfork >= 2)
1964 if (!outfname || outfname[0] == '|' || outfname[0] == '!') {
1965 setvbuf(shared_log, NULL, _IOLBF, 0);
1969 * argv[0] -pPID -oFILE Default interactive setting
1970 * yes * 0 INTR_WHILE_WAIT
1971 * no 1 0 INTR_WHILE_WAIT
1972 * yes * 1 INTR_NEVER
1973 * no 1 1 INTR_WHILE_WAIT
1976 if (daemonized_tracer && !opt_intr)
1977 opt_intr = INTR_BLOCK_TSTP_TOO;
1978 if (outfname && argc) {
1980 opt_intr = INTR_NEVER;
1985 opt_intr = INTR_WHILE_WAIT;
1988 * startup_child() must be called before the signal handlers get
1989 * installed below as they are inherited into the spawned process.
1990 * Also we do not need to be protected by them as during interruption
1991 * in the startup_child() mode we kill the spawned process anyway.
1994 startup_child(argv);
1997 set_sighandler(SIGTTOU, SIG_IGN, NULL);
1998 set_sighandler(SIGTTIN, SIG_IGN, NULL);
1999 if (opt_intr != INTR_ANYWHERE) {
2000 if (opt_intr == INTR_BLOCK_TSTP_TOO)
2001 set_sighandler(SIGTSTP, SIG_IGN, NULL);
2003 * In interactive mode (if no -o OUTFILE, or -p PID is used),
2004 * fatal signals are handled asynchronously and acted
2005 * when waiting for process state changes.
2006 * In non-interactive mode these signals are ignored.
2008 set_sighandler(SIGHUP, interactive ? interrupt : SIG_IGN, NULL);
2009 set_sighandler(SIGINT, interactive ? interrupt : SIG_IGN, NULL);
2010 set_sighandler(SIGQUIT, interactive ? interrupt : SIG_IGN, NULL);
2011 set_sighandler(SIGPIPE, interactive ? interrupt : SIG_IGN, NULL);
2012 set_sighandler(SIGTERM, interactive ? interrupt : SIG_IGN, NULL);
2015 sigemptyset(&timer_set);
2016 sigaddset(&timer_set, SIGALRM);
2017 sigprocmask(SIG_BLOCK, &timer_set, NULL);
2018 set_sighandler(SIGALRM, timer_sighandler, NULL);
2020 if (nprocs != 0 || daemonized_tracer)
2023 /* Do we want pids printed in our -o OUTFILE?
2024 * -ff: no (every pid has its own file); or
2025 * -f: yes (there can be more pids in the future); or
2026 * -p PID1,PID2: yes (there are already more than one pid)
2028 print_pid_pfx = (outfname && followfork < 2 && (followfork == 1 || nprocs > 1));
2032 pid2tcb(const int pid)
2037 #define PID2TCB_CACHE_SIZE 1024U
2038 #define PID2TCB_CACHE_MASK (PID2TCB_CACHE_SIZE - 1)
2040 static struct tcb *pid2tcb_cache[PID2TCB_CACHE_SIZE];
2041 struct tcb **const ptcp = &pid2tcb_cache[pid & PID2TCB_CACHE_MASK];
2042 struct tcb *tcp = *ptcp;
2044 if (tcp && tcp->pid == pid)
2047 for (unsigned int i = 0; i < tcbtabsize; ++i) {
2049 if (tcp->pid == pid)
2057 cleanup(int fatal_sig)
2063 fatal_sig = SIGTERM;
2065 for (i = 0; i < tcbtabsize; i++) {
2069 debug_func_msg("looking at pid %u", tcp->pid);
2070 if (tcp->pid == strace_child) {
2071 kill(tcp->pid, SIGCONT);
2072 kill(tcp->pid, fatal_sig);
2085 print_debug_info(const int pid, int status)
2087 const unsigned int event = (unsigned int) status >> 16;
2088 char buf[sizeof("WIFEXITED,exitcode=%u") + sizeof(int)*3 /*paranoia:*/ + 16];
2089 char evbuf[sizeof(",EVENT_VFORK_DONE (%u)") + sizeof(int)*3 /*paranoia:*/ + 16];
2092 if (WIFSIGNALED(status))
2093 xsprintf(buf, "WIFSIGNALED,%ssig=%s",
2094 WCOREDUMP(status) ? "core," : "",
2095 sprintsigname(WTERMSIG(status)));
2096 if (WIFEXITED(status))
2097 xsprintf(buf, "WIFEXITED,exitcode=%u", WEXITSTATUS(status));
2098 if (WIFSTOPPED(status))
2099 xsprintf(buf, "WIFSTOPPED,sig=%s",
2100 sprintsigname(WSTOPSIG(status)));
2103 static const char *const event_names[] = {
2104 [PTRACE_EVENT_CLONE] = "CLONE",
2105 [PTRACE_EVENT_FORK] = "FORK",
2106 [PTRACE_EVENT_VFORK] = "VFORK",
2107 [PTRACE_EVENT_VFORK_DONE] = "VFORK_DONE",
2108 [PTRACE_EVENT_EXEC] = "EXEC",
2109 [PTRACE_EVENT_EXIT] = "EXIT",
2110 [PTRACE_EVENT_SECCOMP] = "SECCOMP",
2111 /* [PTRACE_EVENT_STOP (=128)] would make biggish array */
2113 const char *e = "??";
2114 if (event < ARRAY_SIZE(event_names))
2115 e = event_names[event];
2116 else if (event == PTRACE_EVENT_STOP)
2118 xsprintf(evbuf, ",EVENT_%s (%u)", e, event);
2120 error_msg("[wait(0x%06x) = %u] %s%s", status, pid, buf, evbuf);
2124 maybe_allocate_tcb(const int pid, int status)
2126 if (!WIFSTOPPED(status)) {
2127 if (detach_on_execve && pid == strace_child) {
2128 /* example: strace -bexecve sh -c 'exec true' */
2133 * This can happen if we inherited an unknown child.
2134 * Example: (sleep 1 & exec strace true)
2136 error_msg("Exit of unknown pid %u ignored", pid);
2140 /* We assume it's a fork/vfork/clone child */
2141 struct tcb *tcp = alloctcb(pid);
2142 after_successful_attach(tcp, post_attach_sigstop);
2144 error_msg("Process %d attached", pid);
2148 * This can happen if a clone call misused CLONE_PTRACE itself.
2150 * There used to be a dance around possible re-injection of
2151 * WSTOPSIG(status), but it was later removed as the only
2152 * observable stop here is the initial ptrace-stop.
2154 ptrace(PTRACE_DETACH, pid, NULL, 0L);
2155 error_msg("Detached unknown pid %d", pid);
2161 * Under Linux, execve changes pid to thread leader's pid, and we see this
2162 * changed pid on EVENT_EXEC and later, execve sysexit. Leader "disappears"
2163 * without exit notification. Let user know that, drop leader's tcb, and fix
2164 * up pid in execve thread's tcb. Effectively, execve thread's tcb replaces
2167 * BTW, leader is 'stuck undead' (doesn't report WIFEXITED on exit syscall)
2168 * in multi-threaded programs exactly in order to handle this case.
2171 maybe_switch_tcbs(struct tcb *tcp, const int pid)
2174 * PTRACE_GETEVENTMSG returns old pid starting from Linux 3.0.
2175 * On 2.6 and earlier it can return garbage.
2177 if (os_release < KERNEL_VERSION(3, 0, 0))
2180 const long old_pid = tcb_wait_tab[tcp->wait_data_idx].msg;
2182 /* Avoid truncation in pid2tcb() param passing */
2183 if (old_pid <= 0 || old_pid == pid)
2185 if ((unsigned long) old_pid > UINT_MAX)
2187 struct tcb *execve_thread = pid2tcb(old_pid);
2188 /* It should be !NULL, but I feel paranoid */
2192 if (execve_thread->curcol != 0) {
2194 * One case we are here is -ff, try
2195 * "strace -oLOG -ff test/threaded_execve".
2196 * Another case is demonstrated by
2197 * tests/maybe_switch_current_tcp.c
2199 fprintf(execve_thread->outf, " <pid changed to %d ...>\n", pid);
2200 /*execve_thread->curcol = 0; - no need, see code below */
2202 /* Swap output FILEs and memstream (needed for -ff) */
2203 FILE *fp = execve_thread->outf;
2204 execve_thread->outf = tcp->outf;
2206 if (execve_thread->staged_output_data || tcp->staged_output_data) {
2207 struct staged_output_data *staged_output_data;
2209 staged_output_data = execve_thread->staged_output_data;
2210 execve_thread->staged_output_data = tcp->staged_output_data;
2211 tcp->staged_output_data = staged_output_data;
2214 /* And their column positions */
2215 execve_thread->curcol = tcp->curcol;
2217 /* Drop leader, but close execve'd thread outfile (if -ff) */
2219 /* Switch to the thread, reusing leader's outfile and pid */
2220 tcp = execve_thread;
2222 if (cflag != CFLAG_ONLY_STATS) {
2224 tprintf("+++ superseded by execve in pid %lu +++\n", old_pid);
2227 * Need to reopen memstream for thread
2228 * as we closed it in droptcb.
2230 if (!is_complete_set(status_set, NUMBER_OF_STATUSES))
2231 strace_open_memstream(tcp);
2232 tcp->flags |= TCB_REPRINT;
2239 maybe_switch_current_tcp(void)
2241 struct tcb *tcp = maybe_switch_tcbs(current_tcp, current_tcp->pid);
2244 set_current_tcp(tcp);
2250 print_signalled(struct tcb *tcp, const int pid, int status)
2252 if (pid == strace_child) {
2253 exit_code = 0x100 | WTERMSIG(status);
2257 if (cflag != CFLAG_ONLY_STATS
2258 && is_number_in_set(WTERMSIG(status), signal_set)) {
2260 tprintf("+++ killed by %s %s+++\n",
2261 sprintsigname(WTERMSIG(status)),
2262 WCOREDUMP(status) ? "(core dumped) " : "");
2268 print_exited(struct tcb *tcp, const int pid, int status)
2270 if (pid == strace_child) {
2271 exit_code = WEXITSTATUS(status);
2275 if (cflag != CFLAG_ONLY_STATS &&
2278 tprintf("+++ exited with %d +++\n", WEXITSTATUS(status));
2284 print_stopped(struct tcb *tcp, const siginfo_t *si, const unsigned int sig)
2286 if (cflag != CFLAG_ONLY_STATS
2288 && is_number_in_set(sig, signal_set)) {
2291 tprintf("--- %s ", sprintsigname(sig));
2295 tprintf("--- stopped by %s ---\n", sprintsigname(sig));
2298 #ifdef ENABLE_STACKTRACE
2299 if (stack_trace_enabled)
2300 unwind_tcb_print(tcp);
2306 startup_tcb(struct tcb *tcp)
2308 debug_msg("pid %d has TCB_STARTUP, initializing it", tcp->pid);
2310 tcp->flags &= ~TCB_STARTUP;
2313 debug_msg("setting opts 0x%x on pid %d",
2314 ptrace_setoptions, tcp->pid);
2315 if (ptrace(PTRACE_SETOPTIONS, tcp->pid, NULL, ptrace_setoptions) < 0) {
2316 if (errno != ESRCH) {
2317 /* Should never happen, really */
2318 perror_msg_and_die("PTRACE_SETOPTIONS");
2323 if ((tcp->flags & TCB_GRABBED) && (get_scno(tcp) == 1))
2324 tcp->s_prev_ent = tcp->s_ent;
2327 tcp->atime = tcp->stime;
2332 print_event_exit(struct tcb *tcp)
2334 if (entering(tcp) || filtered(tcp) || hide_log(tcp)
2335 || cflag == CFLAG_ONLY_STATS) {
2339 if (followfork < 2 && printing_tcp && printing_tcp != tcp
2340 && printing_tcp->curcol != 0) {
2341 set_current_tcp(printing_tcp);
2342 tprints(" <unfinished ...>\n");
2343 flush_tcp_output(printing_tcp);
2344 printing_tcp->curcol = 0;
2345 set_current_tcp(tcp);
2348 print_syscall_resume(tcp);
2350 if (!(tcp->sys_func_rval & RVAL_DECODED)) {
2352 * The decoder has probably decided to print something
2353 * on exiting syscall which is not going to happen.
2355 tprints(" <unfinished ...>");
2362 if (!is_complete_set(status_set, NUMBER_OF_STATUSES)) {
2363 bool publish = is_number_in_set(STATUS_UNFINISHED, status_set);
2364 strace_close_memstream(tcp, publish);
2370 trace_wait_data_size(struct tcb *tcp)
2372 return sizeof(struct tcb_wait_data);
2375 static struct tcb_wait_data *
2376 init_trace_wait_data(void *p)
2378 struct tcb_wait_data *wd = p;
2380 memset(wd, 0, sizeof(*wd));
2385 static struct tcb_wait_data *
2386 copy_trace_wait_data(const struct tcb_wait_data *wd)
2388 struct tcb_wait_data *new_wd = xmalloc(sizeof(*new_wd));
2390 memcpy(new_wd, wd, sizeof(*wd));
2396 free_trace_wait_data(struct tcb_wait_data *wd)
2402 tcb_wait_tab_check_size(const size_t size)
2404 while (size >= tcb_wait_tab_size) {
2405 tcb_wait_tab = xgrowarray(tcb_wait_tab,
2407 sizeof(tcb_wait_tab[0]));
2411 static const struct tcb_wait_data *
2417 invalidate_umove_cache();
2419 struct tcb *tcp = NULL;
2420 struct list_item *elem;
2422 static EMPTY_LIST(pending_tcps);
2423 /* Handle the queued tcbs before waiting for new events. */
2424 if (!list_is_empty(&pending_tcps))
2425 goto next_event_get_tcp;
2427 static struct tcb *extra_tcp;
2428 static size_t wait_extra_data_idx;
2429 /* Handle the extra tcb event. */
2433 tcp->wait_data_idx = wait_extra_data_idx;
2435 debug_msg("dequeued extra event for pid %u", tcp->pid);
2436 goto next_event_exit;
2440 * Used to exit simply when nprocs hits zero, but in this testcase:
2441 * int main(void) { _exit(!!fork()); }
2442 * under strace -f, parent sometimes (rarely) manages
2443 * to exit before we see the first stop of the child,
2444 * and we are losing track of it:
2445 * 19923 clone(...) = 19924
2446 * 19923 exit_group(1) = ?
2447 * 19923 +++ exited with 1 +++
2448 * Exiting only when wait() returns ECHILD works better.
2450 if (popen_pid != 0) {
2451 /* However, if -o|logger is in use, we can't do that.
2452 * Can work around that by double-forking the logger,
2453 * but that loses the ability to wait for its completion
2454 * on exit. Oh well...
2460 const bool unblock_delay_timer = is_delay_timer_armed();
2463 * The window of opportunity to handle expirations
2464 * of the delay timer opens here.
2466 * Unblock the signal handler for the delay timer
2467 * iff the delay timer is already created.
2469 if (unblock_delay_timer)
2470 sigprocmask(SIG_UNBLOCK, &timer_set, NULL);
2473 * If the delay timer has expired, then its expiration
2474 * has been handled already by the signal handler.
2476 * If the delay timer expires during wait4(),
2477 * then the system call will be interrupted and
2478 * the expiration will be handled by the signal handler.
2482 int pid = wait4(-1, &status, __WALL, (cflag ? &ru : NULL));
2483 int wait_errno = errno;
2486 * The window of opportunity to handle expirations
2487 * of the delay timer closes here.
2489 * Block the signal handler for the delay timer
2490 * iff it was unblocked earlier.
2492 if (unblock_delay_timer) {
2493 sigprocmask(SIG_BLOCK, &timer_set, NULL);
2499 size_t wait_tab_pos = 0;
2500 bool wait_nohang = false;
2503 * Wait for new events until wait4() returns 0 (meaning that there's
2504 * nothing more to wait for for now), or a second event for some tcb
2505 * appears (which may happen if a tracee was SIGKILL'ed, for example).
2508 struct tcb_wait_data *wd;
2511 if (wait_errno == EINTR)
2515 if (nprocs == 0 && wait_errno == ECHILD)
2518 * If nprocs > 0, ECHILD is not expected,
2519 * treat it as any other error here:
2522 perror_msg_and_die("wait4(__WALL)");
2528 if (pid == popen_pid) {
2529 if (!WIFSTOPPED(status))
2535 print_debug_info(pid, status);
2537 /* Look up 'pid' in our table. */
2541 tcp = maybe_allocate_tcb(pid, status);
2543 goto next_event_wait_next;
2547 tcp->stime.tv_sec = ru.ru_stime.tv_sec;
2548 tcp->stime.tv_nsec = ru.ru_stime.tv_usec * 1000;
2551 tcb_wait_tab_check_size(wait_tab_pos);
2553 /* Initialise a new wait data structure. */
2554 wd = tcb_wait_tab + wait_tab_pos;
2555 init_trace_wait_data(wd);
2556 wd->status = status;
2558 if (WIFSIGNALED(status)) {
2559 wd->te = TE_SIGNALLED;
2560 } else if (WIFEXITED(status)) {
2564 * As WCONTINUED flag has not been specified to wait4,
2565 * it cannot be WIFCONTINUED(status), so the only case
2566 * that remains is WIFSTOPPED(status).
2569 const unsigned int sig = WSTOPSIG(status);
2570 const unsigned int event = (unsigned int) status >> 16;
2575 * Is this post-attach SIGSTOP?
2576 * Interestingly, the process may stop
2577 * with STOPSIG equal to some other signal
2578 * than SIGSTOP if we happened to attach
2579 * just before the process takes a signal.
2581 if (sig == SIGSTOP &&
2582 (tcp->flags & TCB_IGNORE_ONE_SIGSTOP)) {
2583 debug_func_msg("ignored SIGSTOP on "
2584 "pid %d", tcp->pid);
2585 tcp->flags &= ~TCB_IGNORE_ONE_SIGSTOP;
2586 wd->te = TE_RESTART;
2587 } else if (sig == syscall_trap_sig) {
2588 wd->te = TE_SYSCALL_STOP;
2591 * True if tracee is stopped by signal
2592 * (as opposed to "tracee received
2594 * TODO: shouldn't we check for
2595 * errno == EINVAL too?
2596 * We can get ESRCH instead, you know...
2598 bool stopped = ptrace(PTRACE_GETSIGINFO,
2599 pid, 0, &wd->si) < 0;
2601 wd->te = stopped ? TE_GROUP_STOP
2602 : TE_SIGNAL_DELIVERY_STOP;
2605 case PTRACE_EVENT_STOP:
2607 * PTRACE_INTERRUPT-stop or group-stop.
2608 * PTRACE_INTERRUPT-stop has sig == SIGTRAP here.
2615 wd->te = TE_GROUP_STOP;
2618 wd->te = TE_RESTART;
2621 case PTRACE_EVENT_EXEC:
2623 * TODO: shouldn't we check for
2624 * errno == EINVAL here, too?
2625 * We can get ESRCH instead, you know...
2627 if (ptrace(PTRACE_GETEVENTMSG, pid, NULL,
2631 wd->te = TE_STOP_BEFORE_EXECVE;
2633 case PTRACE_EVENT_EXIT:
2634 wd->te = TE_STOP_BEFORE_EXIT;
2636 case PTRACE_EVENT_SECCOMP:
2637 wd->te = TE_SECCOMP;
2640 wd->te = TE_RESTART;
2645 error_func_msg("Tracing event hasn't been determined "
2646 "for pid %d, status %0#x", pid, status);
2648 if (!list_is_empty(&tcp->wait_list)) {
2649 wait_extra_data_idx = wait_tab_pos;
2651 debug_func_msg("queued extra pid %d", tcp->pid);
2653 tcp->wait_data_idx = wait_tab_pos;
2654 list_append(&pending_tcps, &tcp->wait_list);
2655 debug_func_msg("queued pid %d", tcp->pid);
2663 next_event_wait_next:
2664 pid = wait4(-1, &status, __WALL | WNOHANG, (cflag ? &ru : NULL));
2670 elem = list_remove_head(&pending_tcps);
2673 tcb_wait_tab_check_size(0);
2674 memset(tcb_wait_tab, 0, sizeof(*tcb_wait_tab));
2675 tcb_wait_tab->te = TE_NEXT;
2677 return tcb_wait_tab;
2679 tcp = list_elem(elem, struct tcb, wait_list);
2680 debug_func_msg("dequeued pid %d", tcp->pid);
2684 /* Is this the very first time we see this tracee stopped? */
2685 if (tcp->flags & TCB_STARTUP)
2690 /* Set current output file */
2691 set_current_tcp(tcp);
2693 return tcb_wait_tab + tcp->wait_data_idx;
2697 trace_syscall(struct tcb *tcp, unsigned int *sig)
2699 if (entering(tcp)) {
2700 int res = syscall_entering_decode(tcp);
2705 res = syscall_entering_trace(tcp, sig);
2707 syscall_entering_finish(tcp, res);
2710 struct timespec ts = {};
2711 int res = syscall_exiting_decode(tcp, &ts);
2713 res = syscall_exiting_trace(tcp, &ts, res);
2715 syscall_exiting_finish(tcp);
2720 /* Returns true iff the main trace loop has to continue. */
2722 dispatch_event(const struct tcb_wait_data *wd)
2724 unsigned int restart_op;
2725 unsigned int restart_sig = 0;
2726 enum trace_event te = wd ? wd->te : TE_BREAK;
2728 * Copy wd->status to a non-const variable to workaround glibc bugs
2729 * around union wait fixed by glibc commit glibc-2.24~391
2731 int status = wd ? wd->status : 0;
2733 if (current_tcp && has_seccomp_filter(current_tcp))
2734 restart_op = seccomp_filter_restart_operator(current_tcp);
2736 restart_op = PTRACE_SYSCALL;
2749 if (!has_seccomp_filter(current_tcp)) {
2751 * We don't know if forks/clones have a seccomp filter
2752 * when they are created, but we can detect it when we
2753 * have a seccomp-stop.
2754 * In such a case, if !seccomp_before_sysentry, we have
2755 * already processed the syscall entry, so we avoid
2756 * processing it a second time.
2758 current_tcp->flags |= TCB_SECCOMP_FILTER;
2759 restart_op = PTRACE_SYSCALL;
2763 if (seccomp_before_sysentry) {
2764 restart_op = PTRACE_SYSCALL;
2767 ATTRIBUTE_FALLTHROUGH;
2769 case TE_SYSCALL_STOP:
2770 if (trace_syscall(current_tcp, &restart_sig) < 0) {
2772 * ptrace() failed in trace_syscall().
2773 * Likely a result of process disappearing mid-flight.
2774 * Observed case: exit_group() or SIGKILL terminating
2775 * all processes in thread group.
2776 * We assume that ptrace error was caused by process death.
2777 * We used to detach(current_tcp) here, but since we no
2778 * longer implement "detach before death" policy/hack,
2779 * we can let this process to report its death to us
2780 * normally, via WIFEXITED or WIFSIGNALED wait status.
2784 if (has_seccomp_filter(current_tcp)) {
2786 * Syscall and seccomp stops can happen in different
2787 * orders depending on kernel. strace tests this in
2788 * check_seccomp_order_tracer().
2791 * (seccomp-stop before syscall-entry-stop)
2792 * +--> seccomp-stop ->-PTRACE_SYSCALL->-+
2794 * PTRACE_CONT syscall-entry-stop
2796 * syscall-exit-stop <---PTRACE_SYSCALL-----<----+
2799 * (seccomp-stop after syscall-entry-stop)
2800 * syscall-entry-stop
2802 * +---->-----PTRACE_CONT---->----+
2804 * syscall-exit-stop seccomp-stop
2806 * +----<----PTRACE_SYSCALL---<---+
2808 * Note in Linux 4.8+, we restart in PTRACE_CONT
2809 * after syscall-exit to skip the syscall-entry-stop.
2810 * The next seccomp-stop will be treated as a syscall
2813 * The line below implements this behavior.
2814 * Note that exiting(current_tcp) actually marks
2815 * a syscall-entry-stop because the flag was inverted
2816 * in the above call to trace_syscall.
2818 restart_op = exiting(current_tcp) ? PTRACE_SYSCALL : PTRACE_CONT;
2822 case TE_SIGNAL_DELIVERY_STOP:
2823 restart_sig = WSTOPSIG(status);
2824 print_stopped(current_tcp, &wd->si, restart_sig);
2828 print_signalled(current_tcp, current_tcp->pid, status);
2829 droptcb(current_tcp);
2833 restart_sig = WSTOPSIG(status);
2834 print_stopped(current_tcp, NULL, restart_sig);
2837 * This ends ptrace-stop, but does *not* end group-stop.
2838 * This makes stopping signals work properly on straced
2839 * process (that is, process really stops. It used to
2842 restart_op = PTRACE_LISTEN;
2848 print_exited(current_tcp, current_tcp->pid, status);
2849 droptcb(current_tcp);
2852 case TE_STOP_BEFORE_EXECVE:
2853 /* The syscall succeeded, clear the flag. */
2854 current_tcp->flags &= ~TCB_CHECK_EXEC_SYSCALL;
2856 * Check that we are inside syscall now (next event after
2857 * PTRACE_EVENT_EXEC should be for syscall exiting). If it is
2858 * not the case, we might have a situation when we attach to a
2859 * process and the first thing we see is a PTRACE_EVENT_EXEC
2860 * and all the following syscall state tracking is screwed up
2863 if (!maybe_switch_current_tcp() && entering(current_tcp)) {
2866 error_msg("Stray PTRACE_EVENT_EXEC from pid %d"
2867 ", trying to recover...",
2870 current_tcp->flags |= TCB_RECOVERING;
2871 ret = trace_syscall(current_tcp, &restart_sig);
2872 current_tcp->flags &= ~TCB_RECOVERING;
2875 /* The reason is described in TE_SYSCALL_STOP */
2880 if (detach_on_execve) {
2881 if (current_tcp->flags & TCB_SKIP_DETACH_ON_FIRST_EXEC) {
2882 current_tcp->flags &= ~TCB_SKIP_DETACH_ON_FIRST_EXEC;
2884 detach(current_tcp); /* do "-b execve" thingy */
2890 case TE_STOP_BEFORE_EXIT:
2891 print_event_exit(current_tcp);
2895 /* We handled quick cases, we are permitted to interrupt now. */
2899 /* If the process is being delayed, do not ptrace_restart just yet */
2900 if (syscall_delayed(current_tcp)) {
2901 if (current_tcp->delayed_wait_data)
2902 error_func_msg("pid %d has delayed wait data set"
2903 " already", current_tcp->pid);
2905 current_tcp->delayed_wait_data = copy_trace_wait_data(wd);
2910 if (ptrace_restart(restart_op, current_tcp, restart_sig) < 0) {
2911 /* Note: ptrace_restart emitted error message */
2919 restart_delayed_tcb(struct tcb *const tcp)
2921 struct tcb_wait_data *wd = tcp->delayed_wait_data;
2924 error_func_msg("No delayed wait data found for pid %d",
2926 wd = init_trace_wait_data(alloca(trace_wait_data_size(tcp)));
2929 wd->te = TE_RESTART;
2931 debug_func_msg("pid %d", tcp->pid);
2933 tcp->flags &= ~TCB_DELAYED;
2935 struct tcb *const prev_tcp = current_tcp;
2937 bool ret = dispatch_event(wd);
2938 current_tcp = prev_tcp;
2940 free_trace_wait_data(tcp->delayed_wait_data);
2941 tcp->delayed_wait_data = NULL;
2947 restart_delayed_tcbs(void)
2949 struct tcb *tcp_next = NULL;
2950 struct timespec ts_now;
2952 clock_gettime(CLOCK_MONOTONIC, &ts_now);
2954 for (size_t i = 0; i < tcbtabsize; i++) {
2955 struct tcb *tcp = tcbtab[i];
2957 if (tcp->pid && syscall_delayed(tcp)) {
2958 if (ts_cmp(&ts_now, &tcp->delay_expiration_time) > 0) {
2959 if (!restart_delayed_tcb(tcp))
2962 /* Check whether this tcb is the next. */
2964 ts_cmp(&tcp_next->delay_expiration_time,
2965 &tcp->delay_expiration_time) > 0) {
2973 arm_delay_timer(tcp_next);
2979 * As this signal handler does a lot of work that is not suitable
2980 * for signal handlers, extra care must be taken to ensure that
2981 * it is enabled only in those places where it's safe.
2984 timer_sighandler(int sig)
2986 delay_timer_expired();
2991 int saved_errno = errno;
2993 if (!restart_delayed_tcbs())
2996 errno = saved_errno;
2999 #ifdef ENABLE_COVERAGE_GCOV
3000 extern void __gcov_flush(void);
3003 static void ATTRIBUTE_NORETURN
3006 int sig = interrupted;
3010 call_summary(shared_log);
3012 if (shared_log != stderr)
3015 while (waitpid(popen_pid, NULL, 0) < 0 && errno == EINTR)
3019 exit_code = 0x100 | sig;
3021 if (exit_code > 0xff) {
3022 /* Avoid potential core file clobbering. */
3023 struct_rlimit rlim = {0, 0};
3024 set_rlimit(RLIMIT_CORE, &rlim);
3026 /* Child was killed by a signal, mimic that. */
3028 signal(exit_code, SIG_DFL);
3029 #ifdef ENABLE_COVERAGE_GCOV
3034 /* Unblock the signal. */
3037 sigaddset(&mask, exit_code);
3038 #ifdef ENABLE_COVERAGE_GCOV
3041 sigprocmask(SIG_UNBLOCK, &mask, NULL);
3043 /* Paranoia - what if this signal is not fatal?
3044 Exit with 128 + signo then. */
3051 main(int argc, char *argv[])
3053 setlocale(LC_ALL, "");
3056 exit_code = !nprocs;
3058 while (dispatch_event(next_event()))