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)
97 * daemonized_tracer supports -D option.
98 * With this option, strace forks twice.
99 * Unlike normal case, with -D *grandparent* process exec's,
100 * becoming a traced process. Child exits (this prevents traced process
101 * from having children it doesn't expect to have), and grandchild
102 * attaches to grandparent similarly to strace -p PID.
103 * This allows for more transparent interaction in cases
104 * when process and its parent are communicating via signals,
105 * wait() etc. Without -D, strace process gets lodged in between,
106 * disrupting parent<->child link.
108 static bool daemonized_tracer;
110 static int post_attach_sigstop = TCB_IGNORE_ONE_SIGSTOP;
111 #define use_seize (post_attach_sigstop == 0)
113 /* Show path associated with fd arguments */
114 unsigned int show_fd_path;
116 static bool detach_on_execve;
118 static int exit_code;
119 static int strace_child;
120 static int strace_tracer_pid;
122 static const char *username;
123 static uid_t run_uid;
124 static gid_t run_gid;
126 unsigned int max_strlen = DEFAULT_STRLEN;
127 static int acolumn = DEFAULT_ACOLUMN;
128 static char *acolumn_spaces;
130 /* Default output style for xlat entities */
131 enum xlat_style xlat_verbosity = XLAT_STYLE_ABBREV;
133 static const char *outfname;
134 /* If -ff, points to stderr. Else, it's our common output log */
135 static FILE *shared_log;
136 static bool open_append;
138 struct tcb *printing_tcp;
139 static struct tcb *current_tcp;
141 struct tcb_wait_data {
142 enum trace_event te; /**< Event passed to dispatch_event() */
143 int status; /**< status, returned by wait4() */
144 unsigned long msg; /**< Value returned by PTRACE_GETEVENTMSG */
145 siginfo_t si; /**< siginfo, returned by PTRACE_GETSIGINFO */
148 static struct tcb **tcbtab;
149 static unsigned int nprocs;
150 static size_t tcbtabsize;
152 static struct tcb_wait_data *tcb_wait_tab;
153 static size_t tcb_wait_tab_size;
156 #ifndef HAVE_PROGRAM_INVOCATION_NAME
157 char *program_invocation_name;
160 unsigned os_release; /* generated from uname()'s u.release */
162 static void detach(struct tcb *tcp);
163 static void cleanup(int sig);
164 static void interrupt(int sig);
166 #ifdef HAVE_SIG_ATOMIC_T
167 static volatile sig_atomic_t interrupted, restart_failed;
169 static volatile int interrupted, restart_failed;
172 static sigset_t timer_set;
173 static void timer_sighandler(int);
175 #ifndef HAVE_STRERROR
177 # if !HAVE_DECL_SYS_ERRLIST
179 extern char *sys_errlist[];
185 static char buf[sizeof("Unknown error %d") + sizeof(int)*3];
187 if (err_no < 1 || err_no >= sys_nerr) {
188 xsprintf(buf, "Unknown error %d", err_no);
191 return sys_errlist[err_no];
194 #endif /* HAVE_STERRROR */
199 static const char features[] =
200 #ifdef ENABLE_STACKTRACE
201 " stack-trace=" USE_UNWINDER
206 #if SUPPORTED_PERSONALITIES > 1
207 # if defined HAVE_M32_MPERS
212 #endif /* SUPPORTED_PERSONALITIES > 1 */
213 #if SUPPORTED_PERSONALITIES > 2
214 # if defined HAVE_MX32_MPERS
219 #endif /* SUPPORTED_PERSONALITIES > 2 */
222 printf("%s -- version %s\n"
223 "Copyright (c) 1991-%s The strace developers <%s>.\n"
224 "This is free software; see the source for copying conditions. There is NO\n"
225 "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n",
226 PACKAGE_NAME, PACKAGE_VERSION, COPYRIGHT_YEAR, PACKAGE_URL);
227 printf("\nOptional features enabled:%s\n",
228 features[0] ? features : " (none)");
234 #ifdef ENABLE_STACKTRACE
241 usage: strace [-ACdffhi" K_OPT "qqrtttTvVwxxyyzZ] [-I n] [-b execve] [-e expr]...\n\
242 [-a column] [-o file] [-s strsize] [-X format] [-P path]...\n\
243 [-p pid]... [--seccomp-bpf]\n\
244 { -p pid | [-D] [-E var=val]... [-u username] PROG [ARGS] }\n\
245 or: strace -c[dfwzZ] [-I n] [-b execve] [-e expr]... [-O overhead]\n\
246 [-S sortby] [-P path]... [-p pid]... [--seccomp-bpf]\n\
247 { -p pid | [-D] [-E var=val]... [-u username] PROG [ARGS] }\n\
250 -A open the file provided in the -o option in append mode\n\
251 -a column alignment COLUMN for printing syscall results (default %d)\n\
252 -i print instruction pointer at time of syscall\n\
254 #ifdef ENABLE_STACKTRACE
256 -k obtain stack trace between each syscall\n\
260 -o file send trace output to FILE instead of stderr\n\
261 -q suppress messages about attaching, detaching, etc.\n\
262 -qq suppress messages about process exit status as well.\n\
263 -r print relative timestamp\n\
264 -s strsize limit length of print strings to STRSIZE chars (default %d)\n\
265 -t print absolute timestamp\n\
266 -tt print absolute timestamp with usecs\n\
267 -T print time spent in each syscall\n\
268 -v verbose mode: print entities unabbreviated\n\
269 -x print non-ascii strings in hex\n\
270 -xx print all strings in hex\n\
271 -X format set the format for printing of named constants and flags\n\
272 -y print paths associated with file descriptor arguments\n\
273 -yy print protocol specific information associated with socket\n\
277 -c count time, calls, and errors for each syscall and report\n\
279 -C like -c but also print regular output\n\
280 -O overhead set overhead for tracing syscalls to OVERHEAD usecs\n\
281 -S sortby sort syscall counts by: time, calls, errors, name, nothing\n\
283 -w summarise syscall latency (default is system time)\n\
286 -e expr a qualifying expression: option=[!]all or option=[!]val1[,val2]...\n\
287 options: trace, abbrev, verbose, raw, signal, read, write, fault,\n\
288 inject, status, kvm\n\
289 -P path trace accesses to path\n\
290 -z print only syscalls that returned without an error code\n\
291 -Z print only syscalls that returned with an error code\n\
294 -b execve detach on execve syscall\n\
295 -D run tracer process as a detached grandchild, not as parent\n\
297 -ff follow forks with output into separate files\n\
299 1: no signals are blocked\n\
300 2: fatal signals are blocked while decoding syscall (default)\n\
301 3: fatal signals are always blocked (default if '-o FILE PROG')\n\
302 4: fatal signals and SIGTSTP (^Z) are always blocked\n\
303 (useful to make 'strace -o FILE PROG' not stop on ^Z)\n\
306 -E var remove var from the environment for command\n\
307 -E var=val put var=val in the environment for command\n\
308 -p pid trace process with process id PID, may be repeated\n\
309 -u username run command as username handling setuid and/or setgid\n\
312 --seccomp-bpf enable seccomp-bpf filtering\n\
313 -d enable debug output to stderr\n\
314 -h, --help print help message\n\
315 -V, --version print version\n\
317 /* ancient, no one should use it
318 -F -- attempt to follow vforks (deprecated, use -f)\n\
320 , DEFAULT_ACOLUMN, DEFAULT_STRLEN, DEFAULT_SORTBY);
326 void ATTRIBUTE_NORETURN
329 if (strace_tracer_pid == getpid()) {
338 error_opt_arg(int opt, const char *arg)
340 error_msg_and_help("invalid -%c argument: '%s'", opt, arg);
343 static const char *ptrace_attach_cmd;
346 ptrace_attach_or_seize(int pid)
350 return ptrace_attach_cmd = "PTRACE_ATTACH",
351 ptrace(PTRACE_ATTACH, pid, 0L, 0L);
352 r = ptrace(PTRACE_SEIZE, pid, 0L, (unsigned long) ptrace_setoptions);
354 return ptrace_attach_cmd = "PTRACE_SEIZE", r;
355 r = ptrace(PTRACE_INTERRUPT, pid, 0L, 0L);
356 return ptrace_attach_cmd = "PTRACE_INTERRUPT", r;
360 ptrace_op_str(unsigned int op)
362 const char *str = xlookup(ptrace_cmds, op);
366 static char buf[sizeof(op) * 3];
367 xsprintf(buf, "%u", op);
372 * Used when we want to unblock stopped traced process.
373 * Should be only used with PTRACE_CONT, PTRACE_DETACH and PTRACE_SYSCALL.
374 * Returns 0 on success or if error was ESRCH
375 * (presumably process was killed while we talk to it).
376 * Otherwise prints error message and returns -1.
379 ptrace_restart(const unsigned int op, struct tcb *const tcp, unsigned int sig)
384 ptrace(op, tcp->pid, 0L, (unsigned long) sig);
386 if (!err || err == ESRCH)
390 * Why curcol != 0? Otherwise sometimes we get this:
392 * 10252 kill(10253, SIGKILL) = 0
393 * <ptrace(SYSCALL,10252):No such process>10253 ...next decode...
395 * 10252 died after we retrieved syscall exit data,
396 * but before we tried to restart it. Log looks ugly.
398 if (current_tcp && current_tcp->curcol != 0) {
399 tprintf(" <Cannot restart pid %d with ptrace(%s): %s>\n",
400 tcp->pid, ptrace_op_str(op), strerror(err));
404 perror_msg("ptrace(%s,pid:%d,sig:%u)",
405 ptrace_op_str(op), tcp->pid, sig);
410 set_cloexec_flag(int fd)
414 flags = fcntl(fd, F_GETFD);
416 /* Can happen only if fd is bad.
417 * Should never happen: if it does, we have a bug
418 * in the caller. Therefore we just abort
419 * instead of propagating the error.
421 perror_msg_and_die("fcntl(%d, F_GETFD)", fd);
424 newflags = flags | FD_CLOEXEC;
425 if (flags == newflags)
428 if (fcntl(fd, F_SETFD, newflags)) /* never fails */
429 perror_msg_and_die("fcntl(%d, F_SETFD, %#x)", fd, newflags);
433 * When strace is setuid executable, we have to swap uids
434 * before and after filesystem and process management operations.
439 int euid = geteuid(), uid = getuid();
441 if (euid != uid && setreuid(euid, uid) < 0) {
442 perror_msg_and_die("setreuid");
447 strace_fopen(const char *path)
452 fp = fopen_stream(path, open_append ? "a" : "w");
454 perror_msg_and_die("Can't fopen '%s'", path);
456 set_cloexec_flag(fileno(fp));
460 static int popen_pid;
463 # define _PATH_BSHELL "/bin/sh"
467 * We cannot use standard popen(3) here because we have to distinguish
468 * popen child process from other processes we trace, and standard popen(3)
469 * does not export its child's pid.
472 strace_popen(const char *command)
480 perror_msg_and_die("pipe");
482 set_cloexec_flag(fds[1]); /* never fails */
486 perror_msg_and_die("vfork");
493 perror_msg_and_die("dup2");
496 execl(_PATH_BSHELL, "sh", "-c", command, NULL);
497 perror_msg_and_die("Can't execute '%s'", _PATH_BSHELL);
504 fp = fdopen(fds[1], "w");
506 perror_msg_and_die("fdopen");
511 outf_perror(const struct tcb * const tcp)
513 if (tcp->outf == stderr)
516 /* This is ugly, but we don't store separate file names */
518 perror_msg("%s.%u", outfname, tcp->pid);
520 perror_msg("%s", outfname);
523 ATTRIBUTE_FORMAT((printf, 1, 0))
525 tvprintf(const char *const fmt, va_list args)
528 int n = vfprintf(current_tcp->outf, fmt, args);
530 /* very unlikely due to vfprintf buffering */
531 outf_perror(current_tcp);
533 current_tcp->curcol += n;
538 tprintf(const char *fmt, ...)
546 #ifndef HAVE_FPUTS_UNLOCKED
547 # define fputs_unlocked fputs
551 tprints(const char *str)
554 int n = fputs_unlocked(str, current_tcp->outf);
556 current_tcp->curcol += strlen(str);
559 /* very unlikely due to fputs_unlocked buffering */
560 outf_perror(current_tcp);
565 tprints_comment(const char *const str)
568 tprintf(" /* %s */", str);
572 tprintf_comment(const char *fmt, ...)
586 flush_tcp_output(const struct tcb *const tcp)
588 if (fflush(tcp->outf))
596 current_tcp->curcol = 0;
597 flush_tcp_output(current_tcp);
600 printing_tcp->curcol = 0;
606 set_current_tcp(const struct tcb *tcp)
608 current_tcp = (struct tcb *) tcp;
610 /* Sync current_personality and stuff */
612 set_personality(current_tcp->currpers);
616 printleader(struct tcb *tcp)
618 /* If -ff, "previous tcb we printed" is always the same as current,
619 * because we have per-tcb output files.
625 set_current_tcp(printing_tcp);
626 if (!tcp->staged_output_data && printing_tcp->curcol != 0 &&
627 (followfork < 2 || printing_tcp == tcp)) {
629 * case 1: we have a shared log (i.e. not -ff), and last line
630 * wasn't finished (same or different tcb, doesn't matter).
631 * case 2: split log, we are the same tcb, but our last line
632 * didn't finish ("SIGKILL nuked us after syscall entry" etc).
634 tprints(" <unfinished ...>\n");
635 printing_tcp->curcol = 0;
640 set_current_tcp(tcp);
641 current_tcp->curcol = 0;
644 tprintf("%-5d ", tcp->pid);
645 else if (nprocs > 1 && !outfname)
646 tprintf("[pid %5u] ", tcp->pid);
650 clock_gettime(CLOCK_REALTIME, &ts);
653 tprintf("%lld.%06ld ",
654 (long long) ts.tv_sec, (long) ts.tv_nsec / 1000);
656 time_t local = ts.tv_sec;
657 char str[MAX(sizeof("HH:MM:SS"), sizeof(ts.tv_sec) * 3)];
658 struct tm *tm = localtime(&local);
661 strftime(str, sizeof(str), "%T", tm);
663 xsprintf(str, "%lld", (long long) local);
666 str, (long) ts.tv_nsec / 1000);
674 clock_gettime(CLOCK_MONOTONIC, &ts);
676 static struct timespec ots;
681 ts_sub(&dts, &ts, &ots);
684 tprintf("%s%6ld.%06ld%s ",
686 (long) dts.tv_sec, (long) dts.tv_nsec / 1000,
691 print_instruction_pointer(tcp);
697 if (current_tcp->curcol < acolumn)
698 tprints(acolumn_spaces + current_tcp->curcol);
701 /* Should be only called directly *after successful attach* to a tracee.
702 * Otherwise, "strace -oFILE -ff -p<nonexistant_pid>"
703 * may create bogus empty FILE.<nonexistant_pid>, and then die.
706 after_successful_attach(struct tcb *tcp, const unsigned int flags)
708 tcp->flags |= TCB_ATTACHED | TCB_STARTUP | flags;
709 tcp->outf = shared_log; /* if not -ff mode, the same file is for all */
710 if (followfork >= 2) {
712 xsprintf(name, "%s.%u", outfname, tcp->pid);
713 tcp->outf = strace_fopen(name);
716 #ifdef ENABLE_STACKTRACE
717 if (stack_trace_enabled)
718 unwind_tcb_init(tcp);
725 /* Allocate some (more) TCBs (and expand the table).
726 We don't want to relocate the TCBs because our
727 callers have pointers and it would be a pain.
728 So tcbtab is a table of pointers. Since we never
729 free the TCBs, we allocate a single chunk of many. */
730 size_t old_tcbtabsize;
732 struct tcb **tcb_ptr;
734 old_tcbtabsize = tcbtabsize;
736 tcbtab = xgrowarray(tcbtab, &tcbtabsize, sizeof(tcbtab[0]));
737 newtcbs = xcalloc(tcbtabsize - old_tcbtabsize, sizeof(newtcbs[0]));
739 for (tcb_ptr = tcbtab + old_tcbtabsize;
740 tcb_ptr < tcbtab + tcbtabsize; tcb_ptr++, newtcbs++)
750 if (nprocs == tcbtabsize)
753 for (i = 0; i < tcbtabsize; i++) {
756 memset(tcp, 0, sizeof(*tcp));
757 list_init(&tcp->wait_list);
759 #if SUPPORTED_PERSONALITIES > 1
760 tcp->currpers = current_personality;
763 debug_msg("new tcb for pid %d, active tcbs:%d",
768 error_msg_and_die("bug in alloctcb");
772 get_tcb_priv_data(const struct tcb *tcp)
774 return tcp->_priv_data;
778 set_tcb_priv_data(struct tcb *tcp, void *const priv_data,
779 void (*const free_priv_data)(void *))
784 tcp->_free_priv_data = free_priv_data;
785 tcp->_priv_data = priv_data;
791 free_tcb_priv_data(struct tcb *tcp)
793 if (tcp->_priv_data) {
794 if (tcp->_free_priv_data) {
795 tcp->_free_priv_data(tcp->_priv_data);
796 tcp->_free_priv_data = NULL;
798 tcp->_priv_data = NULL;
803 droptcb(struct tcb *tcp)
808 if (cflag && debug_flag) {
811 ts_sub(&dt, &tcp->stime, &tcp->atime);
812 debug_func_msg("pid %d: %.9f seconds of system time spent "
813 "since attach", tcp->pid, ts_float(&dt));
817 for (p = 0; p < SUPPORTED_PERSONALITIES; ++p)
818 free(tcp->inject_vec[p]);
820 free_tcb_priv_data(tcp);
822 #ifdef ENABLE_STACKTRACE
823 if (stack_trace_enabled)
827 #ifdef HAVE_LINUX_KVM_H
828 kvm_vcpu_info_free(tcp);
832 tcp->mmap_cache->free_fn(tcp, __func__);
835 debug_msg("dropped tcb for pid %d, %d remain", tcp->pid, nprocs);
839 if (!is_complete_set(status_set, NUMBER_OF_STATUSES)) {
840 publish = is_number_in_set(STATUS_DETACHED, status_set);
841 strace_close_memstream(tcp, publish);
844 if (followfork >= 2) {
845 if (tcp->curcol != 0 && publish)
846 fprintf(tcp->outf, " <detached ...>\n");
849 if (printing_tcp == tcp && tcp->curcol != 0 && publish)
850 fprintf(tcp->outf, " <detached ...>\n");
851 flush_tcp_output(tcp);
855 if (current_tcp == tcp)
856 set_current_tcp(NULL);
857 if (printing_tcp == tcp)
860 list_remove(&tcp->wait_list);
862 memset(tcp, 0, sizeof(*tcp));
865 /* Detach traced process.
866 * Never call DETACH twice on the same process as both unattached and
867 * attached-unstopped processes give the same ESRCH. For unattached process we
868 * would SIGSTOP it and wait for its SIGSTOP notification forever.
871 detach(struct tcb *tcp)
877 * Linux wrongly insists the child be stopped
878 * before detaching. Arghh. We go through hoops
879 * to make a clean break of things.
882 if (!(tcp->flags & TCB_ATTACHED))
885 /* We attached but possibly didn't see the expected SIGSTOP.
886 * We must catch exactly one as otherwise the detached process
887 * would be left stopped (process state T).
889 if (tcp->flags & TCB_IGNORE_ONE_SIGSTOP)
892 error = ptrace(PTRACE_DETACH, tcp->pid, 0, 0);
894 /* On a clear day, you can see forever. */
897 if (errno != ESRCH) {
898 /* Shouldn't happen. */
899 perror_func_msg("ptrace(PTRACE_DETACH,%u)", tcp->pid);
902 /* ESRCH: process is either not stopped or doesn't exist. */
903 if (my_tkill(tcp->pid, 0) < 0) {
905 /* Shouldn't happen. */
906 perror_func_msg("tkill(%u,0)", tcp->pid);
907 /* else: process doesn't exist. */
910 /* Process is not stopped, need to stop it. */
913 * With SEIZE, tracee can be in group-stop already.
914 * In this state sending it another SIGSTOP does nothing.
915 * Need to use INTERRUPT.
916 * Testcase: trying to ^C a "strace -p <stopped_process>".
918 error = ptrace(PTRACE_INTERRUPT, tcp->pid, 0, 0);
922 perror_func_msg("ptrace(PTRACE_INTERRUPT,%u)", tcp->pid);
924 error = my_tkill(tcp->pid, SIGSTOP);
928 perror_func_msg("tkill(%u,SIGSTOP)", tcp->pid);
930 /* Either process doesn't exist, or some weird error. */
934 /* We end up here in three cases:
935 * 1. We sent PTRACE_INTERRUPT (use_seize case)
936 * 2. We sent SIGSTOP (!use_seize)
937 * 3. Attach SIGSTOP was already pending (TCB_IGNORE_ONE_SIGSTOP set)
941 if (waitpid(tcp->pid, &status, __WALL) < 0) {
945 * if (errno == ECHILD) break;
946 * ^^^ WRONG! We expect this PID to exist,
947 * and want to emit a message otherwise:
949 perror_func_msg("waitpid(%u)", tcp->pid);
952 if (!WIFSTOPPED(status)) {
954 * Tracee exited or was killed by signal.
955 * We shouldn't normally reach this place:
956 * we don't want to consume exit status.
957 * Consider "strace -p PID" being ^C-ed:
958 * we want merely to detach from PID.
960 * However, we _can_ end up here if tracee
965 sig = WSTOPSIG(status);
966 debug_msg("detach wait: event:%d sig:%d",
967 (unsigned) status >> 16, sig);
969 unsigned event = (unsigned)status >> 16;
970 if (event == PTRACE_EVENT_STOP /*&& sig == SIGTRAP*/) {
972 * sig == SIGTRAP: PTRACE_INTERRUPT stop.
973 * sig == other: process was already stopped
974 * with this stopping sig (see tests/detach-stopped).
975 * Looks like re-injecting this sig is not necessary
976 * in DETACH for the tracee to remain stopped.
981 * PTRACE_INTERRUPT is not guaranteed to produce
982 * the above event if other ptrace-stop is pending.
983 * See tests/detach-sleeping testcase:
984 * strace got SIGINT while tracee is sleeping.
985 * We sent PTRACE_INTERRUPT.
986 * We see syscall exit, not PTRACE_INTERRUPT stop.
987 * We won't get PTRACE_INTERRUPT stop
988 * if we would CONT now. Need to DETACH.
990 if (sig == syscall_trap_sig)
992 /* else: not sure in which case we can be here.
993 * Signal stop? Inject it while detaching.
995 ptrace_restart(PTRACE_DETACH, tcp, sig);
998 /* Note: this check has to be after use_seize check */
999 /* (else, in use_seize case SIGSTOP will be mistreated) */
1000 if (sig == SIGSTOP) {
1001 /* Detach, suppressing SIGSTOP */
1002 ptrace_restart(PTRACE_DETACH, tcp, 0);
1005 if (sig == syscall_trap_sig)
1007 /* Can't detach just yet, may need to wait for SIGSTOP */
1008 error = ptrace_restart(PTRACE_CONT, tcp, sig);
1010 /* Should not happen.
1011 * Note: ptrace_restart returns 0 on ESRCH, so it's not it.
1012 * ptrace_restart already emitted error message.
1019 if (!qflag && (tcp->flags & TCB_ATTACHED))
1020 error_msg("Process %u detached", tcp->pid);
1026 process_opt_p_list(char *opt)
1030 * We accept -p PID,PID; -p "`pidof PROG`"; -p "`pgrep PROG`".
1031 * pidof uses space as delim, pgrep uses newline. :(
1034 char *delim = opt + strcspn(opt, "\n\t ,");
1038 pid = string_to_uint(opt);
1040 error_msg_and_die("Invalid process id: '%s'", opt);
1042 if (pid == strace_tracer_pid) {
1043 error_msg_and_die("I'm sorry, I can't let you do that, Dave.");
1054 attach_tcb(struct tcb *const tcp)
1056 if (ptrace_attach_or_seize(tcp->pid) < 0) {
1057 perror_msg("attach: ptrace(%s, %d)",
1058 ptrace_attach_cmd, tcp->pid);
1063 after_successful_attach(tcp, TCB_GRABBED | post_attach_sigstop);
1064 debug_msg("attach to pid %d (main) succeeded", tcp->pid);
1066 static const char task_path[] = "/proc/%d/task";
1067 char procdir[sizeof(task_path) + sizeof(int) * 3];
1069 unsigned int ntid = 0, nerr = 0;
1071 if (followfork && tcp->pid != strace_child &&
1072 xsprintf(procdir, task_path, tcp->pid) > 0 &&
1073 (dir = opendir(procdir)) != NULL) {
1076 while ((de = read_dir(dir)) != NULL) {
1077 if (de->d_fileno == 0)
1080 int tid = string_to_uint(de->d_name);
1081 if (tid <= 0 || tid == tcp->pid)
1085 if (ptrace_attach_or_seize(tid) < 0) {
1087 debug_perror_msg("attach: ptrace(%s, %d)",
1088 ptrace_attach_cmd, tid);
1092 after_successful_attach(alloctcb(tid),
1093 TCB_GRABBED | post_attach_sigstop);
1094 debug_msg("attach to pid %d succeeded", tid);
1102 error_msg("Process %u attached"
1104 tcp->pid, ntid - nerr + 1);
1106 error_msg("Process %u attached",
1112 startup_attach(void)
1114 pid_t parent_pid = strace_tracer_pid;
1118 if (daemonized_tracer) {
1121 perror_func_msg_and_die("fork");
1123 if (pid) { /* parent */
1125 * Wait for grandchild to attach to straced process
1126 * (grandparent). Grandchild SIGKILLs us after it attached.
1127 * Grandparent's wait() is unblocked by our death,
1128 * it proceeds to exec the straced program.
1131 _exit(0); /* paranoia */
1134 /* We will be the tracer process. Remember our new pid: */
1135 strace_tracer_pid = getpid();
1138 for (tcbi = 0; tcbi < tcbtabsize; tcbi++) {
1144 /* Is this a process we should attach to, but not yet attached? */
1145 if (tcp->flags & TCB_ATTACHED)
1146 continue; /* no, we already attached it */
1148 if (tcp->pid == parent_pid || tcp->pid == strace_tracer_pid) {
1150 perror_msg("attach: pid %d", tcp->pid);
1159 } /* for each tcbtab[] */
1161 if (daemonized_tracer) {
1163 * Make parent go away.
1164 * Also makes grandparent's wait() unblock.
1166 kill(parent_pid, SIGKILL);
1171 /* Stack-o-phobic exec helper, in the hope to work around
1172 * NOMMU + "daemonized tracer" difficulty.
1174 struct exec_params {
1180 struct sigaction child_sa;
1182 static struct exec_params params_for_tracee;
1184 static void ATTRIBUTE_NOINLINE ATTRIBUTE_NORETURN
1187 struct exec_params *params = ¶ms_for_tracee;
1189 if (params->fd_to_close >= 0)
1190 close(params->fd_to_close);
1191 if (!daemonized_tracer && !use_seize) {
1192 if (ptrace(PTRACE_TRACEME, 0L, 0L, 0L) < 0) {
1193 perror_msg_and_die("ptrace(PTRACE_TRACEME, ...)");
1197 if (username != NULL) {
1199 * It is important to set groups before we
1200 * lose privileges on setuid.
1202 if (initgroups(username, run_gid) < 0) {
1203 perror_msg_and_die("initgroups");
1205 if (setregid(run_gid, params->run_egid) < 0) {
1206 perror_msg_and_die("setregid");
1208 if (setreuid(run_uid, params->run_euid) < 0) {
1209 perror_msg_and_die("setreuid");
1211 } else if (geteuid() != 0)
1212 if (setreuid(run_uid, run_uid) < 0) {
1213 perror_msg_and_die("setreuid");
1216 if (!daemonized_tracer) {
1218 * Induce a ptrace stop. Tracer (our parent)
1219 * will resume us with PTRACE_SYSCALL and display
1220 * the immediately following execve syscall.
1221 * Can't do this on NOMMU systems, we are after
1222 * vfork: parent is blocked, stopping would deadlock.
1225 kill(getpid(), SIGSTOP);
1228 /* we depend on SIGCHLD set to SIG_DFL by init code */
1229 /* if it happens to be SIG_IGN'ed, wait won't block */
1234 if (params_for_tracee.child_sa.sa_handler != SIG_DFL)
1235 sigaction(SIGCHLD, ¶ms_for_tracee.child_sa, NULL);
1237 debug_msg("seccomp filter %s",
1238 seccomp_filtering ? "enabled" : "disabled");
1239 if (seccomp_filtering)
1240 init_seccomp_filter();
1241 execv(params->pathname, params->argv);
1242 perror_msg_and_die("exec");
1246 * Open a dummy descriptor for use as a placeholder.
1247 * The descriptor is O_RDONLY with FD_CLOEXEC flag set.
1248 * A read attempt from such descriptor ends with EOF,
1249 * a write attempt is rejected with EBADF.
1252 open_dummy_desc(void)
1257 perror_func_msg_and_die("pipe");
1259 set_cloexec_flag(fds[0]);
1263 /* placeholder fds status for stdin and stdout */
1264 static bool fd_is_placeholder[2];
1267 * Ensure that all standard file descriptors are open by opening placeholder
1268 * file descriptors for those standard file descriptors that are not open.
1270 * The information which descriptors have been made open is saved
1271 * in fd_is_placeholder for later use.
1274 ensure_standard_fds_opened(void)
1278 while ((fd = open_dummy_desc()) <= 2) {
1281 fd_is_placeholder[fd] = true;
1289 * Redirect stdin and stdout unless they have been opened earlier
1290 * by ensure_standard_fds_opened as placeholders.
1293 redirect_standard_fds(void)
1298 * It might be a good idea to redirect stderr as well,
1299 * but we sometimes need to print error messages.
1301 for (i = 0; i <= 1; ++i) {
1302 if (!fd_is_placeholder[i]) {
1310 startup_child(char **argv)
1312 strace_stat_t statbuf;
1313 const char *filename;
1314 size_t filename_len;
1315 char pathname[PATH_MAX];
1320 filename_len = strlen(filename);
1322 if (filename_len > sizeof(pathname) - 1) {
1323 errno = ENAMETOOLONG;
1324 perror_msg_and_die("exec");
1326 if (strchr(filename, '/')) {
1327 strcpy(pathname, filename);
1329 #ifdef USE_DEBUGGING_EXEC
1331 * Debuggers customarily check the current directory
1332 * first regardless of the path but doing that gives
1333 * security geeks a panic attack.
1335 else if (stat_file(filename, &statbuf) == 0)
1336 strcpy(pathname, filename);
1337 #endif /* USE_DEBUGGING_EXEC */
1342 for (path = getenv("PATH"); path && *path; path += m) {
1343 const char *colon = strchr(path, ':');
1348 m = n = strlen(path);
1350 if (!getcwd(pathname, PATH_MAX))
1352 len = strlen(pathname);
1353 } else if (n > sizeof(pathname) - 1)
1356 strncpy(pathname, path, n);
1359 if (len && pathname[len - 1] != '/')
1360 pathname[len++] = '/';
1361 if (filename_len + len > sizeof(pathname) - 1)
1363 strcpy(pathname + len, filename);
1364 if (stat_file(pathname, &statbuf) == 0 &&
1365 /* Accept only regular files
1366 with some execute bits set.
1367 XXX not perfect, might still fail */
1368 S_ISREG(statbuf.st_mode) &&
1369 (statbuf.st_mode & 0111))
1372 if (!path || !*path)
1375 if (stat_file(pathname, &statbuf) < 0) {
1376 perror_msg_and_die("Can't stat '%s'", filename);
1379 params_for_tracee.fd_to_close = (shared_log != stderr) ? fileno(shared_log) : -1;
1380 params_for_tracee.run_euid = (statbuf.st_mode & S_ISUID) ? statbuf.st_uid : run_uid;
1381 params_for_tracee.run_egid = (statbuf.st_mode & S_ISGID) ? statbuf.st_gid : run_gid;
1382 params_for_tracee.argv = argv;
1384 * On NOMMU, can be safely freed only after execve in tracee.
1385 * It's hard to know when that happens, so we just leak it.
1387 params_for_tracee.pathname = NOMMU_SYSTEM ? xstrdup(pathname) : pathname;
1389 #if defined HAVE_PRCTL && defined PR_SET_PTRACER && defined PR_SET_PTRACER_ANY
1390 if (daemonized_tracer)
1391 prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY);
1396 perror_func_msg_and_die("fork");
1398 if ((pid != 0 && daemonized_tracer)
1399 || (pid == 0 && !daemonized_tracer)
1401 /* We are to become the tracee. Two cases:
1403 * not -D: we are child
1408 /* We are the tracer */
1410 if (!daemonized_tracer) {
1413 /* child did PTRACE_TRACEME, nothing to do in parent */
1415 if (!NOMMU_SYSTEM) {
1416 /* Wait until child stopped itself */
1418 while (waitpid(pid, &status, WSTOPPED) < 0) {
1421 perror_msg_and_die("waitpid");
1423 if (!WIFSTOPPED(status) || WSTOPSIG(status) != SIGSTOP) {
1424 kill_save_errno(pid, SIGKILL);
1425 perror_msg_and_die("Unexpected wait status %#x",
1429 /* Else: NOMMU case, we have no way to sync.
1430 * Just attach to it as soon as possible.
1431 * This means that we may miss a few first syscalls...
1434 if (ptrace_attach_or_seize(pid)) {
1435 kill_save_errno(pid, SIGKILL);
1436 perror_msg_and_die("attach: ptrace(%s, %d)",
1437 ptrace_attach_cmd, pid);
1442 tcp = alloctcb(pid);
1443 after_successful_attach(tcp, TCB_SKIP_DETACH_ON_FIRST_EXEC
1446 | post_attach_sigstop)));
1448 /* With -D, we are *child* here, the tracee is our parent. */
1449 strace_child = strace_tracer_pid;
1450 strace_tracer_pid = getpid();
1451 tcp = alloctcb(strace_child);
1452 tcp->flags |= TCB_SKIP_DETACH_ON_FIRST_EXEC | TCB_HIDE_LOG;
1454 * Attaching will be done later, by startup_attach.
1455 * Note: we don't do after_successful_attach() here either!
1458 /* NOMMU BUG! -D mode is active, we (child) return,
1459 * and we will scribble over parent's stack!
1460 * When parent later unpauses, it segfaults.
1463 * (1) by declaring exec_or_die() NORETURN,
1464 * hopefully compiler will just jump to it
1465 * instead of call (won't push anything to stack),
1466 * (2) by trying very hard in exec_or_die()
1467 * to not use any stack,
1468 * (3) having a really big (PATH_MAX) stack object
1469 * in this function, which creates a "buffer" between
1470 * child's and parent's stack pointers.
1471 * This may save us if (1) and (2) failed
1472 * and compiler decided to use stack in exec_or_die() anyway
1473 * (happens on i386 because of stack parameter passing).
1475 * A cleaner solution is to use makecontext + setcontext
1476 * to create a genuine separate stack and execute on it.
1480 if (seccomp_filtering)
1481 tcp->flags |= TCB_SECCOMP_FILTER;
1484 * A case where straced process is part of a pipe:
1485 * { sleep 1; yes | head -n99999; } | strace -o/dev/null sh -c 'exec <&-; sleep 9'
1486 * If strace won't close its fd#0, closing it in tracee is not enough:
1487 * the pipe is still open, it has a reader. Thus, "head" will not get its
1488 * SIGPIPE at once, on the first write.
1490 * Preventing it by redirecting strace's stdin/out.
1491 * (Don't leave fds 0 and 1 closed, this is bad practice: future opens
1492 * will reuse them, unexpectedly making a newly opened object "stdin").
1494 redirect_standard_fds();
1498 test_ptrace_seize(void)
1502 /* Need fork for test. NOMMU has no forks */
1504 post_attach_sigstop = 0; /* this sets use_seize to 1 */
1510 perror_func_msg_and_die("fork");
1517 /* PTRACE_SEIZE, unlike ATTACH, doesn't force tracee to trap. After
1518 * attaching tracee continues to run unless a trap condition occurs.
1519 * PTRACE_SEIZE doesn't affect signal or group stop state.
1521 if (ptrace(PTRACE_SEIZE, pid, 0, 0) == 0) {
1522 post_attach_sigstop = 0; /* this sets use_seize to 1 */
1524 debug_msg("PTRACE_SEIZE doesn't work");
1530 int status, tracee_pid;
1533 tracee_pid = waitpid(pid, &status, 0);
1534 if (tracee_pid <= 0) {
1537 perror_func_msg_and_die("unexpected wait result %d",
1540 if (WIFSIGNALED(status))
1543 error_func_msg_and_die("unexpected wait status %#x", status);
1548 get_os_release(void)
1552 perror_msg_and_die("uname");
1554 * u.release string consists of at most three parts
1555 * and normally has this form: "3.2.9[-some-garbage]",
1556 * "X.Y-something" means "X.Y.0".
1558 const char *p = u.release;
1559 unsigned int rel = 0;
1560 for (unsigned int parts = 0; parts < 3; ++parts) {
1562 for (; (*p >= '0') && (*p <= '9'); ++p) {
1575 set_sighandler(int signo, void (*sighandler)(int), struct sigaction *oldact)
1577 const struct sigaction sa = { .sa_handler = sighandler };
1578 sigaction(signo, &sa, oldact);
1582 * Initialization part of main() was eating much stack (~0.5k),
1583 * which was unused after init.
1584 * We can reuse it if we move init code into a separate function.
1586 * Don't want main() to inline us and defeat the reason
1587 * we have a separate function.
1589 static void ATTRIBUTE_NOINLINE
1590 init(int argc, char *argv[])
1593 int optF = 0, zflags = 0;
1595 if (!program_invocation_name || !*program_invocation_name) {
1596 static char name[] = "strace";
1597 program_invocation_name =
1598 (argc > 0 && argv[0] && *argv[0]) ? argv[0] : name;
1601 strace_tracer_pid = getpid();
1603 os_release = get_os_release();
1605 shared_log = stderr;
1606 set_sortby(DEFAULT_SORTBY);
1607 set_personality(DEFAULT_PERSONALITY);
1608 qualify("trace=all");
1609 qualify("abbrev=all");
1610 qualify("verbose=all");
1611 qualify("status=all");
1612 #if DEFAULT_QUAL_FLAGS != (QUAL_TRACE | QUAL_ABBREV | QUAL_VERBOSE)
1613 # error Bug in DEFAULT_QUAL_FLAGS
1615 qualify("signal=all");
1617 static const char optstring[] = "+"
1618 #ifdef ENABLE_STACKTRACE
1621 "a:Ab:cCdDe:E:fFhiI:o:O:p:P:qrs:S:tTu:vVwxX:yzZ";
1624 SECCOMP_OPTION = 0x100
1626 static const struct option longopts[] = {
1627 { "seccomp-bpf", no_argument, 0, SECCOMP_OPTION },
1628 { "help", no_argument, 0, 'h' },
1629 { "version", no_argument, 0, 'V' },
1633 while ((c = getopt_long(argc, argv, optstring, longopts, NULL)) != EOF) {
1636 acolumn = string_to_uint(optarg);
1638 error_opt_arg(c, optarg);
1644 if (strcmp(optarg, "execve") != 0)
1645 error_msg_and_die("Syscall '%s' for -b isn't supported",
1647 detach_on_execve = 1;
1650 if (cflag == CFLAG_BOTH) {
1651 error_msg_and_help("-c and -C are mutually exclusive");
1653 cflag = CFLAG_ONLY_STATS;
1656 if (cflag == CFLAG_ONLY_STATS) {
1657 error_msg_and_help("-c and -C are mutually exclusive");
1665 daemonized_tracer = 1;
1671 if (putenv(optarg) < 0)
1672 perror_msg_and_die("putenv");
1687 opt_intr = string_to_uint_upto(optarg, NUM_INTR_OPTS - 1);
1689 error_opt_arg(c, optarg);
1691 #ifdef ENABLE_STACKTRACE
1693 stack_trace_enabled = true;
1700 if (set_overhead(optarg) < 0)
1701 error_opt_arg(c, optarg);
1704 process_opt_p_list(optarg);
1707 pathtrace_select(optarg);
1716 i = string_to_uint(optarg);
1717 if (i < 0 || (unsigned int) i > -1U / 4)
1718 error_opt_arg(c, optarg);
1734 qualify("abbrev=none");
1741 count_wallclock = 1;
1747 if (!strcmp(optarg, "raw"))
1748 xlat_verbosity = XLAT_STYLE_RAW;
1749 else if (!strcmp(optarg, "abbrev"))
1750 xlat_verbosity = XLAT_STYLE_ABBREV;
1751 else if (!strcmp(optarg, "verbose"))
1752 xlat_verbosity = XLAT_STYLE_VERBOSE;
1754 error_opt_arg(c, optarg);
1760 clear_number_set_array(status_set, 1);
1761 add_number_to_set(STATUS_SUCCESSFUL, status_set);
1765 clear_number_set_array(status_set, 1);
1766 add_number_to_set(STATUS_FAILED, status_set);
1769 case SECCOMP_OPTION:
1770 seccomp_filtering = true;
1773 error_msg_and_help(NULL);
1781 if (argc < 0 || (!nprocs && !argc)) {
1782 error_msg_and_help("must have PROG [ARGS] or -p PID");
1785 if (!argc && daemonized_tracer) {
1786 error_msg_and_help("PROG [ARGS] must be specified with -D");
1789 if (seccomp_filtering) {
1790 if (nprocs && (!argc || debug_flag))
1791 error_msg("--seccomp-bpf is not enabled for processes"
1792 " attached with -p");
1794 error_msg("--seccomp-bpf implies -f");
1801 error_msg("deprecated option -F ignored");
1803 error_msg("option -F is deprecated, "
1804 "please use -f instead");
1809 if (followfork >= 2 && cflag) {
1810 error_msg_and_help("(-c or -C) and -ff are mutually exclusive");
1813 if (count_wallclock && !cflag) {
1814 error_msg_and_help("-w must be given with (-c or -C)");
1817 if (cflag == CFLAG_ONLY_STATS) {
1819 error_msg("-%c has no effect with -c", 'i');
1820 if (stack_trace_enabled)
1821 error_msg("-%c has no effect with -c", 'k');
1823 error_msg("-%c has no effect with -c", 'r');
1825 error_msg("-%c has no effect with -c", 't');
1827 error_msg("-%c has no effect with -c", 'T');
1829 error_msg("-%c has no effect with -c", 'y');
1832 #ifndef HAVE_OPEN_MEMSTREAM
1833 if (!is_complete_set(status_set, NUMBER_OF_STATUSES))
1834 error_msg_and_help("open_memstream is required to use -z, -Z, or -e status");
1838 error_msg("Only the last of -z/-Z options will take effect. "
1839 "See status qualifier for more complex filters.");
1841 acolumn_spaces = xmalloc(acolumn + 1);
1842 memset(acolumn_spaces, ' ', acolumn);
1843 acolumn_spaces[acolumn] = '\0';
1845 set_sighandler(SIGCHLD, SIG_DFL, ¶ms_for_tracee.child_sa);
1847 #ifdef ENABLE_STACKTRACE
1848 if (stack_trace_enabled)
1852 /* See if they want to run as another user. */
1853 if (username != NULL) {
1854 struct passwd *pent;
1856 if (getuid() != 0 || geteuid() != 0) {
1857 error_msg_and_die("You must be root to use the -u option");
1859 pent = getpwnam(username);
1861 error_msg_and_die("Cannot find user '%s'", username);
1863 run_uid = pent->pw_uid;
1864 run_gid = pent->pw_gid;
1871 ptrace_setoptions |= PTRACE_O_TRACECLONE |
1872 PTRACE_O_TRACEFORK |
1873 PTRACE_O_TRACEVFORK;
1875 if (seccomp_filtering)
1876 check_seccomp_filter();
1877 if (seccomp_filtering)
1878 ptrace_setoptions |= PTRACE_O_TRACESECCOMP;
1880 debug_msg("ptrace_setoptions = %#x", ptrace_setoptions);
1881 test_ptrace_seize();
1882 test_ptrace_get_syscall_info();
1885 * Is something weird with our stdin and/or stdout -
1886 * for example, may they be not open? In this case,
1887 * ensure that none of the future opens uses them.
1889 * This was seen in the wild when /proc/sys/kernel/core_pattern
1890 * was set to "|/bin/strace -o/tmp/LOG PROG":
1891 * kernel runs coredump helper with fd#0 open but fd#1 closed (!),
1892 * therefore LOG gets opened to fd#1, and fd#1 is closed by
1893 * "don't hold up stdin/out open" code soon after.
1895 ensure_standard_fds_opened();
1897 /* Check if they want to redirect the output. */
1899 /* See if they want to pipe the output. */
1900 if (outfname[0] == '|' || outfname[0] == '!') {
1902 * We can't do the <outfname>.PID funny business
1903 * when using popen, so prohibit it.
1905 if (followfork >= 2)
1906 error_msg_and_help("piping the output and -ff "
1907 "are mutually exclusive");
1908 shared_log = strace_popen(outfname + 1);
1909 } else if (followfork < 2) {
1910 shared_log = strace_fopen(outfname);
1911 } else if (strlen(outfname) >= PATH_MAX - sizeof(int) * 3) {
1912 errno = ENAMETOOLONG;
1913 perror_msg_and_die("%s", outfname);
1916 /* -ff without -o FILE is the same as single -f */
1917 if (followfork >= 2)
1921 if (!outfname || outfname[0] == '|' || outfname[0] == '!') {
1922 setvbuf(shared_log, NULL, _IOLBF, 0);
1926 * argv[0] -pPID -oFILE Default interactive setting
1927 * yes * 0 INTR_WHILE_WAIT
1928 * no 1 0 INTR_WHILE_WAIT
1929 * yes * 1 INTR_NEVER
1930 * no 1 1 INTR_WHILE_WAIT
1933 if (daemonized_tracer && !opt_intr)
1934 opt_intr = INTR_BLOCK_TSTP_TOO;
1935 if (outfname && argc) {
1937 opt_intr = INTR_NEVER;
1942 opt_intr = INTR_WHILE_WAIT;
1945 * startup_child() must be called before the signal handlers get
1946 * installed below as they are inherited into the spawned process.
1947 * Also we do not need to be protected by them as during interruption
1948 * in the startup_child() mode we kill the spawned process anyway.
1951 startup_child(argv);
1954 set_sighandler(SIGTTOU, SIG_IGN, NULL);
1955 set_sighandler(SIGTTIN, SIG_IGN, NULL);
1956 if (opt_intr != INTR_ANYWHERE) {
1957 if (opt_intr == INTR_BLOCK_TSTP_TOO)
1958 set_sighandler(SIGTSTP, SIG_IGN, NULL);
1960 * In interactive mode (if no -o OUTFILE, or -p PID is used),
1961 * fatal signals are handled asynchronously and acted
1962 * when waiting for process state changes.
1963 * In non-interactive mode these signals are ignored.
1965 set_sighandler(SIGHUP, interactive ? interrupt : SIG_IGN, NULL);
1966 set_sighandler(SIGINT, interactive ? interrupt : SIG_IGN, NULL);
1967 set_sighandler(SIGQUIT, interactive ? interrupt : SIG_IGN, NULL);
1968 set_sighandler(SIGPIPE, interactive ? interrupt : SIG_IGN, NULL);
1969 set_sighandler(SIGTERM, interactive ? interrupt : SIG_IGN, NULL);
1972 sigemptyset(&timer_set);
1973 sigaddset(&timer_set, SIGALRM);
1974 sigprocmask(SIG_BLOCK, &timer_set, NULL);
1975 set_sighandler(SIGALRM, timer_sighandler, NULL);
1977 if (nprocs != 0 || daemonized_tracer)
1980 /* Do we want pids printed in our -o OUTFILE?
1981 * -ff: no (every pid has its own file); or
1982 * -f: yes (there can be more pids in the future); or
1983 * -p PID1,PID2: yes (there are already more than one pid)
1985 print_pid_pfx = (outfname && followfork < 2 && (followfork == 1 || nprocs > 1));
1989 pid2tcb(const int pid)
1994 #define PID2TCB_CACHE_SIZE 1024U
1995 #define PID2TCB_CACHE_MASK (PID2TCB_CACHE_SIZE - 1)
1997 static struct tcb *pid2tcb_cache[PID2TCB_CACHE_SIZE];
1998 struct tcb **const ptcp = &pid2tcb_cache[pid & PID2TCB_CACHE_MASK];
1999 struct tcb *tcp = *ptcp;
2001 if (tcp && tcp->pid == pid)
2004 for (unsigned int i = 0; i < tcbtabsize; ++i) {
2006 if (tcp->pid == pid)
2014 cleanup(int fatal_sig)
2020 fatal_sig = SIGTERM;
2022 for (i = 0; i < tcbtabsize; i++) {
2026 debug_func_msg("looking at pid %u", tcp->pid);
2027 if (tcp->pid == strace_child) {
2028 kill(tcp->pid, SIGCONT);
2029 kill(tcp->pid, fatal_sig);
2042 print_debug_info(const int pid, int status)
2044 const unsigned int event = (unsigned int) status >> 16;
2045 char buf[sizeof("WIFEXITED,exitcode=%u") + sizeof(int)*3 /*paranoia:*/ + 16];
2046 char evbuf[sizeof(",EVENT_VFORK_DONE (%u)") + sizeof(int)*3 /*paranoia:*/ + 16];
2049 if (WIFSIGNALED(status))
2050 xsprintf(buf, "WIFSIGNALED,%ssig=%s",
2051 WCOREDUMP(status) ? "core," : "",
2052 sprintsigname(WTERMSIG(status)));
2053 if (WIFEXITED(status))
2054 xsprintf(buf, "WIFEXITED,exitcode=%u", WEXITSTATUS(status));
2055 if (WIFSTOPPED(status))
2056 xsprintf(buf, "WIFSTOPPED,sig=%s",
2057 sprintsigname(WSTOPSIG(status)));
2060 static const char *const event_names[] = {
2061 [PTRACE_EVENT_CLONE] = "CLONE",
2062 [PTRACE_EVENT_FORK] = "FORK",
2063 [PTRACE_EVENT_VFORK] = "VFORK",
2064 [PTRACE_EVENT_VFORK_DONE] = "VFORK_DONE",
2065 [PTRACE_EVENT_EXEC] = "EXEC",
2066 [PTRACE_EVENT_EXIT] = "EXIT",
2067 [PTRACE_EVENT_SECCOMP] = "SECCOMP",
2068 /* [PTRACE_EVENT_STOP (=128)] would make biggish array */
2070 const char *e = "??";
2071 if (event < ARRAY_SIZE(event_names))
2072 e = event_names[event];
2073 else if (event == PTRACE_EVENT_STOP)
2075 xsprintf(evbuf, ",EVENT_%s (%u)", e, event);
2077 error_msg("[wait(0x%06x) = %u] %s%s", status, pid, buf, evbuf);
2081 maybe_allocate_tcb(const int pid, int status)
2083 if (!WIFSTOPPED(status)) {
2084 if (detach_on_execve && pid == strace_child) {
2085 /* example: strace -bexecve sh -c 'exec true' */
2090 * This can happen if we inherited an unknown child.
2091 * Example: (sleep 1 & exec strace true)
2093 error_msg("Exit of unknown pid %u ignored", pid);
2097 /* We assume it's a fork/vfork/clone child */
2098 struct tcb *tcp = alloctcb(pid);
2099 after_successful_attach(tcp, post_attach_sigstop);
2101 error_msg("Process %d attached", pid);
2105 * This can happen if a clone call misused CLONE_PTRACE itself.
2107 * There used to be a dance around possible re-injection of
2108 * WSTOPSIG(status), but it was later removed as the only
2109 * observable stop here is the initial ptrace-stop.
2111 ptrace(PTRACE_DETACH, pid, NULL, 0L);
2112 error_msg("Detached unknown pid %d", pid);
2118 * Under Linux, execve changes pid to thread leader's pid, and we see this
2119 * changed pid on EVENT_EXEC and later, execve sysexit. Leader "disappears"
2120 * without exit notification. Let user know that, drop leader's tcb, and fix
2121 * up pid in execve thread's tcb. Effectively, execve thread's tcb replaces
2124 * BTW, leader is 'stuck undead' (doesn't report WIFEXITED on exit syscall)
2125 * in multi-threaded programs exactly in order to handle this case.
2128 maybe_switch_tcbs(struct tcb *tcp, const int pid)
2131 * PTRACE_GETEVENTMSG returns old pid starting from Linux 3.0.
2132 * On 2.6 and earlier it can return garbage.
2134 if (os_release < KERNEL_VERSION(3, 0, 0))
2137 const long old_pid = tcb_wait_tab[tcp->wait_data_idx].msg;
2139 /* Avoid truncation in pid2tcb() param passing */
2140 if (old_pid <= 0 || old_pid == pid)
2142 if ((unsigned long) old_pid > UINT_MAX)
2144 struct tcb *execve_thread = pid2tcb(old_pid);
2145 /* It should be !NULL, but I feel paranoid */
2149 if (execve_thread->curcol != 0) {
2151 * One case we are here is -ff, try
2152 * "strace -oLOG -ff test/threaded_execve".
2153 * Another case is demonstrated by
2154 * tests/maybe_switch_current_tcp.c
2156 fprintf(execve_thread->outf, " <pid changed to %d ...>\n", pid);
2157 /*execve_thread->curcol = 0; - no need, see code below */
2159 /* Swap output FILEs and memstream (needed for -ff) */
2160 FILE *fp = execve_thread->outf;
2161 execve_thread->outf = tcp->outf;
2163 if (execve_thread->staged_output_data || tcp->staged_output_data) {
2164 struct staged_output_data *staged_output_data;
2166 staged_output_data = execve_thread->staged_output_data;
2167 execve_thread->staged_output_data = tcp->staged_output_data;
2168 tcp->staged_output_data = staged_output_data;
2171 /* And their column positions */
2172 execve_thread->curcol = tcp->curcol;
2174 /* Drop leader, but close execve'd thread outfile (if -ff) */
2176 /* Switch to the thread, reusing leader's outfile and pid */
2177 tcp = execve_thread;
2179 if (cflag != CFLAG_ONLY_STATS) {
2181 tprintf("+++ superseded by execve in pid %lu +++\n", old_pid);
2184 * Need to reopen memstream for thread
2185 * as we closed it in droptcb.
2187 if (!is_complete_set(status_set, NUMBER_OF_STATUSES))
2188 strace_open_memstream(tcp);
2189 tcp->flags |= TCB_REPRINT;
2196 maybe_switch_current_tcp(void)
2198 struct tcb *tcp = maybe_switch_tcbs(current_tcp, current_tcp->pid);
2201 set_current_tcp(tcp);
2207 print_signalled(struct tcb *tcp, const int pid, int status)
2209 if (pid == strace_child) {
2210 exit_code = 0x100 | WTERMSIG(status);
2214 if (cflag != CFLAG_ONLY_STATS
2215 && is_number_in_set(WTERMSIG(status), signal_set)) {
2217 tprintf("+++ killed by %s %s+++\n",
2218 sprintsigname(WTERMSIG(status)),
2219 WCOREDUMP(status) ? "(core dumped) " : "");
2225 print_exited(struct tcb *tcp, const int pid, int status)
2227 if (pid == strace_child) {
2228 exit_code = WEXITSTATUS(status);
2232 if (cflag != CFLAG_ONLY_STATS &&
2235 tprintf("+++ exited with %d +++\n", WEXITSTATUS(status));
2241 print_stopped(struct tcb *tcp, const siginfo_t *si, const unsigned int sig)
2243 if (cflag != CFLAG_ONLY_STATS
2245 && is_number_in_set(sig, signal_set)) {
2248 tprintf("--- %s ", sprintsigname(sig));
2252 tprintf("--- stopped by %s ---\n", sprintsigname(sig));
2255 #ifdef ENABLE_STACKTRACE
2256 if (stack_trace_enabled)
2257 unwind_tcb_print(tcp);
2263 startup_tcb(struct tcb *tcp)
2265 debug_msg("pid %d has TCB_STARTUP, initializing it", tcp->pid);
2267 tcp->flags &= ~TCB_STARTUP;
2270 debug_msg("setting opts 0x%x on pid %d",
2271 ptrace_setoptions, tcp->pid);
2272 if (ptrace(PTRACE_SETOPTIONS, tcp->pid, NULL, ptrace_setoptions) < 0) {
2273 if (errno != ESRCH) {
2274 /* Should never happen, really */
2275 perror_msg_and_die("PTRACE_SETOPTIONS");
2280 if ((tcp->flags & TCB_GRABBED) && (get_scno(tcp) == 1))
2281 tcp->s_prev_ent = tcp->s_ent;
2284 tcp->atime = tcp->stime;
2289 print_event_exit(struct tcb *tcp)
2291 if (entering(tcp) || filtered(tcp) || hide_log(tcp)
2292 || cflag == CFLAG_ONLY_STATS) {
2296 if (followfork < 2 && printing_tcp && printing_tcp != tcp
2297 && printing_tcp->curcol != 0) {
2298 set_current_tcp(printing_tcp);
2299 tprints(" <unfinished ...>\n");
2300 flush_tcp_output(printing_tcp);
2301 printing_tcp->curcol = 0;
2302 set_current_tcp(tcp);
2305 print_syscall_resume(tcp);
2307 if (!(tcp->sys_func_rval & RVAL_DECODED)) {
2309 * The decoder has probably decided to print something
2310 * on exiting syscall which is not going to happen.
2312 tprints(" <unfinished ...>");
2319 if (!is_complete_set(status_set, NUMBER_OF_STATUSES)) {
2320 bool publish = is_number_in_set(STATUS_UNFINISHED, status_set);
2321 strace_close_memstream(tcp, publish);
2327 trace_wait_data_size(struct tcb *tcp)
2329 return sizeof(struct tcb_wait_data);
2332 static struct tcb_wait_data *
2333 init_trace_wait_data(void *p)
2335 struct tcb_wait_data *wd = p;
2337 memset(wd, 0, sizeof(*wd));
2342 static struct tcb_wait_data *
2343 copy_trace_wait_data(const struct tcb_wait_data *wd)
2345 struct tcb_wait_data *new_wd = xmalloc(sizeof(*new_wd));
2347 memcpy(new_wd, wd, sizeof(*wd));
2353 free_trace_wait_data(struct tcb_wait_data *wd)
2359 tcb_wait_tab_check_size(const size_t size)
2361 while (size >= tcb_wait_tab_size) {
2362 tcb_wait_tab = xgrowarray(tcb_wait_tab,
2364 sizeof(tcb_wait_tab[0]));
2368 static const struct tcb_wait_data *
2374 invalidate_umove_cache();
2376 struct tcb *tcp = NULL;
2377 struct list_item *elem;
2379 static EMPTY_LIST(pending_tcps);
2380 /* Handle the queued tcbs before waiting for new events. */
2381 if (!list_is_empty(&pending_tcps))
2382 goto next_event_get_tcp;
2384 static struct tcb *extra_tcp;
2385 static size_t wait_extra_data_idx;
2386 /* Handle the extra tcb event. */
2390 tcp->wait_data_idx = wait_extra_data_idx;
2392 debug_msg("dequeued extra event for pid %u", tcp->pid);
2393 goto next_event_exit;
2397 * Used to exit simply when nprocs hits zero, but in this testcase:
2398 * int main(void) { _exit(!!fork()); }
2399 * under strace -f, parent sometimes (rarely) manages
2400 * to exit before we see the first stop of the child,
2401 * and we are losing track of it:
2402 * 19923 clone(...) = 19924
2403 * 19923 exit_group(1) = ?
2404 * 19923 +++ exited with 1 +++
2405 * Exiting only when wait() returns ECHILD works better.
2407 if (popen_pid != 0) {
2408 /* However, if -o|logger is in use, we can't do that.
2409 * Can work around that by double-forking the logger,
2410 * but that loses the ability to wait for its completion
2411 * on exit. Oh well...
2417 const bool unblock_delay_timer = is_delay_timer_armed();
2420 * The window of opportunity to handle expirations
2421 * of the delay timer opens here.
2423 * Unblock the signal handler for the delay timer
2424 * iff the delay timer is already created.
2426 if (unblock_delay_timer)
2427 sigprocmask(SIG_UNBLOCK, &timer_set, NULL);
2430 * If the delay timer has expired, then its expiration
2431 * has been handled already by the signal handler.
2433 * If the delay timer expires during wait4(),
2434 * then the system call will be interrupted and
2435 * the expiration will be handled by the signal handler.
2439 int pid = wait4(-1, &status, __WALL, (cflag ? &ru : NULL));
2440 int wait_errno = errno;
2443 * The window of opportunity to handle expirations
2444 * of the delay timer closes here.
2446 * Block the signal handler for the delay timer
2447 * iff it was unblocked earlier.
2449 if (unblock_delay_timer) {
2450 sigprocmask(SIG_BLOCK, &timer_set, NULL);
2456 size_t wait_tab_pos = 0;
2457 bool wait_nohang = false;
2460 * Wait for new events until wait4() returns 0 (meaning that there's
2461 * nothing more to wait for for now), or a second event for some tcb
2462 * appears (which may happen if a tracee was SIGKILL'ed, for example).
2465 struct tcb_wait_data *wd;
2468 if (wait_errno == EINTR)
2472 if (nprocs == 0 && wait_errno == ECHILD)
2475 * If nprocs > 0, ECHILD is not expected,
2476 * treat it as any other error here:
2479 perror_msg_and_die("wait4(__WALL)");
2485 if (pid == popen_pid) {
2486 if (!WIFSTOPPED(status))
2492 print_debug_info(pid, status);
2494 /* Look up 'pid' in our table. */
2498 tcp = maybe_allocate_tcb(pid, status);
2500 goto next_event_wait_next;
2504 tcp->stime.tv_sec = ru.ru_stime.tv_sec;
2505 tcp->stime.tv_nsec = ru.ru_stime.tv_usec * 1000;
2508 tcb_wait_tab_check_size(wait_tab_pos);
2510 /* Initialise a new wait data structure. */
2511 wd = tcb_wait_tab + wait_tab_pos;
2512 init_trace_wait_data(wd);
2513 wd->status = status;
2515 if (WIFSIGNALED(status)) {
2516 wd->te = TE_SIGNALLED;
2517 } else if (WIFEXITED(status)) {
2521 * As WCONTINUED flag has not been specified to wait4,
2522 * it cannot be WIFCONTINUED(status), so the only case
2523 * that remains is WIFSTOPPED(status).
2526 const unsigned int sig = WSTOPSIG(status);
2527 const unsigned int event = (unsigned int) status >> 16;
2532 * Is this post-attach SIGSTOP?
2533 * Interestingly, the process may stop
2534 * with STOPSIG equal to some other signal
2535 * than SIGSTOP if we happened to attach
2536 * just before the process takes a signal.
2538 if (sig == SIGSTOP &&
2539 (tcp->flags & TCB_IGNORE_ONE_SIGSTOP)) {
2540 debug_func_msg("ignored SIGSTOP on "
2541 "pid %d", tcp->pid);
2542 tcp->flags &= ~TCB_IGNORE_ONE_SIGSTOP;
2543 wd->te = TE_RESTART;
2544 } else if (sig == syscall_trap_sig) {
2545 wd->te = TE_SYSCALL_STOP;
2548 * True if tracee is stopped by signal
2549 * (as opposed to "tracee received
2551 * TODO: shouldn't we check for
2552 * errno == EINVAL too?
2553 * We can get ESRCH instead, you know...
2555 bool stopped = ptrace(PTRACE_GETSIGINFO,
2556 pid, 0, &wd->si) < 0;
2558 wd->te = stopped ? TE_GROUP_STOP
2559 : TE_SIGNAL_DELIVERY_STOP;
2562 case PTRACE_EVENT_STOP:
2564 * PTRACE_INTERRUPT-stop or group-stop.
2565 * PTRACE_INTERRUPT-stop has sig == SIGTRAP here.
2572 wd->te = TE_GROUP_STOP;
2575 wd->te = TE_RESTART;
2578 case PTRACE_EVENT_EXEC:
2580 * TODO: shouldn't we check for
2581 * errno == EINVAL here, too?
2582 * We can get ESRCH instead, you know...
2584 if (ptrace(PTRACE_GETEVENTMSG, pid, NULL,
2588 wd->te = TE_STOP_BEFORE_EXECVE;
2590 case PTRACE_EVENT_EXIT:
2591 wd->te = TE_STOP_BEFORE_EXIT;
2593 case PTRACE_EVENT_SECCOMP:
2594 wd->te = TE_SECCOMP;
2597 wd->te = TE_RESTART;
2602 error_func_msg("Tracing event hasn't been determined "
2603 "for pid %d, status %0#x", pid, status);
2605 if (!list_is_empty(&tcp->wait_list)) {
2606 wait_extra_data_idx = wait_tab_pos;
2608 debug_func_msg("queued extra pid %d", tcp->pid);
2610 tcp->wait_data_idx = wait_tab_pos;
2611 list_append(&pending_tcps, &tcp->wait_list);
2612 debug_func_msg("queued pid %d", tcp->pid);
2620 next_event_wait_next:
2621 pid = wait4(-1, &status, __WALL | WNOHANG, (cflag ? &ru : NULL));
2627 elem = list_remove_head(&pending_tcps);
2630 tcb_wait_tab_check_size(0);
2631 memset(tcb_wait_tab, 0, sizeof(*tcb_wait_tab));
2632 tcb_wait_tab->te = TE_NEXT;
2634 return tcb_wait_tab;
2636 tcp = list_elem(elem, struct tcb, wait_list);
2637 debug_func_msg("dequeued pid %d", tcp->pid);
2641 /* Is this the very first time we see this tracee stopped? */
2642 if (tcp->flags & TCB_STARTUP)
2647 /* Set current output file */
2648 set_current_tcp(tcp);
2650 return tcb_wait_tab + tcp->wait_data_idx;
2654 trace_syscall(struct tcb *tcp, unsigned int *sig)
2656 if (entering(tcp)) {
2657 int res = syscall_entering_decode(tcp);
2662 res = syscall_entering_trace(tcp, sig);
2664 syscall_entering_finish(tcp, res);
2667 struct timespec ts = {};
2668 int res = syscall_exiting_decode(tcp, &ts);
2670 res = syscall_exiting_trace(tcp, &ts, res);
2672 syscall_exiting_finish(tcp);
2677 /* Returns true iff the main trace loop has to continue. */
2679 dispatch_event(const struct tcb_wait_data *wd)
2681 unsigned int restart_op;
2682 unsigned int restart_sig = 0;
2683 enum trace_event te = wd ? wd->te : TE_BREAK;
2685 * Copy wd->status to a non-const variable to workaround glibc bugs
2686 * around union wait fixed by glibc commit glibc-2.24~391
2688 int status = wd ? wd->status : 0;
2690 if (current_tcp && has_seccomp_filter(current_tcp))
2691 restart_op = seccomp_filter_restart_operator(current_tcp);
2693 restart_op = PTRACE_SYSCALL;
2706 if (!has_seccomp_filter(current_tcp)) {
2708 * We don't know if forks/clones have a seccomp filter
2709 * when they are created, but we can detect it when we
2710 * have a seccomp-stop.
2711 * In such a case, if !seccomp_before_sysentry, we have
2712 * already processed the syscall entry, so we avoid
2713 * processing it a second time.
2715 current_tcp->flags |= TCB_SECCOMP_FILTER;
2716 restart_op = PTRACE_SYSCALL;
2720 if (seccomp_before_sysentry) {
2721 restart_op = PTRACE_SYSCALL;
2724 ATTRIBUTE_FALLTHROUGH;
2726 case TE_SYSCALL_STOP:
2727 if (trace_syscall(current_tcp, &restart_sig) < 0) {
2729 * ptrace() failed in trace_syscall().
2730 * Likely a result of process disappearing mid-flight.
2731 * Observed case: exit_group() or SIGKILL terminating
2732 * all processes in thread group.
2733 * We assume that ptrace error was caused by process death.
2734 * We used to detach(current_tcp) here, but since we no
2735 * longer implement "detach before death" policy/hack,
2736 * we can let this process to report its death to us
2737 * normally, via WIFEXITED or WIFSIGNALED wait status.
2741 if (has_seccomp_filter(current_tcp)) {
2743 * Syscall and seccomp stops can happen in different
2744 * orders depending on kernel. strace tests this in
2745 * check_seccomp_order_tracer().
2748 * (seccomp-stop before syscall-entry-stop)
2749 * +--> seccomp-stop ->-PTRACE_SYSCALL->-+
2751 * PTRACE_CONT syscall-entry-stop
2753 * syscall-exit-stop <---PTRACE_SYSCALL-----<----+
2756 * (seccomp-stop after syscall-entry-stop)
2757 * syscall-entry-stop
2759 * +---->-----PTRACE_CONT---->----+
2761 * syscall-exit-stop seccomp-stop
2763 * +----<----PTRACE_SYSCALL---<---+
2765 * Note in Linux 4.8+, we restart in PTRACE_CONT
2766 * after syscall-exit to skip the syscall-entry-stop.
2767 * The next seccomp-stop will be treated as a syscall
2770 * The line below implements this behavior.
2771 * Note that exiting(current_tcp) actually marks
2772 * a syscall-entry-stop because the flag was inverted
2773 * in the above call to trace_syscall.
2775 restart_op = exiting(current_tcp) ? PTRACE_SYSCALL : PTRACE_CONT;
2779 case TE_SIGNAL_DELIVERY_STOP:
2780 restart_sig = WSTOPSIG(status);
2781 print_stopped(current_tcp, &wd->si, restart_sig);
2785 print_signalled(current_tcp, current_tcp->pid, status);
2786 droptcb(current_tcp);
2790 restart_sig = WSTOPSIG(status);
2791 print_stopped(current_tcp, NULL, restart_sig);
2794 * This ends ptrace-stop, but does *not* end group-stop.
2795 * This makes stopping signals work properly on straced
2796 * process (that is, process really stops. It used to
2799 restart_op = PTRACE_LISTEN;
2805 print_exited(current_tcp, current_tcp->pid, status);
2806 droptcb(current_tcp);
2809 case TE_STOP_BEFORE_EXECVE:
2810 /* The syscall succeeded, clear the flag. */
2811 current_tcp->flags &= ~TCB_CHECK_EXEC_SYSCALL;
2813 * Check that we are inside syscall now (next event after
2814 * PTRACE_EVENT_EXEC should be for syscall exiting). If it is
2815 * not the case, we might have a situation when we attach to a
2816 * process and the first thing we see is a PTRACE_EVENT_EXEC
2817 * and all the following syscall state tracking is screwed up
2820 if (!maybe_switch_current_tcp() && entering(current_tcp)) {
2823 error_msg("Stray PTRACE_EVENT_EXEC from pid %d"
2824 ", trying to recover...",
2827 current_tcp->flags |= TCB_RECOVERING;
2828 ret = trace_syscall(current_tcp, &restart_sig);
2829 current_tcp->flags &= ~TCB_RECOVERING;
2832 /* The reason is described in TE_SYSCALL_STOP */
2837 if (detach_on_execve) {
2838 if (current_tcp->flags & TCB_SKIP_DETACH_ON_FIRST_EXEC) {
2839 current_tcp->flags &= ~TCB_SKIP_DETACH_ON_FIRST_EXEC;
2841 detach(current_tcp); /* do "-b execve" thingy */
2847 case TE_STOP_BEFORE_EXIT:
2848 print_event_exit(current_tcp);
2852 /* We handled quick cases, we are permitted to interrupt now. */
2856 /* If the process is being delayed, do not ptrace_restart just yet */
2857 if (syscall_delayed(current_tcp)) {
2858 if (current_tcp->delayed_wait_data)
2859 error_func_msg("pid %d has delayed wait data set"
2860 " already", current_tcp->pid);
2862 current_tcp->delayed_wait_data = copy_trace_wait_data(wd);
2867 if (ptrace_restart(restart_op, current_tcp, restart_sig) < 0) {
2868 /* Note: ptrace_restart emitted error message */
2876 restart_delayed_tcb(struct tcb *const tcp)
2878 struct tcb_wait_data *wd = tcp->delayed_wait_data;
2881 error_func_msg("No delayed wait data found for pid %d",
2883 wd = init_trace_wait_data(alloca(trace_wait_data_size(tcp)));
2886 wd->te = TE_RESTART;
2888 debug_func_msg("pid %d", tcp->pid);
2890 tcp->flags &= ~TCB_DELAYED;
2892 struct tcb *const prev_tcp = current_tcp;
2894 bool ret = dispatch_event(wd);
2895 current_tcp = prev_tcp;
2897 free_trace_wait_data(tcp->delayed_wait_data);
2898 tcp->delayed_wait_data = NULL;
2904 restart_delayed_tcbs(void)
2906 struct tcb *tcp_next = NULL;
2907 struct timespec ts_now;
2909 clock_gettime(CLOCK_MONOTONIC, &ts_now);
2911 for (size_t i = 0; i < tcbtabsize; i++) {
2912 struct tcb *tcp = tcbtab[i];
2914 if (tcp->pid && syscall_delayed(tcp)) {
2915 if (ts_cmp(&ts_now, &tcp->delay_expiration_time) > 0) {
2916 if (!restart_delayed_tcb(tcp))
2919 /* Check whether this tcb is the next. */
2921 ts_cmp(&tcp_next->delay_expiration_time,
2922 &tcp->delay_expiration_time) > 0) {
2930 arm_delay_timer(tcp_next);
2936 * As this signal handler does a lot of work that is not suitable
2937 * for signal handlers, extra care must be taken to ensure that
2938 * it is enabled only in those places where it's safe.
2941 timer_sighandler(int sig)
2943 delay_timer_expired();
2948 int saved_errno = errno;
2950 if (!restart_delayed_tcbs())
2953 errno = saved_errno;
2956 #ifdef ENABLE_COVERAGE_GCOV
2957 extern void __gcov_flush(void);
2960 static void ATTRIBUTE_NORETURN
2963 int sig = interrupted;
2967 call_summary(shared_log);
2969 if (shared_log != stderr)
2972 while (waitpid(popen_pid, NULL, 0) < 0 && errno == EINTR)
2976 exit_code = 0x100 | sig;
2978 if (exit_code > 0xff) {
2979 /* Avoid potential core file clobbering. */
2980 struct_rlimit rlim = {0, 0};
2981 set_rlimit(RLIMIT_CORE, &rlim);
2983 /* Child was killed by a signal, mimic that. */
2985 signal(exit_code, SIG_DFL);
2986 #ifdef ENABLE_COVERAGE_GCOV
2991 /* Unblock the signal. */
2994 sigaddset(&mask, exit_code);
2995 #ifdef ENABLE_COVERAGE_GCOV
2998 sigprocmask(SIG_UNBLOCK, &mask, NULL);
3000 /* Paranoia - what if this signal is not fatal?
3001 Exit with 128 + signo then. */
3008 main(int argc, char *argv[])
3010 setlocale(LC_ALL, "");
3013 exit_code = !nprocs;
3015 while (dispatch_event(next_event()))