]> granicus.if.org Git - strace/blob - strace.c
Introduce seccomp-assisted syscall filtering
[strace] / strace.c
1 /*
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.
7  * All rights reserved.
8  *
9  * SPDX-License-Identifier: LGPL-2.1-or-later
10  */
11
12 #include "defs.h"
13 #include <stdarg.h>
14 #include <limits.h>
15 #include <fcntl.h>
16 #include "ptrace.h"
17 #include <signal.h>
18 #include <sys/resource.h>
19 #include <sys/stat.h>
20 #ifdef HAVE_PATHS_H
21 # include <paths.h>
22 #endif
23 #include <getopt.h>
24 #include <pwd.h>
25 #include <grp.h>
26 #include <dirent.h>
27 #include <locale.h>
28 #include <sys/utsname.h>
29 #ifdef HAVE_PRCTL
30 # include <sys/prctl.h>
31 #endif
32
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"
39 #include "scno.h"
40 #include "printsiginfo.h"
41 #include "trace_event.h"
42 #include "xstring.h"
43 #include "delay.h"
44 #include "wait.h"
45
46 /* In some libc, these aren't declared. Do it ourself: */
47 extern char **environ;
48 extern int optind;
49 extern char *optarg;
50
51 #ifdef ENABLE_STACKTRACE
52 /* if this is true do the stack trace for every system call */
53 bool stack_trace_enabled;
54 #endif
55
56 #define my_tkill(tid, sig) syscall(__NR_tkill, (tid), (sig))
57
58 /* Glue for systems without a MMU that cannot provide fork() */
59 #if !defined(HAVE_FORK)
60 # undef NOMMU_SYSTEM
61 # define NOMMU_SYSTEM 1
62 #endif
63 #if NOMMU_SYSTEM
64 # define fork() vfork()
65 #endif
66
67 const unsigned int syscall_trap_sig = SIGTRAP | 0x80;
68
69 cflag_t cflag = CFLAG_NONE;
70 unsigned int followfork;
71 unsigned int ptrace_setoptions = PTRACE_O_TRACESYSGOOD | PTRACE_O_TRACEEXEC
72                                  | PTRACE_O_TRACEEXIT;
73 unsigned int xflag;
74 bool debug_flag;
75 bool Tflag;
76 bool iflag;
77 bool count_wallclock;
78 unsigned int qflag;
79 static unsigned int tflag;
80 static bool rflag;
81 static bool print_pid_pfx;
82
83 /* -I n */
84 enum {
85         INTR_NOT_SET        = 0,
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 */
90         NUM_INTR_OPTS
91 };
92 static int opt_intr;
93 /* We play with signal mask only if this mode is active: */
94 #define interactive (opt_intr == INTR_WHILE_WAIT)
95
96 /*
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.
107  */
108 static bool daemonized_tracer;
109
110 static int post_attach_sigstop = TCB_IGNORE_ONE_SIGSTOP;
111 #define use_seize (post_attach_sigstop == 0)
112
113 /* Show path associated with fd arguments */
114 unsigned int show_fd_path;
115
116 static bool detach_on_execve;
117
118 static int exit_code;
119 static int strace_child;
120 static int strace_tracer_pid;
121
122 static const char *username;
123 static uid_t run_uid;
124 static gid_t run_gid;
125
126 unsigned int max_strlen = DEFAULT_STRLEN;
127 static int acolumn = DEFAULT_ACOLUMN;
128 static char *acolumn_spaces;
129
130 /* Default output style for xlat entities */
131 enum xlat_style xlat_verbosity = XLAT_STYLE_ABBREV;
132
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;
137
138 struct tcb *printing_tcp;
139 static struct tcb *current_tcp;
140
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 */
146 };
147
148 static struct tcb **tcbtab;
149 static unsigned int nprocs;
150 static size_t tcbtabsize;
151
152 static struct tcb_wait_data *tcb_wait_tab;
153 static size_t tcb_wait_tab_size;
154
155
156 #ifndef HAVE_PROGRAM_INVOCATION_NAME
157 char *program_invocation_name;
158 #endif
159
160 unsigned os_release; /* generated from uname()'s u.release */
161
162 static void detach(struct tcb *tcp);
163 static void cleanup(int sig);
164 static void interrupt(int sig);
165
166 #ifdef HAVE_SIG_ATOMIC_T
167 static volatile sig_atomic_t interrupted, restart_failed;
168 #else
169 static volatile int interrupted, restart_failed;
170 #endif
171
172 static sigset_t timer_set;
173 static void timer_sighandler(int);
174
175 #ifndef HAVE_STRERROR
176
177 # if !HAVE_DECL_SYS_ERRLIST
178 extern int sys_nerr;
179 extern char *sys_errlist[];
180 # endif
181
182 const char *
183 strerror(int err_no)
184 {
185         static char buf[sizeof("Unknown error %d") + sizeof(int)*3];
186
187         if (err_no < 1 || err_no >= sys_nerr) {
188                 xsprintf(buf, "Unknown error %d", err_no);
189                 return buf;
190         }
191         return sys_errlist[err_no];
192 }
193
194 #endif /* HAVE_STERRROR */
195
196 static void
197 print_version(void)
198 {
199         static const char features[] =
200 #ifdef ENABLE_STACKTRACE
201                 " stack-trace=" USE_UNWINDER
202 #endif
203 #ifdef USE_DEMANGLE
204                 " stack-demangle"
205 #endif
206 #if SUPPORTED_PERSONALITIES > 1
207 # if defined HAVE_M32_MPERS
208                 " m32-mpers"
209 # else
210                 " no-m32-mpers"
211 # endif
212 #endif /* SUPPORTED_PERSONALITIES > 1 */
213 #if SUPPORTED_PERSONALITIES > 2
214 # if defined HAVE_MX32_MPERS
215                 " mx32-mpers"
216 # else
217                 " no-mx32-mpers"
218 # endif
219 #endif /* SUPPORTED_PERSONALITIES > 2 */
220                 "";
221
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)");
229 }
230
231 static void
232 usage(void)
233 {
234 #ifdef ENABLE_STACKTRACE
235 # define K_OPT "k"
236 #else
237 # define K_OPT ""
238 #endif
239
240         printf("\
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\
248 \n\
249 Output format:\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\
253 "
254 #ifdef ENABLE_STACKTRACE
255 "\
256   -k             obtain stack trace between each syscall\n\
257 "
258 #endif
259 "\
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\
274                  file descriptors\n\
275 \n\
276 Statistics:\n\
277   -c             count time, calls, and errors for each syscall and report\n\
278                  summary\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\
282                  (default %s)\n\
283   -w             summarise syscall latency (default is system time)\n\
284 \n\
285 Filtering:\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\
292 \n\
293 Tracing:\n\
294   -b execve      detach on execve syscall\n\
295   -D             run tracer process as a detached grandchild, not as parent\n\
296   -f             follow forks\n\
297   -ff            follow forks with output into separate files\n\
298   -I interruptible\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\
304 \n\
305 Startup:\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\
310 \n\
311 Miscellaneous:\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\
316 "
317 /* ancient, no one should use it
318 -F -- attempt to follow vforks (deprecated, use -f)\n\
319  */
320 , DEFAULT_ACOLUMN, DEFAULT_STRLEN, DEFAULT_SORTBY);
321         exit(0);
322
323 #undef K_OPT
324 }
325
326 void ATTRIBUTE_NORETURN
327 die(void)
328 {
329         if (strace_tracer_pid == getpid()) {
330                 cleanup(0);
331                 exit(1);
332         }
333
334         _exit(1);
335 }
336
337 static void
338 error_opt_arg(int opt, const char *arg)
339 {
340         error_msg_and_help("invalid -%c argument: '%s'", opt, arg);
341 }
342
343 static const char *ptrace_attach_cmd;
344
345 static int
346 ptrace_attach_or_seize(int pid)
347 {
348         int r;
349         if (!use_seize)
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);
353         if (r)
354                 return ptrace_attach_cmd = "PTRACE_SEIZE", r;
355         r = ptrace(PTRACE_INTERRUPT, pid, 0L, 0L);
356         return ptrace_attach_cmd = "PTRACE_INTERRUPT", r;
357 }
358
359 static const char *
360 ptrace_op_str(unsigned int op)
361 {
362         const char *str = xlookup(ptrace_cmds, op);
363         if (str)
364                 return str;
365
366         static char buf[sizeof(op) * 3];
367         xsprintf(buf, "%u", op);
368         return buf;
369 }
370
371 /*
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.
377  */
378 static int
379 ptrace_restart(const unsigned int op, struct tcb *const tcp, unsigned int sig)
380 {
381         int err;
382
383         errno = 0;
384         ptrace(op, tcp->pid, 0L, (unsigned long) sig);
385         err = errno;
386         if (!err || err == ESRCH)
387                 return 0;
388
389         /*
390          * Why curcol != 0? Otherwise sometimes we get this:
391          *
392          * 10252 kill(10253, SIGKILL)              = 0
393          *  <ptrace(SYSCALL,10252):No such process>10253 ...next decode...
394          *
395          * 10252 died after we retrieved syscall exit data,
396          * but before we tried to restart it. Log looks ugly.
397          */
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));
401                 line_ended();
402         }
403         errno = err;
404         perror_msg("ptrace(%s,pid:%d,sig:%u)",
405                    ptrace_op_str(op), tcp->pid, sig);
406         return -1;
407 }
408
409 static void
410 set_cloexec_flag(int fd)
411 {
412         int flags, newflags;
413
414         flags = fcntl(fd, F_GETFD);
415         if (flags < 0) {
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.
420                  */
421                 perror_msg_and_die("fcntl(%d, F_GETFD)", fd);
422         }
423
424         newflags = flags | FD_CLOEXEC;
425         if (flags == newflags)
426                 return;
427
428         if (fcntl(fd, F_SETFD, newflags)) /* never fails */
429                 perror_msg_and_die("fcntl(%d, F_SETFD, %#x)", fd, newflags);
430 }
431
432 /*
433  * When strace is setuid executable, we have to swap uids
434  * before and after filesystem and process management operations.
435  */
436 static void
437 swap_uid(void)
438 {
439         int euid = geteuid(), uid = getuid();
440
441         if (euid != uid && setreuid(euid, uid) < 0) {
442                 perror_msg_and_die("setreuid");
443         }
444 }
445
446 static FILE *
447 strace_fopen(const char *path)
448 {
449         FILE *fp;
450
451         swap_uid();
452         fp = fopen_stream(path, open_append ? "a" : "w");
453         if (!fp)
454                 perror_msg_and_die("Can't fopen '%s'", path);
455         swap_uid();
456         set_cloexec_flag(fileno(fp));
457         return fp;
458 }
459
460 static int popen_pid;
461
462 #ifndef _PATH_BSHELL
463 # define _PATH_BSHELL "/bin/sh"
464 #endif
465
466 /*
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.
470  */
471 static FILE *
472 strace_popen(const char *command)
473 {
474         FILE *fp;
475         int pid;
476         int fds[2];
477
478         swap_uid();
479         if (pipe(fds) < 0)
480                 perror_msg_and_die("pipe");
481
482         set_cloexec_flag(fds[1]); /* never fails */
483
484         pid = vfork();
485         if (pid < 0)
486                 perror_msg_and_die("vfork");
487
488         if (pid == 0) {
489                 /* child */
490                 close(fds[1]);
491                 if (fds[0] != 0) {
492                         if (dup2(fds[0], 0))
493                                 perror_msg_and_die("dup2");
494                         close(fds[0]);
495                 }
496                 execl(_PATH_BSHELL, "sh", "-c", command, NULL);
497                 perror_msg_and_die("Can't execute '%s'", _PATH_BSHELL);
498         }
499
500         /* parent */
501         popen_pid = pid;
502         close(fds[0]);
503         swap_uid();
504         fp = fdopen(fds[1], "w");
505         if (!fp)
506                 perror_msg_and_die("fdopen");
507         return fp;
508 }
509
510 static void
511 outf_perror(const struct tcb * const tcp)
512 {
513         if (tcp->outf == stderr)
514                 return;
515
516         /* This is ugly, but we don't store separate file names */
517         if (followfork >= 2)
518                 perror_msg("%s.%u", outfname, tcp->pid);
519         else
520                 perror_msg("%s", outfname);
521 }
522
523 ATTRIBUTE_FORMAT((printf, 1, 0))
524 static void
525 tvprintf(const char *const fmt, va_list args)
526 {
527         if (current_tcp) {
528                 int n = vfprintf(current_tcp->outf, fmt, args);
529                 if (n < 0) {
530                         /* very unlikely due to vfprintf buffering */
531                         outf_perror(current_tcp);
532                 } else
533                         current_tcp->curcol += n;
534         }
535 }
536
537 void
538 tprintf(const char *fmt, ...)
539 {
540         va_list args;
541         va_start(args, fmt);
542         tvprintf(fmt, args);
543         va_end(args);
544 }
545
546 #ifndef HAVE_FPUTS_UNLOCKED
547 # define fputs_unlocked fputs
548 #endif
549
550 void
551 tprints(const char *str)
552 {
553         if (current_tcp) {
554                 int n = fputs_unlocked(str, current_tcp->outf);
555                 if (n >= 0) {
556                         current_tcp->curcol += strlen(str);
557                         return;
558                 }
559                 /* very unlikely due to fputs_unlocked buffering */
560                 outf_perror(current_tcp);
561         }
562 }
563
564 void
565 tprints_comment(const char *const str)
566 {
567         if (str && *str)
568                 tprintf(" /* %s */", str);
569 }
570
571 void
572 tprintf_comment(const char *fmt, ...)
573 {
574         if (!fmt || !*fmt)
575                 return;
576
577         va_list args;
578         va_start(args, fmt);
579         tprints(" /* ");
580         tvprintf(fmt, args);
581         tprints(" */");
582         va_end(args);
583 }
584
585 static void
586 flush_tcp_output(const struct tcb *const tcp)
587 {
588         if (fflush(tcp->outf))
589                 outf_perror(tcp);
590 }
591
592 void
593 line_ended(void)
594 {
595         if (current_tcp) {
596                 current_tcp->curcol = 0;
597                 flush_tcp_output(current_tcp);
598         }
599         if (printing_tcp) {
600                 printing_tcp->curcol = 0;
601                 printing_tcp = NULL;
602         }
603 }
604
605 void
606 set_current_tcp(const struct tcb *tcp)
607 {
608         current_tcp = (struct tcb *) tcp;
609
610         /* Sync current_personality and stuff */
611         if (current_tcp)
612                 set_personality(current_tcp->currpers);
613 }
614
615 void
616 printleader(struct tcb *tcp)
617 {
618         /* If -ff, "previous tcb we printed" is always the same as current,
619          * because we have per-tcb output files.
620          */
621         if (followfork >= 2)
622                 printing_tcp = tcp;
623
624         if (printing_tcp) {
625                 set_current_tcp(printing_tcp);
626                 if (!tcp->staged_output_data && printing_tcp->curcol != 0 &&
627                     (followfork < 2 || printing_tcp == tcp)) {
628                         /*
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).
633                          */
634                         tprints(" <unfinished ...>\n");
635                         printing_tcp->curcol = 0;
636                 }
637         }
638
639         printing_tcp = tcp;
640         set_current_tcp(tcp);
641         current_tcp->curcol = 0;
642
643         if (print_pid_pfx)
644                 tprintf("%-5d ", tcp->pid);
645         else if (nprocs > 1 && !outfname)
646                 tprintf("[pid %5u] ", tcp->pid);
647
648         if (tflag) {
649                 struct timespec ts;
650                 clock_gettime(CLOCK_REALTIME, &ts);
651
652                 if (tflag > 2) {
653                         tprintf("%lld.%06ld ",
654                                 (long long) ts.tv_sec, (long) ts.tv_nsec / 1000);
655                 } else {
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);
659
660                         if (tm)
661                                 strftime(str, sizeof(str), "%T", tm);
662                         else
663                                 xsprintf(str, "%lld", (long long) local);
664                         if (tflag > 1)
665                                 tprintf("%s.%06ld ",
666                                         str, (long) ts.tv_nsec / 1000);
667                         else
668                                 tprintf("%s ", str);
669                 }
670         }
671
672         if (rflag) {
673                 struct timespec ts;
674                 clock_gettime(CLOCK_MONOTONIC, &ts);
675
676                 static struct timespec ots;
677                 if (ots.tv_sec == 0)
678                         ots = ts;
679
680                 struct timespec dts;
681                 ts_sub(&dts, &ts, &ots);
682                 ots = ts;
683
684                 tprintf("%s%6ld.%06ld%s ",
685                         tflag ? "(+" : "",
686                         (long) dts.tv_sec, (long) dts.tv_nsec / 1000,
687                         tflag ? ")" : "");
688         }
689
690         if (iflag)
691                 print_instruction_pointer(tcp);
692 }
693
694 void
695 tabto(void)
696 {
697         if (current_tcp->curcol < acolumn)
698                 tprints(acolumn_spaces + current_tcp->curcol);
699 }
700
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.
704  */
705 static void
706 after_successful_attach(struct tcb *tcp, const unsigned int flags)
707 {
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) {
711                 char name[PATH_MAX];
712                 xsprintf(name, "%s.%u", outfname, tcp->pid);
713                 tcp->outf = strace_fopen(name);
714         }
715
716 #ifdef ENABLE_STACKTRACE
717         if (stack_trace_enabled)
718                 unwind_tcb_init(tcp);
719 #endif
720 }
721
722 static void
723 expand_tcbtab(void)
724 {
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;
731         struct tcb *newtcbs;
732         struct tcb **tcb_ptr;
733
734         old_tcbtabsize = tcbtabsize;
735
736         tcbtab = xgrowarray(tcbtab, &tcbtabsize, sizeof(tcbtab[0]));
737         newtcbs = xcalloc(tcbtabsize - old_tcbtabsize, sizeof(newtcbs[0]));
738
739         for (tcb_ptr = tcbtab + old_tcbtabsize;
740             tcb_ptr < tcbtab + tcbtabsize; tcb_ptr++, newtcbs++)
741                 *tcb_ptr = newtcbs;
742 }
743
744 static struct tcb *
745 alloctcb(int pid)
746 {
747         unsigned int i;
748         struct tcb *tcp;
749
750         if (nprocs == tcbtabsize)
751                 expand_tcbtab();
752
753         for (i = 0; i < tcbtabsize; i++) {
754                 tcp = tcbtab[i];
755                 if (!tcp->pid) {
756                         memset(tcp, 0, sizeof(*tcp));
757                         list_init(&tcp->wait_list);
758                         tcp->pid = pid;
759 #if SUPPORTED_PERSONALITIES > 1
760                         tcp->currpers = current_personality;
761 #endif
762                         nprocs++;
763                         debug_msg("new tcb for pid %d, active tcbs:%d",
764                                   tcp->pid, nprocs);
765                         return tcp;
766                 }
767         }
768         error_msg_and_die("bug in alloctcb");
769 }
770
771 void *
772 get_tcb_priv_data(const struct tcb *tcp)
773 {
774         return tcp->_priv_data;
775 }
776
777 int
778 set_tcb_priv_data(struct tcb *tcp, void *const priv_data,
779                   void (*const free_priv_data)(void *))
780 {
781         if (tcp->_priv_data)
782                 return -1;
783
784         tcp->_free_priv_data = free_priv_data;
785         tcp->_priv_data = priv_data;
786
787         return 0;
788 }
789
790 void
791 free_tcb_priv_data(struct tcb *tcp)
792 {
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;
797                 }
798                 tcp->_priv_data = NULL;
799         }
800 }
801
802 static void
803 droptcb(struct tcb *tcp)
804 {
805         if (tcp->pid == 0)
806                 return;
807
808         if (cflag && debug_flag) {
809                 struct timespec dt;
810
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));
814         }
815
816         int p;
817         for (p = 0; p < SUPPORTED_PERSONALITIES; ++p)
818                 free(tcp->inject_vec[p]);
819
820         free_tcb_priv_data(tcp);
821
822 #ifdef ENABLE_STACKTRACE
823         if (stack_trace_enabled)
824                 unwind_tcb_fin(tcp);
825 #endif
826
827 #ifdef HAVE_LINUX_KVM_H
828         kvm_vcpu_info_free(tcp);
829 #endif
830
831         if (tcp->mmap_cache)
832                 tcp->mmap_cache->free_fn(tcp, __func__);
833
834         nprocs--;
835         debug_msg("dropped tcb for pid %d, %d remain", tcp->pid, nprocs);
836
837         if (tcp->outf) {
838                 bool publish = true;
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);
842                 }
843
844                 if (followfork >= 2) {
845                         if (tcp->curcol != 0 && publish)
846                                 fprintf(tcp->outf, " <detached ...>\n");
847                         fclose(tcp->outf);
848                 } else {
849                         if (printing_tcp == tcp && tcp->curcol != 0 && publish)
850                                 fprintf(tcp->outf, " <detached ...>\n");
851                         flush_tcp_output(tcp);
852                 }
853         }
854
855         if (current_tcp == tcp)
856                 set_current_tcp(NULL);
857         if (printing_tcp == tcp)
858                 printing_tcp = NULL;
859
860         list_remove(&tcp->wait_list);
861
862         memset(tcp, 0, sizeof(*tcp));
863 }
864
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.
869  */
870 static void
871 detach(struct tcb *tcp)
872 {
873         int error;
874         int status;
875
876         /*
877          * Linux wrongly insists the child be stopped
878          * before detaching.  Arghh.  We go through hoops
879          * to make a clean break of things.
880          */
881
882         if (!(tcp->flags & TCB_ATTACHED))
883                 goto drop;
884
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).
888          */
889         if (tcp->flags & TCB_IGNORE_ONE_SIGSTOP)
890                 goto wait_loop;
891
892         error = ptrace(PTRACE_DETACH, tcp->pid, 0, 0);
893         if (!error) {
894                 /* On a clear day, you can see forever. */
895                 goto drop;
896         }
897         if (errno != ESRCH) {
898                 /* Shouldn't happen. */
899                 perror_func_msg("ptrace(PTRACE_DETACH,%u)", tcp->pid);
900                 goto drop;
901         }
902         /* ESRCH: process is either not stopped or doesn't exist. */
903         if (my_tkill(tcp->pid, 0) < 0) {
904                 if (errno != ESRCH)
905                         /* Shouldn't happen. */
906                         perror_func_msg("tkill(%u,0)", tcp->pid);
907                 /* else: process doesn't exist. */
908                 goto drop;
909         }
910         /* Process is not stopped, need to stop it. */
911         if (use_seize) {
912                 /*
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>".
917                  */
918                 error = ptrace(PTRACE_INTERRUPT, tcp->pid, 0, 0);
919                 if (!error)
920                         goto wait_loop;
921                 if (errno != ESRCH)
922                         perror_func_msg("ptrace(PTRACE_INTERRUPT,%u)", tcp->pid);
923         } else {
924                 error = my_tkill(tcp->pid, SIGSTOP);
925                 if (!error)
926                         goto wait_loop;
927                 if (errno != ESRCH)
928                         perror_func_msg("tkill(%u,SIGSTOP)", tcp->pid);
929         }
930         /* Either process doesn't exist, or some weird error. */
931         goto drop;
932
933  wait_loop:
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)
938          */
939         for (;;) {
940                 unsigned int sig;
941                 if (waitpid(tcp->pid, &status, __WALL) < 0) {
942                         if (errno == EINTR)
943                                 continue;
944                         /*
945                          * if (errno == ECHILD) break;
946                          * ^^^  WRONG! We expect this PID to exist,
947                          * and want to emit a message otherwise:
948                          */
949                         perror_func_msg("waitpid(%u)", tcp->pid);
950                         break;
951                 }
952                 if (!WIFSTOPPED(status)) {
953                         /*
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.
959                          *
960                          * However, we _can_ end up here if tracee
961                          * was SIGKILLed.
962                          */
963                         break;
964                 }
965                 sig = WSTOPSIG(status);
966                 debug_msg("detach wait: event:%d sig:%d",
967                           (unsigned) status >> 16, sig);
968                 if (use_seize) {
969                         unsigned event = (unsigned)status >> 16;
970                         if (event == PTRACE_EVENT_STOP /*&& sig == SIGTRAP*/) {
971                                 /*
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.
977                                  */
978                                 sig = 0;
979                         }
980                         /*
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.
989                          */
990                         if (sig == syscall_trap_sig)
991                                 sig = 0;
992                         /* else: not sure in which case we can be here.
993                          * Signal stop? Inject it while detaching.
994                          */
995                         ptrace_restart(PTRACE_DETACH, tcp, sig);
996                         break;
997                 }
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);
1003                         break;
1004                 }
1005                 if (sig == syscall_trap_sig)
1006                         sig = 0;
1007                 /* Can't detach just yet, may need to wait for SIGSTOP */
1008                 error = ptrace_restart(PTRACE_CONT, tcp, sig);
1009                 if (error < 0) {
1010                         /* Should not happen.
1011                          * Note: ptrace_restart returns 0 on ESRCH, so it's not it.
1012                          * ptrace_restart already emitted error message.
1013                          */
1014                         break;
1015                 }
1016         }
1017
1018  drop:
1019         if (!qflag && (tcp->flags & TCB_ATTACHED))
1020                 error_msg("Process %u detached", tcp->pid);
1021
1022         droptcb(tcp);
1023 }
1024
1025 static void
1026 process_opt_p_list(char *opt)
1027 {
1028         while (*opt) {
1029                 /*
1030                  * We accept -p PID,PID; -p "`pidof PROG`"; -p "`pgrep PROG`".
1031                  * pidof uses space as delim, pgrep uses newline. :(
1032                  */
1033                 int pid;
1034                 char *delim = opt + strcspn(opt, "\n\t ,");
1035                 char c = *delim;
1036
1037                 *delim = '\0';
1038                 pid = string_to_uint(opt);
1039                 if (pid <= 0) {
1040                         error_msg_and_die("Invalid process id: '%s'", opt);
1041                 }
1042                 if (pid == strace_tracer_pid) {
1043                         error_msg_and_die("I'm sorry, I can't let you do that, Dave.");
1044                 }
1045                 *delim = c;
1046                 alloctcb(pid);
1047                 if (c == '\0')
1048                         break;
1049                 opt = delim + 1;
1050         }
1051 }
1052
1053 static void
1054 attach_tcb(struct tcb *const tcp)
1055 {
1056         if (ptrace_attach_or_seize(tcp->pid) < 0) {
1057                 perror_msg("attach: ptrace(%s, %d)",
1058                            ptrace_attach_cmd, tcp->pid);
1059                 droptcb(tcp);
1060                 return;
1061         }
1062
1063         after_successful_attach(tcp, TCB_GRABBED | post_attach_sigstop);
1064         debug_msg("attach to pid %d (main) succeeded", tcp->pid);
1065
1066         static const char task_path[] = "/proc/%d/task";
1067         char procdir[sizeof(task_path) + sizeof(int) * 3];
1068         DIR *dir;
1069         unsigned int ntid = 0, nerr = 0;
1070
1071         if (followfork && tcp->pid != strace_child &&
1072             xsprintf(procdir, task_path, tcp->pid) > 0 &&
1073             (dir = opendir(procdir)) != NULL) {
1074                 struct_dirent *de;
1075
1076                 while ((de = read_dir(dir)) != NULL) {
1077                         if (de->d_fileno == 0)
1078                                 continue;
1079
1080                         int tid = string_to_uint(de->d_name);
1081                         if (tid <= 0 || tid == tcp->pid)
1082                                 continue;
1083
1084                         ++ntid;
1085                         if (ptrace_attach_or_seize(tid) < 0) {
1086                                 ++nerr;
1087                                 debug_perror_msg("attach: ptrace(%s, %d)",
1088                                                  ptrace_attach_cmd, tid);
1089                                 continue;
1090                         }
1091
1092                         after_successful_attach(alloctcb(tid),
1093                                                 TCB_GRABBED | post_attach_sigstop);
1094                         debug_msg("attach to pid %d succeeded", tid);
1095                 }
1096
1097                 closedir(dir);
1098         }
1099
1100         if (!qflag) {
1101                 if (ntid > nerr)
1102                         error_msg("Process %u attached"
1103                                   " with %u threads",
1104                                   tcp->pid, ntid - nerr + 1);
1105                 else
1106                         error_msg("Process %u attached",
1107                                   tcp->pid);
1108         }
1109 }
1110
1111 static void
1112 startup_attach(void)
1113 {
1114         pid_t parent_pid = strace_tracer_pid;
1115         unsigned int tcbi;
1116         struct tcb *tcp;
1117
1118         if (daemonized_tracer) {
1119                 pid_t pid = fork();
1120                 if (pid < 0)
1121                         perror_func_msg_and_die("fork");
1122
1123                 if (pid) { /* parent */
1124                         /*
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.
1129                          */
1130                         pause();
1131                         _exit(0); /* paranoia */
1132                 }
1133                 /* grandchild */
1134                 /* We will be the tracer process. Remember our new pid: */
1135                 strace_tracer_pid = getpid();
1136         }
1137
1138         for (tcbi = 0; tcbi < tcbtabsize; tcbi++) {
1139                 tcp = tcbtab[tcbi];
1140
1141                 if (!tcp->pid)
1142                         continue;
1143
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 */
1147
1148                 if (tcp->pid == parent_pid || tcp->pid == strace_tracer_pid) {
1149                         errno = EPERM;
1150                         perror_msg("attach: pid %d", tcp->pid);
1151                         droptcb(tcp);
1152                         continue;
1153                 }
1154
1155                 attach_tcb(tcp);
1156
1157                 if (interrupted)
1158                         return;
1159         } /* for each tcbtab[] */
1160
1161         if (daemonized_tracer) {
1162                 /*
1163                  * Make parent go away.
1164                  * Also makes grandparent's wait() unblock.
1165                  */
1166                 kill(parent_pid, SIGKILL);
1167                 strace_child = 0;
1168         }
1169 }
1170
1171 /* Stack-o-phobic exec helper, in the hope to work around
1172  * NOMMU + "daemonized tracer" difficulty.
1173  */
1174 struct exec_params {
1175         int fd_to_close;
1176         uid_t run_euid;
1177         gid_t run_egid;
1178         char **argv;
1179         char *pathname;
1180         struct sigaction child_sa;
1181 };
1182 static struct exec_params params_for_tracee;
1183
1184 static void ATTRIBUTE_NOINLINE ATTRIBUTE_NORETURN
1185 exec_or_die(void)
1186 {
1187         struct exec_params *params = &params_for_tracee;
1188
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, ...)");
1194                 }
1195         }
1196
1197         if (username != NULL) {
1198                 /*
1199                  * It is important to set groups before we
1200                  * lose privileges on setuid.
1201                  */
1202                 if (initgroups(username, run_gid) < 0) {
1203                         perror_msg_and_die("initgroups");
1204                 }
1205                 if (setregid(run_gid, params->run_egid) < 0) {
1206                         perror_msg_and_die("setregid");
1207                 }
1208                 if (setreuid(run_uid, params->run_euid) < 0) {
1209                         perror_msg_and_die("setreuid");
1210                 }
1211         } else if (geteuid() != 0)
1212                 if (setreuid(run_uid, run_uid) < 0) {
1213                         perror_msg_and_die("setreuid");
1214                 }
1215
1216         if (!daemonized_tracer) {
1217                 /*
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.
1223                  */
1224                 if (!NOMMU_SYSTEM)
1225                         kill(getpid(), SIGSTOP);
1226         } else {
1227                 alarm(3);
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 */
1230                 wait(NULL);
1231                 alarm(0);
1232         }
1233
1234         if (params_for_tracee.child_sa.sa_handler != SIG_DFL)
1235                 sigaction(SIGCHLD, &params_for_tracee.child_sa, NULL);
1236
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");
1243 }
1244
1245 /*
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.
1250  */
1251 static int
1252 open_dummy_desc(void)
1253 {
1254         int fds[2];
1255
1256         if (pipe(fds))
1257                 perror_func_msg_and_die("pipe");
1258         close(fds[1]);
1259         set_cloexec_flag(fds[0]);
1260         return fds[0];
1261 }
1262
1263 /* placeholder fds status for stdin and stdout */
1264 static bool fd_is_placeholder[2];
1265
1266 /*
1267  * Ensure that all standard file descriptors are open by opening placeholder
1268  * file descriptors for those standard file descriptors that are not open.
1269  *
1270  * The information which descriptors have been made open is saved
1271  * in fd_is_placeholder for later use.
1272  */
1273 static void
1274 ensure_standard_fds_opened(void)
1275 {
1276         int fd;
1277
1278         while ((fd = open_dummy_desc()) <= 2) {
1279                 if (fd == 2)
1280                         break;
1281                 fd_is_placeholder[fd] = true;
1282         }
1283
1284         if (fd > 2)
1285                 close(fd);
1286 }
1287
1288 /*
1289  * Redirect stdin and stdout unless they have been opened earlier
1290  * by ensure_standard_fds_opened as placeholders.
1291  */
1292 static void
1293 redirect_standard_fds(void)
1294 {
1295         int i;
1296
1297         /*
1298          * It might be a good idea to redirect stderr as well,
1299          * but we sometimes need to print error messages.
1300          */
1301         for (i = 0; i <= 1; ++i) {
1302                 if (!fd_is_placeholder[i]) {
1303                         close(i);
1304                         open_dummy_desc();
1305                 }
1306         }
1307 }
1308
1309 static void
1310 startup_child(char **argv)
1311 {
1312         strace_stat_t statbuf;
1313         const char *filename;
1314         size_t filename_len;
1315         char pathname[PATH_MAX];
1316         int pid;
1317         struct tcb *tcp;
1318
1319         filename = argv[0];
1320         filename_len = strlen(filename);
1321
1322         if (filename_len > sizeof(pathname) - 1) {
1323                 errno = ENAMETOOLONG;
1324                 perror_msg_and_die("exec");
1325         }
1326         if (strchr(filename, '/')) {
1327                 strcpy(pathname, filename);
1328         }
1329 #ifdef USE_DEBUGGING_EXEC
1330         /*
1331          * Debuggers customarily check the current directory
1332          * first regardless of the path but doing that gives
1333          * security geeks a panic attack.
1334          */
1335         else if (stat_file(filename, &statbuf) == 0)
1336                 strcpy(pathname, filename);
1337 #endif /* USE_DEBUGGING_EXEC */
1338         else {
1339                 const char *path;
1340                 size_t m, n, len;
1341
1342                 for (path = getenv("PATH"); path && *path; path += m) {
1343                         const char *colon = strchr(path, ':');
1344                         if (colon) {
1345                                 n = colon - path;
1346                                 m = n + 1;
1347                         } else
1348                                 m = n = strlen(path);
1349                         if (n == 0) {
1350                                 if (!getcwd(pathname, PATH_MAX))
1351                                         continue;
1352                                 len = strlen(pathname);
1353                         } else if (n > sizeof(pathname) - 1)
1354                                 continue;
1355                         else {
1356                                 strncpy(pathname, path, n);
1357                                 len = n;
1358                         }
1359                         if (len && pathname[len - 1] != '/')
1360                                 pathname[len++] = '/';
1361                         if (filename_len + len > sizeof(pathname) - 1)
1362                                 continue;
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))
1370                                 break;
1371                 }
1372                 if (!path || !*path)
1373                         pathname[0] = '\0';
1374         }
1375         if (stat_file(pathname, &statbuf) < 0) {
1376                 perror_msg_and_die("Can't stat '%s'", filename);
1377         }
1378
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;
1383         /*
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.
1386          */
1387         params_for_tracee.pathname = NOMMU_SYSTEM ? xstrdup(pathname) : pathname;
1388
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);
1392 #endif
1393
1394         pid = fork();
1395         if (pid < 0)
1396                 perror_func_msg_and_die("fork");
1397
1398         if ((pid != 0 && daemonized_tracer)
1399          || (pid == 0 && !daemonized_tracer)
1400         ) {
1401                 /* We are to become the tracee. Two cases:
1402                  * -D: we are parent
1403                  * not -D: we are child
1404                  */
1405                 exec_or_die();
1406         }
1407
1408         /* We are the tracer */
1409
1410         if (!daemonized_tracer) {
1411                 strace_child = pid;
1412                 if (!use_seize) {
1413                         /* child did PTRACE_TRACEME, nothing to do in parent */
1414                 } else {
1415                         if (!NOMMU_SYSTEM) {
1416                                 /* Wait until child stopped itself */
1417                                 int status;
1418                                 while (waitpid(pid, &status, WSTOPPED) < 0) {
1419                                         if (errno == EINTR)
1420                                                 continue;
1421                                         perror_msg_and_die("waitpid");
1422                                 }
1423                                 if (!WIFSTOPPED(status) || WSTOPSIG(status) != SIGSTOP) {
1424                                         kill_save_errno(pid, SIGKILL);
1425                                         perror_msg_and_die("Unexpected wait status %#x",
1426                                                            status);
1427                                 }
1428                         }
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...
1432                          */
1433
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);
1438                         }
1439                         if (!NOMMU_SYSTEM)
1440                                 kill(pid, SIGCONT);
1441                 }
1442                 tcp = alloctcb(pid);
1443                 after_successful_attach(tcp, TCB_SKIP_DETACH_ON_FIRST_EXEC
1444                                              | (NOMMU_SYSTEM ? 0
1445                                                 : (TCB_HIDE_LOG
1446                                                    | post_attach_sigstop)));
1447         } else {
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;
1453                 /*
1454                  * Attaching will be done later, by startup_attach.
1455                  * Note: we don't do after_successful_attach() here either!
1456                  */
1457
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.
1461                  *
1462                  * We work around it
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).
1474                  *
1475                  * A cleaner solution is to use makecontext + setcontext
1476                  * to create a genuine separate stack and execute on it.
1477                  */
1478         }
1479
1480         if (seccomp_filtering)
1481                 tcp->flags |= TCB_SECCOMP_FILTER;
1482
1483         /*
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.
1489          *
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").
1493          */
1494         redirect_standard_fds();
1495 }
1496
1497 static void
1498 test_ptrace_seize(void)
1499 {
1500         int pid;
1501
1502         /* Need fork for test. NOMMU has no forks */
1503         if (NOMMU_SYSTEM) {
1504                 post_attach_sigstop = 0; /* this sets use_seize to 1 */
1505                 return;
1506         }
1507
1508         pid = fork();
1509         if (pid < 0)
1510                 perror_func_msg_and_die("fork");
1511
1512         if (pid == 0) {
1513                 pause();
1514                 _exit(0);
1515         }
1516
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.
1520          */
1521         if (ptrace(PTRACE_SEIZE, pid, 0, 0) == 0) {
1522                 post_attach_sigstop = 0; /* this sets use_seize to 1 */
1523         } else {
1524                 debug_msg("PTRACE_SEIZE doesn't work");
1525         }
1526
1527         kill(pid, SIGKILL);
1528
1529         while (1) {
1530                 int status, tracee_pid;
1531
1532                 errno = 0;
1533                 tracee_pid = waitpid(pid, &status, 0);
1534                 if (tracee_pid <= 0) {
1535                         if (errno == EINTR)
1536                                 continue;
1537                         perror_func_msg_and_die("unexpected wait result %d",
1538                                                 tracee_pid);
1539                 }
1540                 if (WIFSIGNALED(status))
1541                         return;
1542
1543                 error_func_msg_and_die("unexpected wait status %#x", status);
1544         }
1545 }
1546
1547 static unsigned int
1548 get_os_release(void)
1549 {
1550         struct utsname u;
1551         if (uname(&u) < 0)
1552                 perror_msg_and_die("uname");
1553         /*
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".
1557          */
1558         const char *p = u.release;
1559         unsigned int rel = 0;
1560         for (unsigned int parts = 0; parts < 3; ++parts) {
1561                 unsigned int n = 0;
1562                 for (; (*p >= '0') && (*p <= '9'); ++p) {
1563                         n *= 10;
1564                         n += *p - '0';
1565                 }
1566                 rel <<= 8;
1567                 rel |= n;
1568                 if (*p == '.')
1569                         ++p;
1570         }
1571         return rel;
1572 }
1573
1574 static void
1575 set_sighandler(int signo, void (*sighandler)(int), struct sigaction *oldact)
1576 {
1577         const struct sigaction sa = { .sa_handler = sighandler };
1578         sigaction(signo, &sa, oldact);
1579 }
1580
1581 /*
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.
1585  *
1586  * Don't want main() to inline us and defeat the reason
1587  * we have a separate function.
1588  */
1589 static void ATTRIBUTE_NOINLINE
1590 init(int argc, char *argv[])
1591 {
1592         int c, i;
1593         int optF = 0, zflags = 0;
1594
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;
1599         }
1600
1601         strace_tracer_pid = getpid();
1602
1603         os_release = get_os_release();
1604
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
1614 #endif
1615         qualify("signal=all");
1616
1617         static const char optstring[] = "+"
1618 #ifdef ENABLE_STACKTRACE
1619             "k"
1620 #endif
1621             "a:Ab:cCdDe:E:fFhiI:o:O:p:P:qrs:S:tTu:vVwxX:yzZ";
1622
1623         enum {
1624                 SECCOMP_OPTION = 0x100
1625         };
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' },
1630                 { 0, 0, 0, 0 }
1631         };
1632
1633         while ((c = getopt_long(argc, argv, optstring, longopts, NULL)) != EOF) {
1634                 switch (c) {
1635                 case 'a':
1636                         acolumn = string_to_uint(optarg);
1637                         if (acolumn < 0)
1638                                 error_opt_arg(c, optarg);
1639                         break;
1640                 case 'A':
1641                         open_append = true;
1642                         break;
1643                 case 'b':
1644                         if (strcmp(optarg, "execve") != 0)
1645                                 error_msg_and_die("Syscall '%s' for -b isn't supported",
1646                                         optarg);
1647                         detach_on_execve = 1;
1648                         break;
1649                 case 'c':
1650                         if (cflag == CFLAG_BOTH) {
1651                                 error_msg_and_help("-c and -C are mutually exclusive");
1652                         }
1653                         cflag = CFLAG_ONLY_STATS;
1654                         break;
1655                 case 'C':
1656                         if (cflag == CFLAG_ONLY_STATS) {
1657                                 error_msg_and_help("-c and -C are mutually exclusive");
1658                         }
1659                         cflag = CFLAG_BOTH;
1660                         break;
1661                 case 'd':
1662                         debug_flag = 1;
1663                         break;
1664                 case 'D':
1665                         daemonized_tracer = 1;
1666                         break;
1667                 case 'e':
1668                         qualify(optarg);
1669                         break;
1670                 case 'E':
1671                         if (putenv(optarg) < 0)
1672                                 perror_msg_and_die("putenv");
1673                         break;
1674                 case 'f':
1675                         followfork++;
1676                         break;
1677                 case 'F':
1678                         optF = 1;
1679                         break;
1680                 case 'h':
1681                         usage();
1682                         break;
1683                 case 'i':
1684                         iflag = 1;
1685                         break;
1686                 case 'I':
1687                         opt_intr = string_to_uint_upto(optarg, NUM_INTR_OPTS - 1);
1688                         if (opt_intr <= 0)
1689                                 error_opt_arg(c, optarg);
1690                         break;
1691 #ifdef ENABLE_STACKTRACE
1692                 case 'k':
1693                         stack_trace_enabled = true;
1694                         break;
1695 #endif
1696                 case 'o':
1697                         outfname = optarg;
1698                         break;
1699                 case 'O':
1700                         if (set_overhead(optarg) < 0)
1701                                 error_opt_arg(c, optarg);
1702                         break;
1703                 case 'p':
1704                         process_opt_p_list(optarg);
1705                         break;
1706                 case 'P':
1707                         pathtrace_select(optarg);
1708                         break;
1709                 case 'q':
1710                         qflag++;
1711                         break;
1712                 case 'r':
1713                         rflag = 1;
1714                         break;
1715                 case 's':
1716                         i = string_to_uint(optarg);
1717                         if (i < 0 || (unsigned int) i > -1U / 4)
1718                                 error_opt_arg(c, optarg);
1719                         max_strlen = i;
1720                         break;
1721                 case 'S':
1722                         set_sortby(optarg);
1723                         break;
1724                 case 't':
1725                         tflag++;
1726                         break;
1727                 case 'T':
1728                         Tflag = 1;
1729                         break;
1730                 case 'u':
1731                         username = optarg;
1732                         break;
1733                 case 'v':
1734                         qualify("abbrev=none");
1735                         break;
1736                 case 'V':
1737                         print_version();
1738                         exit(0);
1739                         break;
1740                 case 'w':
1741                         count_wallclock = 1;
1742                         break;
1743                 case 'x':
1744                         xflag++;
1745                         break;
1746                 case 'X':
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;
1753                         else
1754                                 error_opt_arg(c, optarg);
1755                         break;
1756                 case 'y':
1757                         show_fd_path++;
1758                         break;
1759                 case 'z':
1760                         clear_number_set_array(status_set, 1);
1761                         add_number_to_set(STATUS_SUCCESSFUL, status_set);
1762                         zflags++;
1763                         break;
1764                 case 'Z':
1765                         clear_number_set_array(status_set, 1);
1766                         add_number_to_set(STATUS_FAILED, status_set);
1767                         zflags++;
1768                         break;
1769                 case SECCOMP_OPTION:
1770                         seccomp_filtering = true;
1771                         break;
1772                 default:
1773                         error_msg_and_help(NULL);
1774                         break;
1775                 }
1776         }
1777
1778         argv += optind;
1779         argc -= optind;
1780
1781         if (argc < 0 || (!nprocs && !argc)) {
1782                 error_msg_and_help("must have PROG [ARGS] or -p PID");
1783         }
1784
1785         if (!argc && daemonized_tracer) {
1786                 error_msg_and_help("PROG [ARGS] must be specified with -D");
1787         }
1788
1789         if (seccomp_filtering) {
1790                 if (nprocs && (!argc || debug_flag))
1791                         error_msg("--seccomp-bpf is not enabled for processes"
1792                                   " attached with -p");
1793                 if (!followfork) {
1794                         error_msg("--seccomp-bpf implies -f");
1795                         followfork = 1;
1796                 }
1797         }
1798
1799         if (optF) {
1800                 if (followfork) {
1801                         error_msg("deprecated option -F ignored");
1802                 } else {
1803                         error_msg("option -F is deprecated, "
1804                                   "please use -f instead");
1805                         followfork = optF;
1806                 }
1807         }
1808
1809         if (followfork >= 2 && cflag) {
1810                 error_msg_and_help("(-c or -C) and -ff are mutually exclusive");
1811         }
1812
1813         if (count_wallclock && !cflag) {
1814                 error_msg_and_help("-w must be given with (-c or -C)");
1815         }
1816
1817         if (cflag == CFLAG_ONLY_STATS) {
1818                 if (iflag)
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');
1822                 if (rflag)
1823                         error_msg("-%c has no effect with -c", 'r');
1824                 if (tflag)
1825                         error_msg("-%c has no effect with -c", 't');
1826                 if (Tflag)
1827                         error_msg("-%c has no effect with -c", 'T');
1828                 if (show_fd_path)
1829                         error_msg("-%c has no effect with -c", 'y');
1830         }
1831
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");
1835 #endif
1836
1837         if (zflags > 1)
1838                 error_msg("Only the last of -z/-Z options will take effect. "
1839                           "See status qualifier for more complex filters.");
1840
1841         acolumn_spaces = xmalloc(acolumn + 1);
1842         memset(acolumn_spaces, ' ', acolumn);
1843         acolumn_spaces[acolumn] = '\0';
1844
1845         set_sighandler(SIGCHLD, SIG_DFL, &params_for_tracee.child_sa);
1846
1847 #ifdef ENABLE_STACKTRACE
1848         if (stack_trace_enabled)
1849                 unwind_init();
1850 #endif
1851
1852         /* See if they want to run as another user. */
1853         if (username != NULL) {
1854                 struct passwd *pent;
1855
1856                 if (getuid() != 0 || geteuid() != 0) {
1857                         error_msg_and_die("You must be root to use the -u option");
1858                 }
1859                 pent = getpwnam(username);
1860                 if (pent == NULL) {
1861                         error_msg_and_die("Cannot find user '%s'", username);
1862                 }
1863                 run_uid = pent->pw_uid;
1864                 run_gid = pent->pw_gid;
1865         } else {
1866                 run_uid = getuid();
1867                 run_gid = getgid();
1868         }
1869
1870         if (followfork)
1871                 ptrace_setoptions |= PTRACE_O_TRACECLONE |
1872                                      PTRACE_O_TRACEFORK |
1873                                      PTRACE_O_TRACEVFORK;
1874
1875         if (seccomp_filtering)
1876                 check_seccomp_filter();
1877         if (seccomp_filtering)
1878                 ptrace_setoptions |= PTRACE_O_TRACESECCOMP;
1879
1880         debug_msg("ptrace_setoptions = %#x", ptrace_setoptions);
1881         test_ptrace_seize();
1882         test_ptrace_get_syscall_info();
1883
1884         /*
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.
1888          *
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.
1894          */
1895         ensure_standard_fds_opened();
1896
1897         /* Check if they want to redirect the output. */
1898         if (outfname) {
1899                 /* See if they want to pipe the output. */
1900                 if (outfname[0] == '|' || outfname[0] == '!') {
1901                         /*
1902                          * We can't do the <outfname>.PID funny business
1903                          * when using popen, so prohibit it.
1904                          */
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);
1914                 }
1915         } else {
1916                 /* -ff without -o FILE is the same as single -f */
1917                 if (followfork >= 2)
1918                         followfork = 1;
1919         }
1920
1921         if (!outfname || outfname[0] == '|' || outfname[0] == '!') {
1922                 setvbuf(shared_log, NULL, _IOLBF, 0);
1923         }
1924
1925         /*
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
1931          */
1932
1933         if (daemonized_tracer && !opt_intr)
1934                 opt_intr = INTR_BLOCK_TSTP_TOO;
1935         if (outfname && argc) {
1936                 if (!opt_intr)
1937                         opt_intr = INTR_NEVER;
1938                 if (!qflag)
1939                         qflag = 1;
1940         }
1941         if (!opt_intr)
1942                 opt_intr = INTR_WHILE_WAIT;
1943
1944         /*
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.
1949          */
1950         if (argc) {
1951                 startup_child(argv);
1952         }
1953
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);
1959                 /*
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.
1964                  */
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);
1970         }
1971
1972         sigemptyset(&timer_set);
1973         sigaddset(&timer_set, SIGALRM);
1974         sigprocmask(SIG_BLOCK, &timer_set, NULL);
1975         set_sighandler(SIGALRM, timer_sighandler, NULL);
1976
1977         if (nprocs != 0 || daemonized_tracer)
1978                 startup_attach();
1979
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)
1984          */
1985         print_pid_pfx = (outfname && followfork < 2 && (followfork == 1 || nprocs > 1));
1986 }
1987
1988 static struct tcb *
1989 pid2tcb(const int pid)
1990 {
1991         if (pid <= 0)
1992                 return NULL;
1993
1994 #define PID2TCB_CACHE_SIZE 1024U
1995 #define PID2TCB_CACHE_MASK (PID2TCB_CACHE_SIZE - 1)
1996
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;
2000
2001         if (tcp && tcp->pid == pid)
2002                 return tcp;
2003
2004         for (unsigned int i = 0; i < tcbtabsize; ++i) {
2005                 tcp = tcbtab[i];
2006                 if (tcp->pid == pid)
2007                         return *ptcp = tcp;
2008         }
2009
2010         return NULL;
2011 }
2012
2013 static void
2014 cleanup(int fatal_sig)
2015 {
2016         unsigned int i;
2017         struct tcb *tcp;
2018
2019         if (!fatal_sig)
2020                 fatal_sig = SIGTERM;
2021
2022         for (i = 0; i < tcbtabsize; i++) {
2023                 tcp = tcbtab[i];
2024                 if (!tcp->pid)
2025                         continue;
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);
2030                 }
2031                 detach(tcp);
2032         }
2033 }
2034
2035 static void
2036 interrupt(int sig)
2037 {
2038         interrupted = sig;
2039 }
2040
2041 static void
2042 print_debug_info(const int pid, int status)
2043 {
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];
2047
2048         strcpy(buf, "???");
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)));
2058         evbuf[0] = '\0';
2059         if (event != 0) {
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 */
2069                 };
2070                 const char *e = "??";
2071                 if (event < ARRAY_SIZE(event_names))
2072                         e = event_names[event];
2073                 else if (event == PTRACE_EVENT_STOP)
2074                         e = "STOP";
2075                 xsprintf(evbuf, ",EVENT_%s (%u)", e, event);
2076         }
2077         error_msg("[wait(0x%06x) = %u] %s%s", status, pid, buf, evbuf);
2078 }
2079
2080 static struct tcb *
2081 maybe_allocate_tcb(const int pid, int status)
2082 {
2083         if (!WIFSTOPPED(status)) {
2084                 if (detach_on_execve && pid == strace_child) {
2085                         /* example: strace -bexecve sh -c 'exec true' */
2086                         strace_child = 0;
2087                         return NULL;
2088                 }
2089                 /*
2090                  * This can happen if we inherited an unknown child.
2091                  * Example: (sleep 1 & exec strace true)
2092                  */
2093                 error_msg("Exit of unknown pid %u ignored", pid);
2094                 return NULL;
2095         }
2096         if (followfork) {
2097                 /* We assume it's a fork/vfork/clone child */
2098                 struct tcb *tcp = alloctcb(pid);
2099                 after_successful_attach(tcp, post_attach_sigstop);
2100                 if (!qflag)
2101                         error_msg("Process %d attached", pid);
2102                 return tcp;
2103         } else {
2104                 /*
2105                  * This can happen if a clone call misused CLONE_PTRACE itself.
2106                  *
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.
2110                  */
2111                 ptrace(PTRACE_DETACH, pid, NULL, 0L);
2112                 error_msg("Detached unknown pid %d", pid);
2113                 return NULL;
2114         }
2115 }
2116
2117 /*
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
2122  * leader's tcb.
2123  *
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.
2126  */
2127 static struct tcb *
2128 maybe_switch_tcbs(struct tcb *tcp, const int pid)
2129 {
2130         /*
2131          * PTRACE_GETEVENTMSG returns old pid starting from Linux 3.0.
2132          * On 2.6 and earlier it can return garbage.
2133          */
2134         if (os_release < KERNEL_VERSION(3, 0, 0))
2135                 return NULL;
2136
2137         const long old_pid = tcb_wait_tab[tcp->wait_data_idx].msg;
2138
2139         /* Avoid truncation in pid2tcb() param passing */
2140         if (old_pid <= 0 || old_pid == pid)
2141                 return NULL;
2142         if ((unsigned long) old_pid > UINT_MAX)
2143                 return NULL;
2144         struct tcb *execve_thread = pid2tcb(old_pid);
2145         /* It should be !NULL, but I feel paranoid */
2146         if (!execve_thread)
2147                 return NULL;
2148
2149         if (execve_thread->curcol != 0) {
2150                 /*
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
2155                  */
2156                 fprintf(execve_thread->outf, " <pid changed to %d ...>\n", pid);
2157                 /*execve_thread->curcol = 0; - no need, see code below */
2158         }
2159         /* Swap output FILEs and memstream (needed for -ff) */
2160         FILE *fp = execve_thread->outf;
2161         execve_thread->outf = tcp->outf;
2162         tcp->outf = fp;
2163         if (execve_thread->staged_output_data || tcp->staged_output_data) {
2164                 struct staged_output_data *staged_output_data;
2165
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;
2169         }
2170
2171         /* And their column positions */
2172         execve_thread->curcol = tcp->curcol;
2173         tcp->curcol = 0;
2174         /* Drop leader, but close execve'd thread outfile (if -ff) */
2175         droptcb(tcp);
2176         /* Switch to the thread, reusing leader's outfile and pid */
2177         tcp = execve_thread;
2178         tcp->pid = pid;
2179         if (cflag != CFLAG_ONLY_STATS) {
2180                 printleader(tcp);
2181                 tprintf("+++ superseded by execve in pid %lu +++\n", old_pid);
2182                 line_ended();
2183                 /*
2184                  * Need to reopen memstream for thread
2185                  * as we closed it in droptcb.
2186                  */
2187                 if (!is_complete_set(status_set, NUMBER_OF_STATUSES))
2188                         strace_open_memstream(tcp);
2189                 tcp->flags |= TCB_REPRINT;
2190         }
2191
2192         return tcp;
2193 }
2194
2195 static struct tcb *
2196 maybe_switch_current_tcp(void)
2197 {
2198         struct tcb *tcp = maybe_switch_tcbs(current_tcp, current_tcp->pid);
2199
2200         if (tcp)
2201                 set_current_tcp(tcp);
2202
2203         return tcp;
2204 }
2205
2206 static void
2207 print_signalled(struct tcb *tcp, const int pid, int status)
2208 {
2209         if (pid == strace_child) {
2210                 exit_code = 0x100 | WTERMSIG(status);
2211                 strace_child = 0;
2212         }
2213
2214         if (cflag != CFLAG_ONLY_STATS
2215             && is_number_in_set(WTERMSIG(status), signal_set)) {
2216                 printleader(tcp);
2217                 tprintf("+++ killed by %s %s+++\n",
2218                         sprintsigname(WTERMSIG(status)),
2219                         WCOREDUMP(status) ? "(core dumped) " : "");
2220                 line_ended();
2221         }
2222 }
2223
2224 static void
2225 print_exited(struct tcb *tcp, const int pid, int status)
2226 {
2227         if (pid == strace_child) {
2228                 exit_code = WEXITSTATUS(status);
2229                 strace_child = 0;
2230         }
2231
2232         if (cflag != CFLAG_ONLY_STATS &&
2233             qflag < 2) {
2234                 printleader(tcp);
2235                 tprintf("+++ exited with %d +++\n", WEXITSTATUS(status));
2236                 line_ended();
2237         }
2238 }
2239
2240 static void
2241 print_stopped(struct tcb *tcp, const siginfo_t *si, const unsigned int sig)
2242 {
2243         if (cflag != CFLAG_ONLY_STATS
2244             && !hide_log(tcp)
2245             && is_number_in_set(sig, signal_set)) {
2246                 printleader(tcp);
2247                 if (si) {
2248                         tprintf("--- %s ", sprintsigname(sig));
2249                         printsiginfo(si);
2250                         tprints(" ---\n");
2251                 } else
2252                         tprintf("--- stopped by %s ---\n", sprintsigname(sig));
2253                 line_ended();
2254
2255 #ifdef ENABLE_STACKTRACE
2256                 if (stack_trace_enabled)
2257                         unwind_tcb_print(tcp);
2258 #endif
2259         }
2260 }
2261
2262 static void
2263 startup_tcb(struct tcb *tcp)
2264 {
2265         debug_msg("pid %d has TCB_STARTUP, initializing it", tcp->pid);
2266
2267         tcp->flags &= ~TCB_STARTUP;
2268
2269         if (!use_seize) {
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");
2276                         }
2277                 }
2278         }
2279
2280         if ((tcp->flags & TCB_GRABBED) && (get_scno(tcp) == 1))
2281                 tcp->s_prev_ent = tcp->s_ent;
2282
2283         if (cflag) {
2284                 tcp->atime = tcp->stime;
2285         }
2286 }
2287
2288 static void
2289 print_event_exit(struct tcb *tcp)
2290 {
2291         if (entering(tcp) || filtered(tcp) || hide_log(tcp)
2292             || cflag == CFLAG_ONLY_STATS) {
2293                 return;
2294         }
2295
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);
2303         }
2304
2305         print_syscall_resume(tcp);
2306
2307         if (!(tcp->sys_func_rval & RVAL_DECODED)) {
2308                 /*
2309                  * The decoder has probably decided to print something
2310                  * on exiting syscall which is not going to happen.
2311                  */
2312                 tprints(" <unfinished ...>");
2313         }
2314
2315         printing_tcp = tcp;
2316         tprints(") ");
2317         tabto();
2318         tprints("= ?\n");
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);
2322         }
2323         line_ended();
2324 }
2325
2326 static size_t
2327 trace_wait_data_size(struct tcb *tcp)
2328 {
2329         return sizeof(struct tcb_wait_data);
2330 }
2331
2332 static struct tcb_wait_data *
2333 init_trace_wait_data(void *p)
2334 {
2335         struct tcb_wait_data *wd = p;
2336
2337         memset(wd, 0, sizeof(*wd));
2338
2339         return wd;
2340 }
2341
2342 static struct tcb_wait_data *
2343 copy_trace_wait_data(const struct tcb_wait_data *wd)
2344 {
2345         struct tcb_wait_data *new_wd = xmalloc(sizeof(*new_wd));
2346
2347         memcpy(new_wd, wd, sizeof(*wd));
2348
2349         return new_wd;
2350 }
2351
2352 static void
2353 free_trace_wait_data(struct tcb_wait_data *wd)
2354 {
2355         free(wd);
2356 }
2357
2358 static void
2359 tcb_wait_tab_check_size(const size_t size)
2360 {
2361         while (size >= tcb_wait_tab_size) {
2362                 tcb_wait_tab = xgrowarray(tcb_wait_tab,
2363                                           &tcb_wait_tab_size,
2364                                           sizeof(tcb_wait_tab[0]));
2365         }
2366 }
2367
2368 static const struct tcb_wait_data *
2369 next_event(void)
2370 {
2371         if (interrupted)
2372                 return NULL;
2373
2374         invalidate_umove_cache();
2375
2376         struct tcb *tcp = NULL;
2377         struct list_item *elem;
2378
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;
2383
2384         static struct tcb *extra_tcp;
2385         static size_t wait_extra_data_idx;
2386         /* Handle the extra tcb event.  */
2387         if (extra_tcp) {
2388                 tcp = extra_tcp;
2389                 extra_tcp = NULL;
2390                 tcp->wait_data_idx = wait_extra_data_idx;
2391
2392                 debug_msg("dequeued extra event for pid %u", tcp->pid);
2393                 goto next_event_exit;
2394         }
2395
2396         /*
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.
2406          */
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...
2412                  */
2413                 if (nprocs == 0)
2414                         return NULL;
2415         }
2416
2417         const bool unblock_delay_timer = is_delay_timer_armed();
2418
2419         /*
2420          * The window of opportunity to handle expirations
2421          * of the delay timer opens here.
2422          *
2423          * Unblock the signal handler for the delay timer
2424          * iff the delay timer is already created.
2425          */
2426         if (unblock_delay_timer)
2427                 sigprocmask(SIG_UNBLOCK, &timer_set, NULL);
2428
2429         /*
2430          * If the delay timer has expired, then its expiration
2431          * has been handled already by the signal handler.
2432          *
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.
2436          */
2437         int status;
2438         struct rusage ru;
2439         int pid = wait4(-1, &status, __WALL, (cflag ? &ru : NULL));
2440         int wait_errno = errno;
2441
2442         /*
2443          * The window of opportunity to handle expirations
2444          * of the delay timer closes here.
2445          *
2446          * Block the signal handler for the delay timer
2447          * iff it was unblocked earlier.
2448          */
2449         if (unblock_delay_timer) {
2450                 sigprocmask(SIG_BLOCK, &timer_set, NULL);
2451
2452                 if (restart_failed)
2453                         return NULL;
2454         }
2455
2456         size_t wait_tab_pos = 0;
2457         bool wait_nohang = false;
2458
2459         /*
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).
2463          */
2464         for (;;) {
2465                 struct tcb_wait_data *wd;
2466
2467                 if (pid < 0) {
2468                         if (wait_errno == EINTR)
2469                                 break;
2470                         if (wait_nohang)
2471                                 break;
2472                         if (nprocs == 0 && wait_errno == ECHILD)
2473                                 return NULL;
2474                         /*
2475                          * If nprocs > 0, ECHILD is not expected,
2476                          * treat it as any other error here:
2477                          */
2478                         errno = wait_errno;
2479                         perror_msg_and_die("wait4(__WALL)");
2480                 }
2481
2482                 if (!pid)
2483                         break;
2484
2485                 if (pid == popen_pid) {
2486                         if (!WIFSTOPPED(status))
2487                                 popen_pid = 0;
2488                         break;
2489                 }
2490
2491                 if (debug_flag)
2492                         print_debug_info(pid, status);
2493
2494                 /* Look up 'pid' in our table. */
2495                 tcp = pid2tcb(pid);
2496
2497                 if (!tcp) {
2498                         tcp = maybe_allocate_tcb(pid, status);
2499                         if (!tcp)
2500                                 goto next_event_wait_next;
2501                 }
2502
2503                 if (cflag) {
2504                         tcp->stime.tv_sec = ru.ru_stime.tv_sec;
2505                         tcp->stime.tv_nsec = ru.ru_stime.tv_usec * 1000;
2506                 }
2507
2508                 tcb_wait_tab_check_size(wait_tab_pos);
2509
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;
2514
2515                 if (WIFSIGNALED(status)) {
2516                         wd->te = TE_SIGNALLED;
2517                 } else if (WIFEXITED(status)) {
2518                         wd->te = TE_EXITED;
2519                 } else {
2520                         /*
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).
2524                          */
2525
2526                         const unsigned int sig = WSTOPSIG(status);
2527                         const unsigned int event = (unsigned int) status >> 16;
2528
2529                         switch (event) {
2530                         case 0:
2531                                 /*
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.
2537                                  */
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;
2546                                 } else {
2547                                         /*
2548                                          * True if tracee is stopped by signal
2549                                          * (as opposed to "tracee received
2550                                          * signal").
2551                                          * TODO: shouldn't we check for
2552                                          * errno == EINVAL too?
2553                                          * We can get ESRCH instead, you know...
2554                                          */
2555                                         bool stopped = ptrace(PTRACE_GETSIGINFO,
2556                                                 pid, 0, &wd->si) < 0;
2557
2558                                         wd->te = stopped ? TE_GROUP_STOP
2559                                                          : TE_SIGNAL_DELIVERY_STOP;
2560                                 }
2561                                 break;
2562                         case PTRACE_EVENT_STOP:
2563                                 /*
2564                                  * PTRACE_INTERRUPT-stop or group-stop.
2565                                  * PTRACE_INTERRUPT-stop has sig == SIGTRAP here.
2566                                  */
2567                                 switch (sig) {
2568                                 case SIGSTOP:
2569                                 case SIGTSTP:
2570                                 case SIGTTIN:
2571                                 case SIGTTOU:
2572                                         wd->te = TE_GROUP_STOP;
2573                                         break;
2574                                 default:
2575                                         wd->te = TE_RESTART;
2576                                 }
2577                                 break;
2578                         case PTRACE_EVENT_EXEC:
2579                                         /*
2580                                          * TODO: shouldn't we check for
2581                                          * errno == EINVAL here, too?
2582                                          * We can get ESRCH instead, you know...
2583                                          */
2584                                 if (ptrace(PTRACE_GETEVENTMSG, pid, NULL,
2585                                     &wd->msg) < 0)
2586                                         wd->msg = 0;
2587
2588                                 wd->te = TE_STOP_BEFORE_EXECVE;
2589                                 break;
2590                         case PTRACE_EVENT_EXIT:
2591                                 wd->te = TE_STOP_BEFORE_EXIT;
2592                                 break;
2593                         case PTRACE_EVENT_SECCOMP:
2594                                 wd->te = TE_SECCOMP;
2595                                 break;
2596                         default:
2597                                 wd->te = TE_RESTART;
2598                         }
2599                 }
2600
2601                 if (!wd->te)
2602                         error_func_msg("Tracing event hasn't been determined "
2603                                        "for pid %d, status %0#x", pid, status);
2604
2605                 if (!list_is_empty(&tcp->wait_list)) {
2606                         wait_extra_data_idx = wait_tab_pos;
2607                         extra_tcp = tcp;
2608                         debug_func_msg("queued extra pid %d", tcp->pid);
2609                 } else {
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);
2613                 }
2614
2615                 wait_tab_pos++;
2616
2617                 if (extra_tcp)
2618                         break;
2619
2620 next_event_wait_next:
2621                 pid = wait4(-1, &status, __WALL | WNOHANG, (cflag ? &ru : NULL));
2622                 wait_errno = errno;
2623                 wait_nohang = true;
2624         }
2625
2626 next_event_get_tcp:
2627         elem = list_remove_head(&pending_tcps);
2628
2629         if (!elem) {
2630                 tcb_wait_tab_check_size(0);
2631                 memset(tcb_wait_tab, 0, sizeof(*tcb_wait_tab));
2632                 tcb_wait_tab->te = TE_NEXT;
2633
2634                 return tcb_wait_tab;
2635         } else {
2636                 tcp = list_elem(elem, struct tcb, wait_list);
2637                 debug_func_msg("dequeued pid %d", tcp->pid);
2638         }
2639
2640 next_event_exit:
2641         /* Is this the very first time we see this tracee stopped? */
2642         if (tcp->flags & TCB_STARTUP)
2643                 startup_tcb(tcp);
2644
2645         clear_regs(tcp);
2646
2647         /* Set current output file */
2648         set_current_tcp(tcp);
2649
2650         return tcb_wait_tab + tcp->wait_data_idx;
2651 }
2652
2653 static int
2654 trace_syscall(struct tcb *tcp, unsigned int *sig)
2655 {
2656         if (entering(tcp)) {
2657                 int res = syscall_entering_decode(tcp);
2658                 switch (res) {
2659                 case 0:
2660                         return 0;
2661                 case 1:
2662                         res = syscall_entering_trace(tcp, sig);
2663                 }
2664                 syscall_entering_finish(tcp, res);
2665                 return res;
2666         } else {
2667                 struct timespec ts = {};
2668                 int res = syscall_exiting_decode(tcp, &ts);
2669                 if (res != 0) {
2670                         res = syscall_exiting_trace(tcp, &ts, res);
2671                 }
2672                 syscall_exiting_finish(tcp);
2673                 return res;
2674         }
2675 }
2676
2677 /* Returns true iff the main trace loop has to continue. */
2678 static bool
2679 dispatch_event(const struct tcb_wait_data *wd)
2680 {
2681         unsigned int restart_op;
2682         unsigned int restart_sig = 0;
2683         enum trace_event te = wd ? wd->te : TE_BREAK;
2684         /*
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
2687          */
2688         int status = wd ? wd->status : 0;
2689
2690         if (current_tcp && has_seccomp_filter(current_tcp))
2691                 restart_op = seccomp_filter_restart_operator(current_tcp);
2692         else
2693                 restart_op = PTRACE_SYSCALL;
2694
2695         switch (te) {
2696         case TE_BREAK:
2697                 return false;
2698
2699         case TE_NEXT:
2700                 return true;
2701
2702         case TE_RESTART:
2703                 break;
2704
2705         case TE_SECCOMP:
2706                 if (!has_seccomp_filter(current_tcp)) {
2707                         /*
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.
2714                          */
2715                         current_tcp->flags |= TCB_SECCOMP_FILTER;
2716                         restart_op = PTRACE_SYSCALL;
2717                         break;
2718                 }
2719
2720                 if (seccomp_before_sysentry) {
2721                         restart_op = PTRACE_SYSCALL;
2722                         break;
2723                 }
2724                 ATTRIBUTE_FALLTHROUGH;
2725
2726         case TE_SYSCALL_STOP:
2727                 if (trace_syscall(current_tcp, &restart_sig) < 0) {
2728                         /*
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.
2738                          */
2739                         return true;
2740                 }
2741                 if (has_seccomp_filter(current_tcp)) {
2742                         /*
2743                          * Syscall and seccomp stops can happen in different
2744                          * orders depending on kernel.  strace tests this in
2745                          * check_seccomp_order_tracer().
2746                          *
2747                          * Linux 3.5--4.7:
2748                          * (seccomp-stop before syscall-entry-stop)
2749                          *         +--> seccomp-stop ->-PTRACE_SYSCALL->-+
2750                          *         |                                     |
2751                          *     PTRACE_CONT                   syscall-entry-stop
2752                          *         |                                     |
2753                          * syscall-exit-stop <---PTRACE_SYSCALL-----<----+
2754                          *
2755                          * Linux 4.8+:
2756                          * (seccomp-stop after syscall-entry-stop)
2757                          *                 syscall-entry-stop
2758                          *
2759                          *         +---->-----PTRACE_CONT---->----+
2760                          *         |                              |
2761                          *  syscall-exit-stop               seccomp-stop
2762                          *         |                              |
2763                          *         +----<----PTRACE_SYSCALL---<---+
2764                          *
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
2768                          * entry.
2769                          *
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.
2774                          */
2775                         restart_op = exiting(current_tcp) ? PTRACE_SYSCALL : PTRACE_CONT;
2776                 }
2777                 break;
2778
2779         case TE_SIGNAL_DELIVERY_STOP:
2780                 restart_sig = WSTOPSIG(status);
2781                 print_stopped(current_tcp, &wd->si, restart_sig);
2782                 break;
2783
2784         case TE_SIGNALLED:
2785                 print_signalled(current_tcp, current_tcp->pid, status);
2786                 droptcb(current_tcp);
2787                 return true;
2788
2789         case TE_GROUP_STOP:
2790                 restart_sig = WSTOPSIG(status);
2791                 print_stopped(current_tcp, NULL, restart_sig);
2792                 if (use_seize) {
2793                         /*
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
2797                          * continue to run).
2798                          */
2799                         restart_op = PTRACE_LISTEN;
2800                         restart_sig = 0;
2801                 }
2802                 break;
2803
2804         case TE_EXITED:
2805                 print_exited(current_tcp, current_tcp->pid, status);
2806                 droptcb(current_tcp);
2807                 return true;
2808
2809         case TE_STOP_BEFORE_EXECVE:
2810                 /* The syscall succeeded, clear the flag.  */
2811                 current_tcp->flags &= ~TCB_CHECK_EXEC_SYSCALL;
2812                 /*
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
2818                  * otherwise.
2819                  */
2820                 if (!maybe_switch_current_tcp() && entering(current_tcp)) {
2821                         int ret;
2822
2823                         error_msg("Stray PTRACE_EVENT_EXEC from pid %d"
2824                                   ", trying to recover...",
2825                                   current_tcp->pid);
2826
2827                         current_tcp->flags |= TCB_RECOVERING;
2828                         ret = trace_syscall(current_tcp, &restart_sig);
2829                         current_tcp->flags &= ~TCB_RECOVERING;
2830
2831                         if (ret < 0) {
2832                                 /* The reason is described in TE_SYSCALL_STOP */
2833                                 return true;
2834                         }
2835                 }
2836
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;
2840                         } else {
2841                                 detach(current_tcp); /* do "-b execve" thingy */
2842                                 return true;
2843                         }
2844                 }
2845                 break;
2846
2847         case TE_STOP_BEFORE_EXIT:
2848                 print_event_exit(current_tcp);
2849                 break;
2850         }
2851
2852         /* We handled quick cases, we are permitted to interrupt now. */
2853         if (interrupted)
2854                 return false;
2855
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);
2861
2862                 current_tcp->delayed_wait_data = copy_trace_wait_data(wd);
2863
2864                 return true;
2865         }
2866
2867         if (ptrace_restart(restart_op, current_tcp, restart_sig) < 0) {
2868                 /* Note: ptrace_restart emitted error message */
2869                 exit_code = 1;
2870                 return false;
2871         }
2872         return true;
2873 }
2874
2875 static bool
2876 restart_delayed_tcb(struct tcb *const tcp)
2877 {
2878         struct tcb_wait_data *wd = tcp->delayed_wait_data;
2879
2880         if (!wd) {
2881                 error_func_msg("No delayed wait data found for pid %d",
2882                                tcp->pid);
2883                 wd = init_trace_wait_data(alloca(trace_wait_data_size(tcp)));
2884         }
2885
2886         wd->te = TE_RESTART;
2887
2888         debug_func_msg("pid %d", tcp->pid);
2889
2890         tcp->flags &= ~TCB_DELAYED;
2891
2892         struct tcb *const prev_tcp = current_tcp;
2893         current_tcp = tcp;
2894         bool ret = dispatch_event(wd);
2895         current_tcp = prev_tcp;
2896
2897         free_trace_wait_data(tcp->delayed_wait_data);
2898         tcp->delayed_wait_data = NULL;
2899
2900         return ret;
2901 }
2902
2903 static bool
2904 restart_delayed_tcbs(void)
2905 {
2906         struct tcb *tcp_next = NULL;
2907         struct timespec ts_now;
2908
2909         clock_gettime(CLOCK_MONOTONIC, &ts_now);
2910
2911         for (size_t i = 0; i < tcbtabsize; i++) {
2912                 struct tcb *tcp = tcbtab[i];
2913
2914                 if (tcp->pid && syscall_delayed(tcp)) {
2915                         if (ts_cmp(&ts_now, &tcp->delay_expiration_time) > 0) {
2916                                 if (!restart_delayed_tcb(tcp))
2917                                         return false;
2918                         } else {
2919                                 /* Check whether this tcb is the next.  */
2920                                 if (!tcp_next ||
2921                                     ts_cmp(&tcp_next->delay_expiration_time,
2922                                            &tcp->delay_expiration_time) > 0) {
2923                                         tcp_next = tcp;
2924                                 }
2925                         }
2926                 }
2927         }
2928
2929         if (tcp_next)
2930                 arm_delay_timer(tcp_next);
2931
2932         return true;
2933 }
2934
2935 /*
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.
2939  */
2940 static void
2941 timer_sighandler(int sig)
2942 {
2943         delay_timer_expired();
2944
2945         if (restart_failed)
2946                 return;
2947
2948         int saved_errno = errno;
2949
2950         if (!restart_delayed_tcbs())
2951                 restart_failed = 1;
2952
2953         errno = saved_errno;
2954 }
2955
2956 #ifdef ENABLE_COVERAGE_GCOV
2957 extern void __gcov_flush(void);
2958 #endif
2959
2960 static void ATTRIBUTE_NORETURN
2961 terminate(void)
2962 {
2963         int sig = interrupted;
2964
2965         cleanup(sig);
2966         if (cflag)
2967                 call_summary(shared_log);
2968         fflush(NULL);
2969         if (shared_log != stderr)
2970                 fclose(shared_log);
2971         if (popen_pid) {
2972                 while (waitpid(popen_pid, NULL, 0) < 0 && errno == EINTR)
2973                         ;
2974         }
2975         if (sig) {
2976                 exit_code = 0x100 | sig;
2977         }
2978         if (exit_code > 0xff) {
2979                 /* Avoid potential core file clobbering.  */
2980                 struct_rlimit rlim = {0, 0};
2981                 set_rlimit(RLIMIT_CORE, &rlim);
2982
2983                 /* Child was killed by a signal, mimic that.  */
2984                 exit_code &= 0xff;
2985                 signal(exit_code, SIG_DFL);
2986 #ifdef ENABLE_COVERAGE_GCOV
2987                 __gcov_flush();
2988 #endif
2989                 raise(exit_code);
2990
2991                 /* Unblock the signal.  */
2992                 sigset_t mask;
2993                 sigemptyset(&mask);
2994                 sigaddset(&mask, exit_code);
2995 #ifdef ENABLE_COVERAGE_GCOV
2996                 __gcov_flush();
2997 #endif
2998                 sigprocmask(SIG_UNBLOCK, &mask, NULL);
2999
3000                 /* Paranoia - what if this signal is not fatal?
3001                    Exit with 128 + signo then.  */
3002                 exit_code += 128;
3003         }
3004         exit(exit_code);
3005 }
3006
3007 int
3008 main(int argc, char *argv[])
3009 {
3010         setlocale(LC_ALL, "");
3011         init(argc, argv);
3012
3013         exit_code = !nprocs;
3014
3015         while (dispatch_event(next_event()))
3016                 ;
3017         terminate();
3018 }