]> granicus.if.org Git - strace/blob - strace.c
rtnl_link: print pad field in the struct ifla_port_vsi decoder
[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 enum {
97         DAEMONIZE_NONE        = 0,
98         DAEMONIZE_GRANDCHILD  = 1,
99         DAEMONIZE_NEW_PGROUP  = 2,
100         DAEMONIZE_NEW_SESSION = 3,
101
102         DAEMONIZE_OPTS_GUARD__,
103         MAX_DAEMONIZE_OPTS    = DAEMONIZE_OPTS_GUARD__ - 1
104 };
105 /*
106  * daemonized_tracer supports -D option.
107  * With this option, strace forks twice.
108  * Unlike normal case, with -D *grandparent* process exec's,
109  * becoming a traced process. Child exits (this prevents traced process
110  * from having children it doesn't expect to have), and grandchild
111  * attaches to grandparent similarly to strace -p PID.
112  * This allows for more transparent interaction in cases
113  * when process and its parent are communicating via signals,
114  * wait() etc. Without -D, strace process gets lodged in between,
115  * disrupting parent<->child link.
116  */
117 static unsigned int daemonized_tracer;
118
119 static int post_attach_sigstop = TCB_IGNORE_ONE_SIGSTOP;
120 #define use_seize (post_attach_sigstop == 0)
121
122 /* Show path associated with fd arguments */
123 unsigned int show_fd_path;
124
125 static bool detach_on_execve;
126
127 static int exit_code;
128 static int strace_child;
129 static int strace_tracer_pid;
130
131 static const char *username;
132 static uid_t run_uid;
133 static gid_t run_gid;
134
135 unsigned int max_strlen = DEFAULT_STRLEN;
136 static int acolumn = DEFAULT_ACOLUMN;
137 static char *acolumn_spaces;
138
139 /* Default output style for xlat entities */
140 enum xlat_style xlat_verbosity = XLAT_STYLE_ABBREV;
141
142 static const char *outfname;
143 /* If -ff, points to stderr. Else, it's our common output log */
144 static FILE *shared_log;
145 static bool open_append;
146
147 struct tcb *printing_tcp;
148 static struct tcb *current_tcp;
149
150 struct tcb_wait_data {
151         enum trace_event te; /**< Event passed to dispatch_event() */
152         int status;          /**< status, returned by wait4() */
153         unsigned long msg;   /**< Value returned by PTRACE_GETEVENTMSG */
154         siginfo_t si;        /**< siginfo, returned by PTRACE_GETSIGINFO */
155 };
156
157 static struct tcb **tcbtab;
158 static unsigned int nprocs;
159 static size_t tcbtabsize;
160
161 static struct tcb_wait_data *tcb_wait_tab;
162 static size_t tcb_wait_tab_size;
163
164
165 #ifndef HAVE_PROGRAM_INVOCATION_NAME
166 char *program_invocation_name;
167 #endif
168
169 unsigned os_release; /* generated from uname()'s u.release */
170
171 static void detach(struct tcb *tcp);
172 static void cleanup(int sig);
173 static void interrupt(int sig);
174
175 #ifdef HAVE_SIG_ATOMIC_T
176 static volatile sig_atomic_t interrupted, restart_failed;
177 #else
178 static volatile int interrupted, restart_failed;
179 #endif
180
181 static sigset_t timer_set;
182 static void timer_sighandler(int);
183
184 #ifndef HAVE_STRERROR
185
186 # if !HAVE_DECL_SYS_ERRLIST
187 extern int sys_nerr;
188 extern char *sys_errlist[];
189 # endif
190
191 const char *
192 strerror(int err_no)
193 {
194         static char buf[sizeof("Unknown error %d") + sizeof(int)*3];
195
196         if (err_no < 1 || err_no >= sys_nerr) {
197                 xsprintf(buf, "Unknown error %d", err_no);
198                 return buf;
199         }
200         return sys_errlist[err_no];
201 }
202
203 #endif /* HAVE_STERRROR */
204
205 static void
206 print_version(void)
207 {
208         static const char features[] =
209 #ifdef ENABLE_STACKTRACE
210                 " stack-trace=" USE_UNWINDER
211 #endif
212 #ifdef USE_DEMANGLE
213                 " stack-demangle"
214 #endif
215 #if SUPPORTED_PERSONALITIES > 1
216 # if defined HAVE_M32_MPERS
217                 " m32-mpers"
218 # else
219                 " no-m32-mpers"
220 # endif
221 #endif /* SUPPORTED_PERSONALITIES > 1 */
222 #if SUPPORTED_PERSONALITIES > 2
223 # if defined HAVE_MX32_MPERS
224                 " mx32-mpers"
225 # else
226                 " no-mx32-mpers"
227 # endif
228 #endif /* SUPPORTED_PERSONALITIES > 2 */
229                 "";
230
231         printf("%s -- version %s\n"
232                "Copyright (c) 1991-%s The strace developers <%s>.\n"
233                "This is free software; see the source for copying conditions.  There is NO\n"
234                "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n",
235                PACKAGE_NAME, PACKAGE_VERSION, COPYRIGHT_YEAR, PACKAGE_URL);
236         printf("\nOptional features enabled:%s\n",
237                features[0] ? features : " (none)");
238 }
239
240 static void
241 usage(void)
242 {
243 #ifdef ENABLE_STACKTRACE
244 # define K_OPT "k"
245 #else
246 # define K_OPT ""
247 #endif
248
249         printf("\
250 usage: strace [-ACdffhi" K_OPT "qqrtttTvVwxxyyzZ] [-I n] [-b execve] [-e expr]...\n\
251               [-a column] [-o file] [-s strsize] [-X format] [-P path]...\n\
252               [-p pid]... [--seccomp-bpf]\n\
253               { -p pid | [-DDD] [-E var=val]... [-u username] PROG [ARGS] }\n\
254    or: strace -c[dfwzZ] [-I n] [-b execve] [-e expr]... [-O overhead]\n\
255               [-S sortby] [-P path]... [-p pid]... [--seccomp-bpf]\n\
256               { -p pid | [-DDD] [-E var=val]... [-u username] PROG [ARGS] }\n\
257 \n\
258 Output format:\n\
259   -A             open the file provided in the -o option in append mode\n\
260   -a column      alignment COLUMN for printing syscall results (default %d)\n\
261   -i             print instruction pointer at time of syscall\n\
262 "
263 #ifdef ENABLE_STACKTRACE
264 "\
265   -k             obtain stack trace between each syscall\n\
266 "
267 #endif
268 "\
269   -o file        send trace output to FILE instead of stderr\n\
270   -q             suppress messages about attaching, detaching, etc.\n\
271   -qq            suppress messages about process exit status as well.\n\
272   -r             print relative timestamp\n\
273   -s strsize     limit length of print strings to STRSIZE chars (default %d)\n\
274   -t             print absolute timestamp\n\
275   -tt            print absolute timestamp with usecs\n\
276   -T             print time spent in each syscall\n\
277   -v             verbose mode: print entities unabbreviated\n\
278   -x             print non-ascii strings in hex\n\
279   -xx            print all strings in hex\n\
280   -X format      set the format for printing of named constants and flags\n\
281   -y             print paths associated with file descriptor arguments\n\
282   -yy            print protocol specific information associated with socket\n\
283                  file descriptors\n\
284 \n\
285 Statistics:\n\
286   -c             count time, calls, and errors for each syscall and report\n\
287                  summary\n\
288   -C             like -c but also print regular output\n\
289   -O overhead    set overhead for tracing syscalls to OVERHEAD usecs\n\
290   -S sortby      sort syscall counts by: time, calls, errors, name, nothing\n\
291                  (default %s)\n\
292   -w             summarise syscall latency (default is system time)\n\
293 \n\
294 Filtering:\n\
295   -e expr        a qualifying expression: option=[!]all or option=[!]val1[,val2]...\n\
296      options:    trace, abbrev, verbose, raw, signal, read, write, fault,\n\
297                  inject, status, kvm\n\
298   -P path        trace accesses to path\n\
299   -z             print only syscalls that returned without an error code\n\
300   -Z             print only syscalls that returned with an error code\n\
301 \n\
302 Tracing:\n\
303   -b execve      detach on execve syscall\n\
304   -D             run tracer process as a grandchild, not as a parent\n\
305   -DD            run tracer process in a separate process group\n\
306   -DDD           run tracer process in a separate session\n\
307   -f             follow forks\n\
308   -ff            follow forks with output into separate files\n\
309   -I interruptible\n\
310      1:          no signals are blocked\n\
311      2:          fatal signals are blocked while decoding syscall (default)\n\
312      3:          fatal signals are always blocked (default if '-o FILE PROG')\n\
313      4:          fatal signals and SIGTSTP (^Z) are always blocked\n\
314                  (useful to make 'strace -o FILE PROG' not stop on ^Z)\n\
315 \n\
316 Startup:\n\
317   -E var         remove var from the environment for command\n\
318   -E var=val     put var=val in the environment for command\n\
319   -p pid         trace process with process id PID, may be repeated\n\
320   -u username    run command as username handling setuid and/or setgid\n\
321 \n\
322 Miscellaneous:\n\
323   --seccomp-bpf  enable seccomp-bpf filtering\n\
324   -d             enable debug output to stderr\n\
325   -h, --help     print help message\n\
326   -V, --version  print version\n\
327 "
328 /* ancient, no one should use it
329 -F -- attempt to follow vforks (deprecated, use -f)\n\
330  */
331 , DEFAULT_ACOLUMN, DEFAULT_STRLEN, DEFAULT_SORTBY);
332         exit(0);
333
334 #undef K_OPT
335 }
336
337 void ATTRIBUTE_NORETURN
338 die(void)
339 {
340         if (strace_tracer_pid == getpid()) {
341                 cleanup(0);
342                 exit(1);
343         }
344
345         _exit(1);
346 }
347
348 static void
349 error_opt_arg(int opt, const char *arg)
350 {
351         error_msg_and_help("invalid -%c argument: '%s'", opt, arg);
352 }
353
354 static const char *ptrace_attach_cmd;
355
356 static int
357 ptrace_attach_or_seize(int pid)
358 {
359         int r;
360         if (!use_seize)
361                 return ptrace_attach_cmd = "PTRACE_ATTACH",
362                        ptrace(PTRACE_ATTACH, pid, 0L, 0L);
363         r = ptrace(PTRACE_SEIZE, pid, 0L, (unsigned long) ptrace_setoptions);
364         if (r)
365                 return ptrace_attach_cmd = "PTRACE_SEIZE", r;
366         r = ptrace(PTRACE_INTERRUPT, pid, 0L, 0L);
367         return ptrace_attach_cmd = "PTRACE_INTERRUPT", r;
368 }
369
370 static const char *
371 ptrace_op_str(unsigned int op)
372 {
373         const char *str = xlookup(ptrace_cmds, op);
374         if (str)
375                 return str;
376
377         static char buf[sizeof(op) * 3];
378         xsprintf(buf, "%u", op);
379         return buf;
380 }
381
382 /*
383  * Used when we want to unblock stopped traced process.
384  * Should be only used with PTRACE_CONT, PTRACE_DETACH and PTRACE_SYSCALL.
385  * Returns 0 on success or if error was ESRCH
386  * (presumably process was killed while we talk to it).
387  * Otherwise prints error message and returns -1.
388  */
389 static int
390 ptrace_restart(const unsigned int op, struct tcb *const tcp, unsigned int sig)
391 {
392         int err;
393
394         errno = 0;
395         ptrace(op, tcp->pid, 0L, (unsigned long) sig);
396         err = errno;
397         if (!err || err == ESRCH)
398                 return 0;
399
400         /*
401          * Why curcol != 0? Otherwise sometimes we get this:
402          *
403          * 10252 kill(10253, SIGKILL)              = 0
404          *  <ptrace(SYSCALL,10252):No such process>10253 ...next decode...
405          *
406          * 10252 died after we retrieved syscall exit data,
407          * but before we tried to restart it. Log looks ugly.
408          */
409         if (current_tcp && current_tcp->curcol != 0) {
410                 tprintf(" <Cannot restart pid %d with ptrace(%s): %s>\n",
411                         tcp->pid, ptrace_op_str(op), strerror(err));
412                 line_ended();
413         }
414         errno = err;
415         perror_msg("ptrace(%s,pid:%d,sig:%u)",
416                    ptrace_op_str(op), tcp->pid, sig);
417         return -1;
418 }
419
420 static void
421 set_cloexec_flag(int fd)
422 {
423         int flags, newflags;
424
425         flags = fcntl(fd, F_GETFD);
426         if (flags < 0) {
427                 /* Can happen only if fd is bad.
428                  * Should never happen: if it does, we have a bug
429                  * in the caller. Therefore we just abort
430                  * instead of propagating the error.
431                  */
432                 perror_msg_and_die("fcntl(%d, F_GETFD)", fd);
433         }
434
435         newflags = flags | FD_CLOEXEC;
436         if (flags == newflags)
437                 return;
438
439         if (fcntl(fd, F_SETFD, newflags)) /* never fails */
440                 perror_msg_and_die("fcntl(%d, F_SETFD, %#x)", fd, newflags);
441 }
442
443 /*
444  * When strace is setuid executable, we have to swap uids
445  * before and after filesystem and process management operations.
446  */
447 static void
448 swap_uid(void)
449 {
450         int euid = geteuid(), uid = getuid();
451
452         if (euid != uid && setreuid(euid, uid) < 0) {
453                 perror_msg_and_die("setreuid");
454         }
455 }
456
457 static FILE *
458 strace_fopen(const char *path)
459 {
460         FILE *fp;
461
462         swap_uid();
463         fp = fopen_stream(path, open_append ? "a" : "w");
464         if (!fp)
465                 perror_msg_and_die("Can't fopen '%s'", path);
466         swap_uid();
467         set_cloexec_flag(fileno(fp));
468         return fp;
469 }
470
471 static int popen_pid;
472
473 #ifndef _PATH_BSHELL
474 # define _PATH_BSHELL "/bin/sh"
475 #endif
476
477 /*
478  * We cannot use standard popen(3) here because we have to distinguish
479  * popen child process from other processes we trace, and standard popen(3)
480  * does not export its child's pid.
481  */
482 static FILE *
483 strace_popen(const char *command)
484 {
485         FILE *fp;
486         int pid;
487         int fds[2];
488
489         swap_uid();
490         if (pipe(fds) < 0)
491                 perror_msg_and_die("pipe");
492
493         set_cloexec_flag(fds[1]); /* never fails */
494
495         pid = vfork();
496         if (pid < 0)
497                 perror_msg_and_die("vfork");
498
499         if (pid == 0) {
500                 /* child */
501                 close(fds[1]);
502                 if (fds[0] != 0) {
503                         if (dup2(fds[0], 0))
504                                 perror_msg_and_die("dup2");
505                         close(fds[0]);
506                 }
507                 execl(_PATH_BSHELL, "sh", "-c", command, NULL);
508                 perror_msg_and_die("Can't execute '%s'", _PATH_BSHELL);
509         }
510
511         /* parent */
512         popen_pid = pid;
513         close(fds[0]);
514         swap_uid();
515         fp = fdopen(fds[1], "w");
516         if (!fp)
517                 perror_msg_and_die("fdopen");
518         return fp;
519 }
520
521 static void
522 outf_perror(const struct tcb * const tcp)
523 {
524         if (tcp->outf == stderr)
525                 return;
526
527         /* This is ugly, but we don't store separate file names */
528         if (followfork >= 2)
529                 perror_msg("%s.%u", outfname, tcp->pid);
530         else
531                 perror_msg("%s", outfname);
532 }
533
534 ATTRIBUTE_FORMAT((printf, 1, 0))
535 static void
536 tvprintf(const char *const fmt, va_list args)
537 {
538         if (current_tcp) {
539                 int n = vfprintf(current_tcp->outf, fmt, args);
540                 if (n < 0) {
541                         /* very unlikely due to vfprintf buffering */
542                         outf_perror(current_tcp);
543                 } else
544                         current_tcp->curcol += n;
545         }
546 }
547
548 void
549 tprintf(const char *fmt, ...)
550 {
551         va_list args;
552         va_start(args, fmt);
553         tvprintf(fmt, args);
554         va_end(args);
555 }
556
557 #ifndef HAVE_FPUTS_UNLOCKED
558 # define fputs_unlocked fputs
559 #endif
560
561 void
562 tprints(const char *str)
563 {
564         if (current_tcp) {
565                 int n = fputs_unlocked(str, current_tcp->outf);
566                 if (n >= 0) {
567                         current_tcp->curcol += strlen(str);
568                         return;
569                 }
570                 /* very unlikely due to fputs_unlocked buffering */
571                 outf_perror(current_tcp);
572         }
573 }
574
575 void
576 tprints_comment(const char *const str)
577 {
578         if (str && *str)
579                 tprintf(" /* %s */", str);
580 }
581
582 void
583 tprintf_comment(const char *fmt, ...)
584 {
585         if (!fmt || !*fmt)
586                 return;
587
588         va_list args;
589         va_start(args, fmt);
590         tprints(" /* ");
591         tvprintf(fmt, args);
592         tprints(" */");
593         va_end(args);
594 }
595
596 static void
597 flush_tcp_output(const struct tcb *const tcp)
598 {
599         if (fflush(tcp->outf))
600                 outf_perror(tcp);
601 }
602
603 void
604 line_ended(void)
605 {
606         if (current_tcp) {
607                 current_tcp->curcol = 0;
608                 flush_tcp_output(current_tcp);
609         }
610         if (printing_tcp) {
611                 printing_tcp->curcol = 0;
612                 printing_tcp = NULL;
613         }
614 }
615
616 void
617 set_current_tcp(const struct tcb *tcp)
618 {
619         current_tcp = (struct tcb *) tcp;
620
621         /* Sync current_personality and stuff */
622         if (current_tcp)
623                 set_personality(current_tcp->currpers);
624 }
625
626 void
627 printleader(struct tcb *tcp)
628 {
629         /* If -ff, "previous tcb we printed" is always the same as current,
630          * because we have per-tcb output files.
631          */
632         if (followfork >= 2)
633                 printing_tcp = tcp;
634
635         if (printing_tcp) {
636                 set_current_tcp(printing_tcp);
637                 if (!tcp->staged_output_data && printing_tcp->curcol != 0 &&
638                     (followfork < 2 || printing_tcp == tcp)) {
639                         /*
640                          * case 1: we have a shared log (i.e. not -ff), and last line
641                          * wasn't finished (same or different tcb, doesn't matter).
642                          * case 2: split log, we are the same tcb, but our last line
643                          * didn't finish ("SIGKILL nuked us after syscall entry" etc).
644                          */
645                         tprints(" <unfinished ...>\n");
646                         printing_tcp->curcol = 0;
647                 }
648         }
649
650         printing_tcp = tcp;
651         set_current_tcp(tcp);
652         current_tcp->curcol = 0;
653
654         if (print_pid_pfx)
655                 tprintf("%-5d ", tcp->pid);
656         else if (nprocs > 1 && !outfname)
657                 tprintf("[pid %5u] ", tcp->pid);
658
659         if (tflag) {
660                 struct timespec ts;
661                 clock_gettime(CLOCK_REALTIME, &ts);
662
663                 if (tflag > 2) {
664                         tprintf("%lld.%06ld ",
665                                 (long long) ts.tv_sec, (long) ts.tv_nsec / 1000);
666                 } else {
667                         time_t local = ts.tv_sec;
668                         char str[MAX(sizeof("HH:MM:SS"), sizeof(ts.tv_sec) * 3)];
669                         struct tm *tm = localtime(&local);
670
671                         if (tm)
672                                 strftime(str, sizeof(str), "%T", tm);
673                         else
674                                 xsprintf(str, "%lld", (long long) local);
675                         if (tflag > 1)
676                                 tprintf("%s.%06ld ",
677                                         str, (long) ts.tv_nsec / 1000);
678                         else
679                                 tprintf("%s ", str);
680                 }
681         }
682
683         if (rflag) {
684                 struct timespec ts;
685                 clock_gettime(CLOCK_MONOTONIC, &ts);
686
687                 static struct timespec ots;
688                 if (ots.tv_sec == 0)
689                         ots = ts;
690
691                 struct timespec dts;
692                 ts_sub(&dts, &ts, &ots);
693                 ots = ts;
694
695                 tprintf("%s%6ld.%06ld%s ",
696                         tflag ? "(+" : "",
697                         (long) dts.tv_sec, (long) dts.tv_nsec / 1000,
698                         tflag ? ")" : "");
699         }
700
701         if (iflag)
702                 print_instruction_pointer(tcp);
703 }
704
705 void
706 tabto(void)
707 {
708         if (current_tcp->curcol < acolumn)
709                 tprints(acolumn_spaces + current_tcp->curcol);
710 }
711
712 /* Should be only called directly *after successful attach* to a tracee.
713  * Otherwise, "strace -oFILE -ff -p<nonexistant_pid>"
714  * may create bogus empty FILE.<nonexistant_pid>, and then die.
715  */
716 static void
717 after_successful_attach(struct tcb *tcp, const unsigned int flags)
718 {
719         tcp->flags |= TCB_ATTACHED | TCB_STARTUP | flags;
720         tcp->outf = shared_log; /* if not -ff mode, the same file is for all */
721         if (followfork >= 2) {
722                 char name[PATH_MAX];
723                 xsprintf(name, "%s.%u", outfname, tcp->pid);
724                 tcp->outf = strace_fopen(name);
725         }
726
727 #ifdef ENABLE_STACKTRACE
728         if (stack_trace_enabled)
729                 unwind_tcb_init(tcp);
730 #endif
731 }
732
733 static void
734 expand_tcbtab(void)
735 {
736         /* Allocate some (more) TCBs (and expand the table).
737            We don't want to relocate the TCBs because our
738            callers have pointers and it would be a pain.
739            So tcbtab is a table of pointers.  Since we never
740            free the TCBs, we allocate a single chunk of many.  */
741         size_t old_tcbtabsize;
742         struct tcb *newtcbs;
743         struct tcb **tcb_ptr;
744
745         old_tcbtabsize = tcbtabsize;
746
747         tcbtab = xgrowarray(tcbtab, &tcbtabsize, sizeof(tcbtab[0]));
748         newtcbs = xcalloc(tcbtabsize - old_tcbtabsize, sizeof(newtcbs[0]));
749
750         for (tcb_ptr = tcbtab + old_tcbtabsize;
751             tcb_ptr < tcbtab + tcbtabsize; tcb_ptr++, newtcbs++)
752                 *tcb_ptr = newtcbs;
753 }
754
755 static struct tcb *
756 alloctcb(int pid)
757 {
758         unsigned int i;
759         struct tcb *tcp;
760
761         if (nprocs == tcbtabsize)
762                 expand_tcbtab();
763
764         for (i = 0; i < tcbtabsize; i++) {
765                 tcp = tcbtab[i];
766                 if (!tcp->pid) {
767                         memset(tcp, 0, sizeof(*tcp));
768                         list_init(&tcp->wait_list);
769                         tcp->pid = pid;
770 #if SUPPORTED_PERSONALITIES > 1
771                         tcp->currpers = current_personality;
772 #endif
773                         nprocs++;
774                         debug_msg("new tcb for pid %d, active tcbs:%d",
775                                   tcp->pid, nprocs);
776                         return tcp;
777                 }
778         }
779         error_msg_and_die("bug in alloctcb");
780 }
781
782 void *
783 get_tcb_priv_data(const struct tcb *tcp)
784 {
785         return tcp->_priv_data;
786 }
787
788 int
789 set_tcb_priv_data(struct tcb *tcp, void *const priv_data,
790                   void (*const free_priv_data)(void *))
791 {
792         if (tcp->_priv_data)
793                 return -1;
794
795         tcp->_free_priv_data = free_priv_data;
796         tcp->_priv_data = priv_data;
797
798         return 0;
799 }
800
801 void
802 free_tcb_priv_data(struct tcb *tcp)
803 {
804         if (tcp->_priv_data) {
805                 if (tcp->_free_priv_data) {
806                         tcp->_free_priv_data(tcp->_priv_data);
807                         tcp->_free_priv_data = NULL;
808                 }
809                 tcp->_priv_data = NULL;
810         }
811 }
812
813 static void
814 droptcb(struct tcb *tcp)
815 {
816         if (tcp->pid == 0)
817                 return;
818
819         if (cflag && debug_flag) {
820                 struct timespec dt;
821
822                 ts_sub(&dt, &tcp->stime, &tcp->atime);
823                 debug_func_msg("pid %d: %.9f seconds of system time spent "
824                                "since attach", tcp->pid, ts_float(&dt));
825         }
826
827         int p;
828         for (p = 0; p < SUPPORTED_PERSONALITIES; ++p)
829                 free(tcp->inject_vec[p]);
830
831         free_tcb_priv_data(tcp);
832
833 #ifdef ENABLE_STACKTRACE
834         if (stack_trace_enabled)
835                 unwind_tcb_fin(tcp);
836 #endif
837
838 #ifdef HAVE_LINUX_KVM_H
839         kvm_vcpu_info_free(tcp);
840 #endif
841
842         if (tcp->mmap_cache)
843                 tcp->mmap_cache->free_fn(tcp, __func__);
844
845         nprocs--;
846         debug_msg("dropped tcb for pid %d, %d remain", tcp->pid, nprocs);
847
848         if (tcp->outf) {
849                 bool publish = true;
850                 if (!is_complete_set(status_set, NUMBER_OF_STATUSES)) {
851                         publish = is_number_in_set(STATUS_DETACHED, status_set);
852                         strace_close_memstream(tcp, publish);
853                 }
854
855                 if (followfork >= 2) {
856                         if (tcp->curcol != 0 && publish)
857                                 fprintf(tcp->outf, " <detached ...>\n");
858                         fclose(tcp->outf);
859                 } else {
860                         if (printing_tcp == tcp && tcp->curcol != 0 && publish)
861                                 fprintf(tcp->outf, " <detached ...>\n");
862                         flush_tcp_output(tcp);
863                 }
864         }
865
866         if (current_tcp == tcp)
867                 set_current_tcp(NULL);
868         if (printing_tcp == tcp)
869                 printing_tcp = NULL;
870
871         list_remove(&tcp->wait_list);
872
873         memset(tcp, 0, sizeof(*tcp));
874 }
875
876 /* Detach traced process.
877  * Never call DETACH twice on the same process as both unattached and
878  * attached-unstopped processes give the same ESRCH.  For unattached process we
879  * would SIGSTOP it and wait for its SIGSTOP notification forever.
880  */
881 static void
882 detach(struct tcb *tcp)
883 {
884         int error;
885         int status;
886
887         /*
888          * Linux wrongly insists the child be stopped
889          * before detaching.  Arghh.  We go through hoops
890          * to make a clean break of things.
891          */
892
893         if (!(tcp->flags & TCB_ATTACHED))
894                 goto drop;
895
896         /* We attached but possibly didn't see the expected SIGSTOP.
897          * We must catch exactly one as otherwise the detached process
898          * would be left stopped (process state T).
899          */
900         if (tcp->flags & TCB_IGNORE_ONE_SIGSTOP)
901                 goto wait_loop;
902
903         error = ptrace(PTRACE_DETACH, tcp->pid, 0, 0);
904         if (!error) {
905                 /* On a clear day, you can see forever. */
906                 goto drop;
907         }
908         if (errno != ESRCH) {
909                 /* Shouldn't happen. */
910                 perror_func_msg("ptrace(PTRACE_DETACH,%u)", tcp->pid);
911                 goto drop;
912         }
913         /* ESRCH: process is either not stopped or doesn't exist. */
914         if (my_tkill(tcp->pid, 0) < 0) {
915                 if (errno != ESRCH)
916                         /* Shouldn't happen. */
917                         perror_func_msg("tkill(%u,0)", tcp->pid);
918                 /* else: process doesn't exist. */
919                 goto drop;
920         }
921         /* Process is not stopped, need to stop it. */
922         if (use_seize) {
923                 /*
924                  * With SEIZE, tracee can be in group-stop already.
925                  * In this state sending it another SIGSTOP does nothing.
926                  * Need to use INTERRUPT.
927                  * Testcase: trying to ^C a "strace -p <stopped_process>".
928                  */
929                 error = ptrace(PTRACE_INTERRUPT, tcp->pid, 0, 0);
930                 if (!error)
931                         goto wait_loop;
932                 if (errno != ESRCH)
933                         perror_func_msg("ptrace(PTRACE_INTERRUPT,%u)", tcp->pid);
934         } else {
935                 error = my_tkill(tcp->pid, SIGSTOP);
936                 if (!error)
937                         goto wait_loop;
938                 if (errno != ESRCH)
939                         perror_func_msg("tkill(%u,SIGSTOP)", tcp->pid);
940         }
941         /* Either process doesn't exist, or some weird error. */
942         goto drop;
943
944  wait_loop:
945         /* We end up here in three cases:
946          * 1. We sent PTRACE_INTERRUPT (use_seize case)
947          * 2. We sent SIGSTOP (!use_seize)
948          * 3. Attach SIGSTOP was already pending (TCB_IGNORE_ONE_SIGSTOP set)
949          */
950         for (;;) {
951                 unsigned int sig;
952                 if (waitpid(tcp->pid, &status, __WALL) < 0) {
953                         if (errno == EINTR)
954                                 continue;
955                         /*
956                          * if (errno == ECHILD) break;
957                          * ^^^  WRONG! We expect this PID to exist,
958                          * and want to emit a message otherwise:
959                          */
960                         perror_func_msg("waitpid(%u)", tcp->pid);
961                         break;
962                 }
963                 if (!WIFSTOPPED(status)) {
964                         /*
965                          * Tracee exited or was killed by signal.
966                          * We shouldn't normally reach this place:
967                          * we don't want to consume exit status.
968                          * Consider "strace -p PID" being ^C-ed:
969                          * we want merely to detach from PID.
970                          *
971                          * However, we _can_ end up here if tracee
972                          * was SIGKILLed.
973                          */
974                         break;
975                 }
976                 sig = WSTOPSIG(status);
977                 debug_msg("detach wait: event:%d sig:%d",
978                           (unsigned) status >> 16, sig);
979                 if (use_seize) {
980                         unsigned event = (unsigned)status >> 16;
981                         if (event == PTRACE_EVENT_STOP /*&& sig == SIGTRAP*/) {
982                                 /*
983                                  * sig == SIGTRAP: PTRACE_INTERRUPT stop.
984                                  * sig == other: process was already stopped
985                                  * with this stopping sig (see tests/detach-stopped).
986                                  * Looks like re-injecting this sig is not necessary
987                                  * in DETACH for the tracee to remain stopped.
988                                  */
989                                 sig = 0;
990                         }
991                         /*
992                          * PTRACE_INTERRUPT is not guaranteed to produce
993                          * the above event if other ptrace-stop is pending.
994                          * See tests/detach-sleeping testcase:
995                          * strace got SIGINT while tracee is sleeping.
996                          * We sent PTRACE_INTERRUPT.
997                          * We see syscall exit, not PTRACE_INTERRUPT stop.
998                          * We won't get PTRACE_INTERRUPT stop
999                          * if we would CONT now. Need to DETACH.
1000                          */
1001                         if (sig == syscall_trap_sig)
1002                                 sig = 0;
1003                         /* else: not sure in which case we can be here.
1004                          * Signal stop? Inject it while detaching.
1005                          */
1006                         ptrace_restart(PTRACE_DETACH, tcp, sig);
1007                         break;
1008                 }
1009                 /* Note: this check has to be after use_seize check */
1010                 /* (else, in use_seize case SIGSTOP will be mistreated) */
1011                 if (sig == SIGSTOP) {
1012                         /* Detach, suppressing SIGSTOP */
1013                         ptrace_restart(PTRACE_DETACH, tcp, 0);
1014                         break;
1015                 }
1016                 if (sig == syscall_trap_sig)
1017                         sig = 0;
1018                 /* Can't detach just yet, may need to wait for SIGSTOP */
1019                 error = ptrace_restart(PTRACE_CONT, tcp, sig);
1020                 if (error < 0) {
1021                         /* Should not happen.
1022                          * Note: ptrace_restart returns 0 on ESRCH, so it's not it.
1023                          * ptrace_restart already emitted error message.
1024                          */
1025                         break;
1026                 }
1027         }
1028
1029  drop:
1030         if (!qflag && (tcp->flags & TCB_ATTACHED))
1031                 error_msg("Process %u detached", tcp->pid);
1032
1033         droptcb(tcp);
1034 }
1035
1036 static void
1037 process_opt_p_list(char *opt)
1038 {
1039         while (*opt) {
1040                 /*
1041                  * We accept -p PID,PID; -p "`pidof PROG`"; -p "`pgrep PROG`".
1042                  * pidof uses space as delim, pgrep uses newline. :(
1043                  */
1044                 int pid;
1045                 char *delim = opt + strcspn(opt, "\n\t ,");
1046                 char c = *delim;
1047
1048                 *delim = '\0';
1049                 pid = string_to_uint(opt);
1050                 if (pid <= 0) {
1051                         error_msg_and_die("Invalid process id: '%s'", opt);
1052                 }
1053                 if (pid == strace_tracer_pid) {
1054                         error_msg_and_die("I'm sorry, I can't let you do that, Dave.");
1055                 }
1056                 *delim = c;
1057                 alloctcb(pid);
1058                 if (c == '\0')
1059                         break;
1060                 opt = delim + 1;
1061         }
1062 }
1063
1064 static void
1065 attach_tcb(struct tcb *const tcp)
1066 {
1067         if (ptrace_attach_or_seize(tcp->pid) < 0) {
1068                 perror_msg("attach: ptrace(%s, %d)",
1069                            ptrace_attach_cmd, tcp->pid);
1070                 droptcb(tcp);
1071                 return;
1072         }
1073
1074         after_successful_attach(tcp, TCB_GRABBED | post_attach_sigstop);
1075         debug_msg("attach to pid %d (main) succeeded", tcp->pid);
1076
1077         static const char task_path[] = "/proc/%d/task";
1078         char procdir[sizeof(task_path) + sizeof(int) * 3];
1079         DIR *dir;
1080         unsigned int ntid = 0, nerr = 0;
1081
1082         if (followfork && tcp->pid != strace_child &&
1083             xsprintf(procdir, task_path, tcp->pid) > 0 &&
1084             (dir = opendir(procdir)) != NULL) {
1085                 struct_dirent *de;
1086
1087                 while ((de = read_dir(dir)) != NULL) {
1088                         if (de->d_fileno == 0)
1089                                 continue;
1090
1091                         int tid = string_to_uint(de->d_name);
1092                         if (tid <= 0 || tid == tcp->pid)
1093                                 continue;
1094
1095                         ++ntid;
1096                         if (ptrace_attach_or_seize(tid) < 0) {
1097                                 ++nerr;
1098                                 debug_perror_msg("attach: ptrace(%s, %d)",
1099                                                  ptrace_attach_cmd, tid);
1100                                 continue;
1101                         }
1102
1103                         after_successful_attach(alloctcb(tid),
1104                                                 TCB_GRABBED | post_attach_sigstop);
1105                         debug_msg("attach to pid %d succeeded", tid);
1106                 }
1107
1108                 closedir(dir);
1109         }
1110
1111         if (!qflag) {
1112                 if (ntid > nerr)
1113                         error_msg("Process %u attached"
1114                                   " with %u threads",
1115                                   tcp->pid, ntid - nerr + 1);
1116                 else
1117                         error_msg("Process %u attached",
1118                                   tcp->pid);
1119         }
1120 }
1121
1122 static void
1123 startup_attach(void)
1124 {
1125         pid_t parent_pid = strace_tracer_pid;
1126         unsigned int tcbi;
1127         struct tcb *tcp;
1128
1129         if (daemonized_tracer) {
1130                 pid_t pid = fork();
1131                 if (pid < 0)
1132                         perror_func_msg_and_die("fork");
1133
1134                 if (pid) { /* parent */
1135                         /*
1136                          * Wait for grandchild to attach to straced process
1137                          * (grandparent). Grandchild SIGKILLs us after it attached.
1138                          * Grandparent's wait() is unblocked by our death,
1139                          * it proceeds to exec the straced program.
1140                          */
1141                         pause();
1142                         _exit(0); /* paranoia */
1143                 }
1144                 /* grandchild */
1145                 /* We will be the tracer process. Remember our new pid: */
1146                 strace_tracer_pid = getpid();
1147
1148                 switch (daemonized_tracer) {
1149                 case DAEMONIZE_NEW_PGROUP:
1150                         /*
1151                          * If -D is passed twice, create a new process group,
1152                          * so we won't be killed by kill(0, ...).
1153                          */
1154                         if (setpgid(0, 0) < 0)
1155                                 perror_msg_and_die("Cannot create a new"
1156                                                    " process group");
1157                         break;
1158                 case DAEMONIZE_NEW_SESSION:
1159                         /*
1160                          * If -D is passed thrice, create a new session,
1161                          * so we won't be killed upon session termination.
1162                          */
1163                         if (setsid() < 0)
1164                                 perror_msg_and_die("Cannot create a new"
1165                                                    " session");
1166                         break;
1167                 }
1168         }
1169
1170         for (tcbi = 0; tcbi < tcbtabsize; tcbi++) {
1171                 tcp = tcbtab[tcbi];
1172
1173                 if (!tcp->pid)
1174                         continue;
1175
1176                 /* Is this a process we should attach to, but not yet attached? */
1177                 if (tcp->flags & TCB_ATTACHED)
1178                         continue; /* no, we already attached it */
1179
1180                 if (tcp->pid == parent_pid || tcp->pid == strace_tracer_pid) {
1181                         errno = EPERM;
1182                         perror_msg("attach: pid %d", tcp->pid);
1183                         droptcb(tcp);
1184                         continue;
1185                 }
1186
1187                 attach_tcb(tcp);
1188
1189                 if (interrupted)
1190                         return;
1191         } /* for each tcbtab[] */
1192
1193         if (daemonized_tracer) {
1194                 /*
1195                  * Make parent go away.
1196                  * Also makes grandparent's wait() unblock.
1197                  */
1198                 kill(parent_pid, SIGKILL);
1199                 strace_child = 0;
1200         }
1201 }
1202
1203 /* Stack-o-phobic exec helper, in the hope to work around
1204  * NOMMU + "daemonized tracer" difficulty.
1205  */
1206 struct exec_params {
1207         int fd_to_close;
1208         uid_t run_euid;
1209         gid_t run_egid;
1210         char **argv;
1211         char *pathname;
1212         struct sigaction child_sa;
1213 };
1214 static struct exec_params params_for_tracee;
1215
1216 static void ATTRIBUTE_NOINLINE ATTRIBUTE_NORETURN
1217 exec_or_die(void)
1218 {
1219         struct exec_params *params = &params_for_tracee;
1220
1221         if (params->fd_to_close >= 0)
1222                 close(params->fd_to_close);
1223         if (!daemonized_tracer && !use_seize) {
1224                 if (ptrace(PTRACE_TRACEME, 0L, 0L, 0L) < 0) {
1225                         perror_msg_and_die("ptrace(PTRACE_TRACEME, ...)");
1226                 }
1227         }
1228
1229         if (username != NULL) {
1230                 /*
1231                  * It is important to set groups before we
1232                  * lose privileges on setuid.
1233                  */
1234                 if (initgroups(username, run_gid) < 0) {
1235                         perror_msg_and_die("initgroups");
1236                 }
1237                 if (setregid(run_gid, params->run_egid) < 0) {
1238                         perror_msg_and_die("setregid");
1239                 }
1240                 if (setreuid(run_uid, params->run_euid) < 0) {
1241                         perror_msg_and_die("setreuid");
1242                 }
1243         } else if (geteuid() != 0)
1244                 if (setreuid(run_uid, run_uid) < 0) {
1245                         perror_msg_and_die("setreuid");
1246                 }
1247
1248         if (!daemonized_tracer) {
1249                 /*
1250                  * Induce a ptrace stop. Tracer (our parent)
1251                  * will resume us with PTRACE_SYSCALL and display
1252                  * the immediately following execve syscall.
1253                  * Can't do this on NOMMU systems, we are after
1254                  * vfork: parent is blocked, stopping would deadlock.
1255                  */
1256                 if (!NOMMU_SYSTEM)
1257                         kill(getpid(), SIGSTOP);
1258         } else {
1259                 alarm(3);
1260                 /* we depend on SIGCHLD set to SIG_DFL by init code */
1261                 /* if it happens to be SIG_IGN'ed, wait won't block */
1262                 wait(NULL);
1263                 alarm(0);
1264         }
1265
1266         if (params_for_tracee.child_sa.sa_handler != SIG_DFL)
1267                 sigaction(SIGCHLD, &params_for_tracee.child_sa, NULL);
1268
1269         debug_msg("seccomp filter %s",
1270                   seccomp_filtering ? "enabled" : "disabled");
1271         if (seccomp_filtering)
1272                 init_seccomp_filter();
1273         execv(params->pathname, params->argv);
1274         perror_msg_and_die("exec");
1275 }
1276
1277 /*
1278  * Open a dummy descriptor for use as a placeholder.
1279  * The descriptor is O_RDONLY with FD_CLOEXEC flag set.
1280  * A read attempt from such descriptor ends with EOF,
1281  * a write attempt is rejected with EBADF.
1282  */
1283 static int
1284 open_dummy_desc(void)
1285 {
1286         int fds[2];
1287
1288         if (pipe(fds))
1289                 perror_func_msg_and_die("pipe");
1290         close(fds[1]);
1291         set_cloexec_flag(fds[0]);
1292         return fds[0];
1293 }
1294
1295 /* placeholder fds status for stdin and stdout */
1296 static bool fd_is_placeholder[2];
1297
1298 /*
1299  * Ensure that all standard file descriptors are open by opening placeholder
1300  * file descriptors for those standard file descriptors that are not open.
1301  *
1302  * The information which descriptors have been made open is saved
1303  * in fd_is_placeholder for later use.
1304  */
1305 static void
1306 ensure_standard_fds_opened(void)
1307 {
1308         int fd;
1309
1310         while ((fd = open_dummy_desc()) <= 2) {
1311                 if (fd == 2)
1312                         break;
1313                 fd_is_placeholder[fd] = true;
1314         }
1315
1316         if (fd > 2)
1317                 close(fd);
1318 }
1319
1320 /*
1321  * Redirect stdin and stdout unless they have been opened earlier
1322  * by ensure_standard_fds_opened as placeholders.
1323  */
1324 static void
1325 redirect_standard_fds(void)
1326 {
1327         int i;
1328
1329         /*
1330          * It might be a good idea to redirect stderr as well,
1331          * but we sometimes need to print error messages.
1332          */
1333         for (i = 0; i <= 1; ++i) {
1334                 if (!fd_is_placeholder[i]) {
1335                         close(i);
1336                         open_dummy_desc();
1337                 }
1338         }
1339 }
1340
1341 static void
1342 startup_child(char **argv)
1343 {
1344         strace_stat_t statbuf;
1345         const char *filename;
1346         size_t filename_len;
1347         char pathname[PATH_MAX];
1348         int pid;
1349         struct tcb *tcp;
1350
1351         filename = argv[0];
1352         filename_len = strlen(filename);
1353
1354         if (filename_len > sizeof(pathname) - 1) {
1355                 errno = ENAMETOOLONG;
1356                 perror_msg_and_die("exec");
1357         }
1358         if (strchr(filename, '/')) {
1359                 strcpy(pathname, filename);
1360         }
1361 #ifdef USE_DEBUGGING_EXEC
1362         /*
1363          * Debuggers customarily check the current directory
1364          * first regardless of the path but doing that gives
1365          * security geeks a panic attack.
1366          */
1367         else if (stat_file(filename, &statbuf) == 0)
1368                 strcpy(pathname, filename);
1369 #endif /* USE_DEBUGGING_EXEC */
1370         else {
1371                 const char *path;
1372                 size_t m, n, len;
1373
1374                 for (path = getenv("PATH"); path && *path; path += m) {
1375                         const char *colon = strchr(path, ':');
1376                         if (colon) {
1377                                 n = colon - path;
1378                                 m = n + 1;
1379                         } else
1380                                 m = n = strlen(path);
1381                         if (n == 0) {
1382                                 if (!getcwd(pathname, PATH_MAX))
1383                                         continue;
1384                                 len = strlen(pathname);
1385                         } else if (n > sizeof(pathname) - 1)
1386                                 continue;
1387                         else {
1388                                 strncpy(pathname, path, n);
1389                                 len = n;
1390                         }
1391                         if (len && pathname[len - 1] != '/')
1392                                 pathname[len++] = '/';
1393                         if (filename_len + len > sizeof(pathname) - 1)
1394                                 continue;
1395                         strcpy(pathname + len, filename);
1396                         if (stat_file(pathname, &statbuf) == 0 &&
1397                             /* Accept only regular files
1398                                with some execute bits set.
1399                                XXX not perfect, might still fail */
1400                             S_ISREG(statbuf.st_mode) &&
1401                             (statbuf.st_mode & 0111))
1402                                 break;
1403                 }
1404                 if (!path || !*path)
1405                         pathname[0] = '\0';
1406         }
1407         if (stat_file(pathname, &statbuf) < 0) {
1408                 perror_msg_and_die("Can't stat '%s'", filename);
1409         }
1410
1411         params_for_tracee.fd_to_close = (shared_log != stderr) ? fileno(shared_log) : -1;
1412         params_for_tracee.run_euid = (statbuf.st_mode & S_ISUID) ? statbuf.st_uid : run_uid;
1413         params_for_tracee.run_egid = (statbuf.st_mode & S_ISGID) ? statbuf.st_gid : run_gid;
1414         params_for_tracee.argv = argv;
1415         /*
1416          * On NOMMU, can be safely freed only after execve in tracee.
1417          * It's hard to know when that happens, so we just leak it.
1418          */
1419         params_for_tracee.pathname = NOMMU_SYSTEM ? xstrdup(pathname) : pathname;
1420
1421 #if defined HAVE_PRCTL && defined PR_SET_PTRACER && defined PR_SET_PTRACER_ANY
1422         if (daemonized_tracer)
1423                 prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY);
1424 #endif
1425
1426         pid = fork();
1427         if (pid < 0)
1428                 perror_func_msg_and_die("fork");
1429
1430         if ((pid != 0 && daemonized_tracer)
1431          || (pid == 0 && !daemonized_tracer)
1432         ) {
1433                 /* We are to become the tracee. Two cases:
1434                  * -D: we are parent
1435                  * not -D: we are child
1436                  */
1437                 exec_or_die();
1438         }
1439
1440         /* We are the tracer */
1441
1442         if (!daemonized_tracer) {
1443                 strace_child = pid;
1444                 if (!use_seize) {
1445                         /* child did PTRACE_TRACEME, nothing to do in parent */
1446                 } else {
1447                         if (!NOMMU_SYSTEM) {
1448                                 /* Wait until child stopped itself */
1449                                 int status;
1450                                 while (waitpid(pid, &status, WSTOPPED) < 0) {
1451                                         if (errno == EINTR)
1452                                                 continue;
1453                                         perror_msg_and_die("waitpid");
1454                                 }
1455                                 if (!WIFSTOPPED(status) || WSTOPSIG(status) != SIGSTOP) {
1456                                         kill_save_errno(pid, SIGKILL);
1457                                         perror_msg_and_die("Unexpected wait status %#x",
1458                                                            status);
1459                                 }
1460                         }
1461                         /* Else: NOMMU case, we have no way to sync.
1462                          * Just attach to it as soon as possible.
1463                          * This means that we may miss a few first syscalls...
1464                          */
1465
1466                         if (ptrace_attach_or_seize(pid)) {
1467                                 kill_save_errno(pid, SIGKILL);
1468                                 perror_msg_and_die("attach: ptrace(%s, %d)",
1469                                                    ptrace_attach_cmd, pid);
1470                         }
1471                         if (!NOMMU_SYSTEM)
1472                                 kill(pid, SIGCONT);
1473                 }
1474                 tcp = alloctcb(pid);
1475                 after_successful_attach(tcp, TCB_SKIP_DETACH_ON_FIRST_EXEC
1476                                              | (NOMMU_SYSTEM ? 0
1477                                                 : (TCB_HIDE_LOG
1478                                                    | post_attach_sigstop)));
1479         } else {
1480                 /* With -D, we are *child* here, the tracee is our parent. */
1481                 strace_child = strace_tracer_pid;
1482                 strace_tracer_pid = getpid();
1483                 tcp = alloctcb(strace_child);
1484                 tcp->flags |= TCB_SKIP_DETACH_ON_FIRST_EXEC | TCB_HIDE_LOG;
1485                 /*
1486                  * Attaching will be done later, by startup_attach.
1487                  * Note: we don't do after_successful_attach() here either!
1488                  */
1489
1490                 /* NOMMU BUG! -D mode is active, we (child) return,
1491                  * and we will scribble over parent's stack!
1492                  * When parent later unpauses, it segfaults.
1493                  *
1494                  * We work around it
1495                  * (1) by declaring exec_or_die() NORETURN,
1496                  * hopefully compiler will just jump to it
1497                  * instead of call (won't push anything to stack),
1498                  * (2) by trying very hard in exec_or_die()
1499                  * to not use any stack,
1500                  * (3) having a really big (PATH_MAX) stack object
1501                  * in this function, which creates a "buffer" between
1502                  * child's and parent's stack pointers.
1503                  * This may save us if (1) and (2) failed
1504                  * and compiler decided to use stack in exec_or_die() anyway
1505                  * (happens on i386 because of stack parameter passing).
1506                  *
1507                  * A cleaner solution is to use makecontext + setcontext
1508                  * to create a genuine separate stack and execute on it.
1509                  */
1510         }
1511
1512         if (seccomp_filtering)
1513                 tcp->flags |= TCB_SECCOMP_FILTER;
1514
1515         /*
1516          * A case where straced process is part of a pipe:
1517          * { sleep 1; yes | head -n99999; } | strace -o/dev/null sh -c 'exec <&-; sleep 9'
1518          * If strace won't close its fd#0, closing it in tracee is not enough:
1519          * the pipe is still open, it has a reader. Thus, "head" will not get its
1520          * SIGPIPE at once, on the first write.
1521          *
1522          * Preventing it by redirecting strace's stdin/out.
1523          * (Don't leave fds 0 and 1 closed, this is bad practice: future opens
1524          * will reuse them, unexpectedly making a newly opened object "stdin").
1525          */
1526         redirect_standard_fds();
1527 }
1528
1529 static void
1530 test_ptrace_seize(void)
1531 {
1532         int pid;
1533
1534         /* Need fork for test. NOMMU has no forks */
1535         if (NOMMU_SYSTEM) {
1536                 post_attach_sigstop = 0; /* this sets use_seize to 1 */
1537                 return;
1538         }
1539
1540         pid = fork();
1541         if (pid < 0)
1542                 perror_func_msg_and_die("fork");
1543
1544         if (pid == 0) {
1545                 pause();
1546                 _exit(0);
1547         }
1548
1549         /* PTRACE_SEIZE, unlike ATTACH, doesn't force tracee to trap.  After
1550          * attaching tracee continues to run unless a trap condition occurs.
1551          * PTRACE_SEIZE doesn't affect signal or group stop state.
1552          */
1553         if (ptrace(PTRACE_SEIZE, pid, 0, 0) == 0) {
1554                 post_attach_sigstop = 0; /* this sets use_seize to 1 */
1555         } else {
1556                 debug_msg("PTRACE_SEIZE doesn't work");
1557         }
1558
1559         kill(pid, SIGKILL);
1560
1561         while (1) {
1562                 int status, tracee_pid;
1563
1564                 errno = 0;
1565                 tracee_pid = waitpid(pid, &status, 0);
1566                 if (tracee_pid <= 0) {
1567                         if (errno == EINTR)
1568                                 continue;
1569                         perror_func_msg_and_die("unexpected wait result %d",
1570                                                 tracee_pid);
1571                 }
1572                 if (WIFSIGNALED(status))
1573                         return;
1574
1575                 error_func_msg_and_die("unexpected wait status %#x", status);
1576         }
1577 }
1578
1579 static unsigned int
1580 get_os_release(void)
1581 {
1582         struct utsname u;
1583         if (uname(&u) < 0)
1584                 perror_msg_and_die("uname");
1585         /*
1586          * u.release string consists of at most three parts
1587          * and normally has this form: "3.2.9[-some-garbage]",
1588          * "X.Y-something" means "X.Y.0".
1589          */
1590         const char *p = u.release;
1591         unsigned int rel = 0;
1592         for (unsigned int parts = 0; parts < 3; ++parts) {
1593                 unsigned int n = 0;
1594                 for (; (*p >= '0') && (*p <= '9'); ++p) {
1595                         n *= 10;
1596                         n += *p - '0';
1597                 }
1598                 rel <<= 8;
1599                 rel |= n;
1600                 if (*p == '.')
1601                         ++p;
1602         }
1603         return rel;
1604 }
1605
1606 static void
1607 set_sighandler(int signo, void (*sighandler)(int), struct sigaction *oldact)
1608 {
1609         const struct sigaction sa = { .sa_handler = sighandler };
1610         sigaction(signo, &sa, oldact);
1611 }
1612
1613 /*
1614  * Initialization part of main() was eating much stack (~0.5k),
1615  * which was unused after init.
1616  * We can reuse it if we move init code into a separate function.
1617  *
1618  * Don't want main() to inline us and defeat the reason
1619  * we have a separate function.
1620  */
1621 static void ATTRIBUTE_NOINLINE
1622 init(int argc, char *argv[])
1623 {
1624         int c, i;
1625         int optF = 0, zflags = 0;
1626
1627         if (!program_invocation_name || !*program_invocation_name) {
1628                 static char name[] = "strace";
1629                 program_invocation_name =
1630                         (argc > 0 && argv[0] && *argv[0]) ? argv[0] : name;
1631         }
1632
1633         strace_tracer_pid = getpid();
1634
1635         os_release = get_os_release();
1636
1637         shared_log = stderr;
1638         set_sortby(DEFAULT_SORTBY);
1639         set_personality(DEFAULT_PERSONALITY);
1640         qualify("trace=all");
1641         qualify("abbrev=all");
1642         qualify("verbose=all");
1643         qualify("status=all");
1644 #if DEFAULT_QUAL_FLAGS != (QUAL_TRACE | QUAL_ABBREV | QUAL_VERBOSE)
1645 # error Bug in DEFAULT_QUAL_FLAGS
1646 #endif
1647         qualify("signal=all");
1648
1649         static const char optstring[] = "+"
1650 #ifdef ENABLE_STACKTRACE
1651             "k"
1652 #endif
1653             "a:Ab:cCdDe:E:fFhiI:o:O:p:P:qrs:S:tTu:vVwxX:yzZ";
1654
1655         enum {
1656                 SECCOMP_OPTION = 0x100
1657         };
1658         static const struct option longopts[] = {
1659                 { "seccomp-bpf", no_argument, 0, SECCOMP_OPTION },
1660                 { "help", no_argument, 0, 'h' },
1661                 { "version", no_argument, 0, 'V' },
1662                 { 0, 0, 0, 0 }
1663         };
1664
1665         while ((c = getopt_long(argc, argv, optstring, longopts, NULL)) != EOF) {
1666                 switch (c) {
1667                 case 'a':
1668                         acolumn = string_to_uint(optarg);
1669                         if (acolumn < 0)
1670                                 error_opt_arg(c, optarg);
1671                         break;
1672                 case 'A':
1673                         open_append = true;
1674                         break;
1675                 case 'b':
1676                         if (strcmp(optarg, "execve") != 0)
1677                                 error_msg_and_die("Syscall '%s' for -b isn't supported",
1678                                         optarg);
1679                         detach_on_execve = 1;
1680                         break;
1681                 case 'c':
1682                         if (cflag == CFLAG_BOTH) {
1683                                 error_msg_and_help("-c and -C are mutually exclusive");
1684                         }
1685                         cflag = CFLAG_ONLY_STATS;
1686                         break;
1687                 case 'C':
1688                         if (cflag == CFLAG_ONLY_STATS) {
1689                                 error_msg_and_help("-c and -C are mutually exclusive");
1690                         }
1691                         cflag = CFLAG_BOTH;
1692                         break;
1693                 case 'd':
1694                         debug_flag = 1;
1695                         break;
1696                 case 'D':
1697                         daemonized_tracer++;
1698                         break;
1699                 case 'e':
1700                         qualify(optarg);
1701                         break;
1702                 case 'E':
1703                         if (putenv(optarg) < 0)
1704                                 perror_msg_and_die("putenv");
1705                         break;
1706                 case 'f':
1707                         followfork++;
1708                         break;
1709                 case 'F':
1710                         optF = 1;
1711                         break;
1712                 case 'h':
1713                         usage();
1714                         break;
1715                 case 'i':
1716                         iflag = 1;
1717                         break;
1718                 case 'I':
1719                         opt_intr = string_to_uint_upto(optarg, NUM_INTR_OPTS - 1);
1720                         if (opt_intr <= 0)
1721                                 error_opt_arg(c, optarg);
1722                         break;
1723 #ifdef ENABLE_STACKTRACE
1724                 case 'k':
1725                         stack_trace_enabled = true;
1726                         break;
1727 #endif
1728                 case 'o':
1729                         outfname = optarg;
1730                         break;
1731                 case 'O':
1732                         if (set_overhead(optarg) < 0)
1733                                 error_opt_arg(c, optarg);
1734                         break;
1735                 case 'p':
1736                         process_opt_p_list(optarg);
1737                         break;
1738                 case 'P':
1739                         pathtrace_select(optarg);
1740                         break;
1741                 case 'q':
1742                         qflag++;
1743                         break;
1744                 case 'r':
1745                         rflag = 1;
1746                         break;
1747                 case 's':
1748                         i = string_to_uint(optarg);
1749                         if (i < 0 || (unsigned int) i > -1U / 4)
1750                                 error_opt_arg(c, optarg);
1751                         max_strlen = i;
1752                         break;
1753                 case 'S':
1754                         set_sortby(optarg);
1755                         break;
1756                 case 't':
1757                         tflag++;
1758                         break;
1759                 case 'T':
1760                         Tflag = 1;
1761                         break;
1762                 case 'u':
1763                         username = optarg;
1764                         break;
1765                 case 'v':
1766                         qualify("abbrev=none");
1767                         break;
1768                 case 'V':
1769                         print_version();
1770                         exit(0);
1771                         break;
1772                 case 'w':
1773                         count_wallclock = 1;
1774                         break;
1775                 case 'x':
1776                         xflag++;
1777                         break;
1778                 case 'X':
1779                         if (!strcmp(optarg, "raw"))
1780                                 xlat_verbosity = XLAT_STYLE_RAW;
1781                         else if (!strcmp(optarg, "abbrev"))
1782                                 xlat_verbosity = XLAT_STYLE_ABBREV;
1783                         else if (!strcmp(optarg, "verbose"))
1784                                 xlat_verbosity = XLAT_STYLE_VERBOSE;
1785                         else
1786                                 error_opt_arg(c, optarg);
1787                         break;
1788                 case 'y':
1789                         show_fd_path++;
1790                         break;
1791                 case 'z':
1792                         clear_number_set_array(status_set, 1);
1793                         add_number_to_set(STATUS_SUCCESSFUL, status_set);
1794                         zflags++;
1795                         break;
1796                 case 'Z':
1797                         clear_number_set_array(status_set, 1);
1798                         add_number_to_set(STATUS_FAILED, status_set);
1799                         zflags++;
1800                         break;
1801                 case SECCOMP_OPTION:
1802                         seccomp_filtering = true;
1803                         break;
1804                 default:
1805                         error_msg_and_help(NULL);
1806                         break;
1807                 }
1808         }
1809
1810         argv += optind;
1811         argc -= optind;
1812
1813         if (argc < 0 || (!nprocs && !argc)) {
1814                 error_msg_and_help("must have PROG [ARGS] or -p PID");
1815         }
1816
1817         if (!argc && daemonized_tracer) {
1818                 error_msg_and_help("PROG [ARGS] must be specified with -D");
1819         }
1820
1821         if (daemonized_tracer > (unsigned int) MAX_DAEMONIZE_OPTS)
1822                 error_msg_and_help("Too many -D's (%u), maximum supported -D "
1823                                    "count is %d",
1824                                    daemonized_tracer, MAX_DAEMONIZE_OPTS);
1825
1826         if (seccomp_filtering && detach_on_execve) {
1827                 error_msg("--seccomp-bpf is not enabled because"
1828                           " it is not compatible with -b");
1829                 seccomp_filtering = false;
1830         }
1831
1832         if (seccomp_filtering) {
1833                 if (nprocs && (!argc || debug_flag))
1834                         error_msg("--seccomp-bpf is not enabled for processes"
1835                                   " attached with -p");
1836                 if (!followfork) {
1837                         error_msg("--seccomp-bpf implies -f");
1838                         followfork = 1;
1839                 }
1840         }
1841
1842         if (optF) {
1843                 if (followfork) {
1844                         error_msg("deprecated option -F ignored");
1845                 } else {
1846                         error_msg("option -F is deprecated, "
1847                                   "please use -f instead");
1848                         followfork = optF;
1849                 }
1850         }
1851
1852         if (followfork >= 2 && cflag) {
1853                 error_msg_and_help("(-c or -C) and -ff are mutually exclusive");
1854         }
1855
1856         if (count_wallclock && !cflag) {
1857                 error_msg_and_help("-w must be given with (-c or -C)");
1858         }
1859
1860         if (cflag == CFLAG_ONLY_STATS) {
1861                 if (iflag)
1862                         error_msg("-%c has no effect with -c", 'i');
1863                 if (stack_trace_enabled)
1864                         error_msg("-%c has no effect with -c", 'k');
1865                 if (rflag)
1866                         error_msg("-%c has no effect with -c", 'r');
1867                 if (tflag)
1868                         error_msg("-%c has no effect with -c", 't');
1869                 if (Tflag)
1870                         error_msg("-%c has no effect with -c", 'T');
1871                 if (show_fd_path)
1872                         error_msg("-%c has no effect with -c", 'y');
1873         }
1874
1875 #ifndef HAVE_OPEN_MEMSTREAM
1876         if (!is_complete_set(status_set, NUMBER_OF_STATUSES))
1877                 error_msg_and_help("open_memstream is required to use -z, -Z, or -e status");
1878 #endif
1879
1880         if (zflags > 1)
1881                 error_msg("Only the last of -z/-Z options will take effect. "
1882                           "See status qualifier for more complex filters.");
1883
1884         acolumn_spaces = xmalloc(acolumn + 1);
1885         memset(acolumn_spaces, ' ', acolumn);
1886         acolumn_spaces[acolumn] = '\0';
1887
1888         set_sighandler(SIGCHLD, SIG_DFL, &params_for_tracee.child_sa);
1889
1890 #ifdef ENABLE_STACKTRACE
1891         if (stack_trace_enabled)
1892                 unwind_init();
1893 #endif
1894
1895         /* See if they want to run as another user. */
1896         if (username != NULL) {
1897                 struct passwd *pent;
1898
1899                 if (getuid() != 0 || geteuid() != 0) {
1900                         error_msg_and_die("You must be root to use the -u option");
1901                 }
1902                 pent = getpwnam(username);
1903                 if (pent == NULL) {
1904                         error_msg_and_die("Cannot find user '%s'", username);
1905                 }
1906                 run_uid = pent->pw_uid;
1907                 run_gid = pent->pw_gid;
1908         } else {
1909                 run_uid = getuid();
1910                 run_gid = getgid();
1911         }
1912
1913         if (followfork)
1914                 ptrace_setoptions |= PTRACE_O_TRACECLONE |
1915                                      PTRACE_O_TRACEFORK |
1916                                      PTRACE_O_TRACEVFORK;
1917
1918         if (seccomp_filtering)
1919                 check_seccomp_filter();
1920         if (seccomp_filtering)
1921                 ptrace_setoptions |= PTRACE_O_TRACESECCOMP;
1922
1923         debug_msg("ptrace_setoptions = %#x", ptrace_setoptions);
1924         test_ptrace_seize();
1925         test_ptrace_get_syscall_info();
1926
1927         /*
1928          * Is something weird with our stdin and/or stdout -
1929          * for example, may they be not open? In this case,
1930          * ensure that none of the future opens uses them.
1931          *
1932          * This was seen in the wild when /proc/sys/kernel/core_pattern
1933          * was set to "|/bin/strace -o/tmp/LOG PROG":
1934          * kernel runs coredump helper with fd#0 open but fd#1 closed (!),
1935          * therefore LOG gets opened to fd#1, and fd#1 is closed by
1936          * "don't hold up stdin/out open" code soon after.
1937          */
1938         ensure_standard_fds_opened();
1939
1940         /* Check if they want to redirect the output. */
1941         if (outfname) {
1942                 /* See if they want to pipe the output. */
1943                 if (outfname[0] == '|' || outfname[0] == '!') {
1944                         /*
1945                          * We can't do the <outfname>.PID funny business
1946                          * when using popen, so prohibit it.
1947                          */
1948                         if (followfork >= 2)
1949                                 error_msg_and_help("piping the output and -ff "
1950                                                    "are mutually exclusive");
1951                         shared_log = strace_popen(outfname + 1);
1952                 } else if (followfork < 2) {
1953                         shared_log = strace_fopen(outfname);
1954                 } else if (strlen(outfname) >= PATH_MAX - sizeof(int) * 3) {
1955                         errno = ENAMETOOLONG;
1956                         perror_msg_and_die("%s", outfname);
1957                 }
1958         } else {
1959                 /* -ff without -o FILE is the same as single -f */
1960                 if (followfork >= 2)
1961                         followfork = 1;
1962         }
1963
1964         if (!outfname || outfname[0] == '|' || outfname[0] == '!') {
1965                 setvbuf(shared_log, NULL, _IOLBF, 0);
1966         }
1967
1968         /*
1969          * argv[0]      -pPID   -oFILE  Default interactive setting
1970          * yes          *       0       INTR_WHILE_WAIT
1971          * no           1       0       INTR_WHILE_WAIT
1972          * yes          *       1       INTR_NEVER
1973          * no           1       1       INTR_WHILE_WAIT
1974          */
1975
1976         if (daemonized_tracer && !opt_intr)
1977                 opt_intr = INTR_BLOCK_TSTP_TOO;
1978         if (outfname && argc) {
1979                 if (!opt_intr)
1980                         opt_intr = INTR_NEVER;
1981                 if (!qflag)
1982                         qflag = 1;
1983         }
1984         if (!opt_intr)
1985                 opt_intr = INTR_WHILE_WAIT;
1986
1987         /*
1988          * startup_child() must be called before the signal handlers get
1989          * installed below as they are inherited into the spawned process.
1990          * Also we do not need to be protected by them as during interruption
1991          * in the startup_child() mode we kill the spawned process anyway.
1992          */
1993         if (argc) {
1994                 startup_child(argv);
1995         }
1996
1997         set_sighandler(SIGTTOU, SIG_IGN, NULL);
1998         set_sighandler(SIGTTIN, SIG_IGN, NULL);
1999         if (opt_intr != INTR_ANYWHERE) {
2000                 if (opt_intr == INTR_BLOCK_TSTP_TOO)
2001                         set_sighandler(SIGTSTP, SIG_IGN, NULL);
2002                 /*
2003                  * In interactive mode (if no -o OUTFILE, or -p PID is used),
2004                  * fatal signals are handled asynchronously and acted
2005                  * when waiting for process state changes.
2006                  * In non-interactive mode these signals are ignored.
2007                  */
2008                 set_sighandler(SIGHUP, interactive ? interrupt : SIG_IGN, NULL);
2009                 set_sighandler(SIGINT, interactive ? interrupt : SIG_IGN, NULL);
2010                 set_sighandler(SIGQUIT, interactive ? interrupt : SIG_IGN, NULL);
2011                 set_sighandler(SIGPIPE, interactive ? interrupt : SIG_IGN, NULL);
2012                 set_sighandler(SIGTERM, interactive ? interrupt : SIG_IGN, NULL);
2013         }
2014
2015         sigemptyset(&timer_set);
2016         sigaddset(&timer_set, SIGALRM);
2017         sigprocmask(SIG_BLOCK, &timer_set, NULL);
2018         set_sighandler(SIGALRM, timer_sighandler, NULL);
2019
2020         if (nprocs != 0 || daemonized_tracer)
2021                 startup_attach();
2022
2023         /* Do we want pids printed in our -o OUTFILE?
2024          * -ff: no (every pid has its own file); or
2025          * -f: yes (there can be more pids in the future); or
2026          * -p PID1,PID2: yes (there are already more than one pid)
2027          */
2028         print_pid_pfx = (outfname && followfork < 2 && (followfork == 1 || nprocs > 1));
2029 }
2030
2031 static struct tcb *
2032 pid2tcb(const int pid)
2033 {
2034         if (pid <= 0)
2035                 return NULL;
2036
2037 #define PID2TCB_CACHE_SIZE 1024U
2038 #define PID2TCB_CACHE_MASK (PID2TCB_CACHE_SIZE - 1)
2039
2040         static struct tcb *pid2tcb_cache[PID2TCB_CACHE_SIZE];
2041         struct tcb **const ptcp = &pid2tcb_cache[pid & PID2TCB_CACHE_MASK];
2042         struct tcb *tcp = *ptcp;
2043
2044         if (tcp && tcp->pid == pid)
2045                 return tcp;
2046
2047         for (unsigned int i = 0; i < tcbtabsize; ++i) {
2048                 tcp = tcbtab[i];
2049                 if (tcp->pid == pid)
2050                         return *ptcp = tcp;
2051         }
2052
2053         return NULL;
2054 }
2055
2056 static void
2057 cleanup(int fatal_sig)
2058 {
2059         unsigned int i;
2060         struct tcb *tcp;
2061
2062         if (!fatal_sig)
2063                 fatal_sig = SIGTERM;
2064
2065         for (i = 0; i < tcbtabsize; i++) {
2066                 tcp = tcbtab[i];
2067                 if (!tcp->pid)
2068                         continue;
2069                 debug_func_msg("looking at pid %u", tcp->pid);
2070                 if (tcp->pid == strace_child) {
2071                         kill(tcp->pid, SIGCONT);
2072                         kill(tcp->pid, fatal_sig);
2073                 }
2074                 detach(tcp);
2075         }
2076 }
2077
2078 static void
2079 interrupt(int sig)
2080 {
2081         interrupted = sig;
2082 }
2083
2084 static void
2085 print_debug_info(const int pid, int status)
2086 {
2087         const unsigned int event = (unsigned int) status >> 16;
2088         char buf[sizeof("WIFEXITED,exitcode=%u") + sizeof(int)*3 /*paranoia:*/ + 16];
2089         char evbuf[sizeof(",EVENT_VFORK_DONE (%u)") + sizeof(int)*3 /*paranoia:*/ + 16];
2090
2091         strcpy(buf, "???");
2092         if (WIFSIGNALED(status))
2093                 xsprintf(buf, "WIFSIGNALED,%ssig=%s",
2094                                 WCOREDUMP(status) ? "core," : "",
2095                                 sprintsigname(WTERMSIG(status)));
2096         if (WIFEXITED(status))
2097                 xsprintf(buf, "WIFEXITED,exitcode=%u", WEXITSTATUS(status));
2098         if (WIFSTOPPED(status))
2099                 xsprintf(buf, "WIFSTOPPED,sig=%s",
2100                          sprintsigname(WSTOPSIG(status)));
2101         evbuf[0] = '\0';
2102         if (event != 0) {
2103                 static const char *const event_names[] = {
2104                         [PTRACE_EVENT_CLONE] = "CLONE",
2105                         [PTRACE_EVENT_FORK]  = "FORK",
2106                         [PTRACE_EVENT_VFORK] = "VFORK",
2107                         [PTRACE_EVENT_VFORK_DONE] = "VFORK_DONE",
2108                         [PTRACE_EVENT_EXEC]  = "EXEC",
2109                         [PTRACE_EVENT_EXIT]  = "EXIT",
2110                         [PTRACE_EVENT_SECCOMP]  = "SECCOMP",
2111                         /* [PTRACE_EVENT_STOP (=128)] would make biggish array */
2112                 };
2113                 const char *e = "??";
2114                 if (event < ARRAY_SIZE(event_names))
2115                         e = event_names[event];
2116                 else if (event == PTRACE_EVENT_STOP)
2117                         e = "STOP";
2118                 xsprintf(evbuf, ",EVENT_%s (%u)", e, event);
2119         }
2120         error_msg("[wait(0x%06x) = %u] %s%s", status, pid, buf, evbuf);
2121 }
2122
2123 static struct tcb *
2124 maybe_allocate_tcb(const int pid, int status)
2125 {
2126         if (!WIFSTOPPED(status)) {
2127                 if (detach_on_execve && pid == strace_child) {
2128                         /* example: strace -bexecve sh -c 'exec true' */
2129                         strace_child = 0;
2130                         return NULL;
2131                 }
2132                 /*
2133                  * This can happen if we inherited an unknown child.
2134                  * Example: (sleep 1 & exec strace true)
2135                  */
2136                 error_msg("Exit of unknown pid %u ignored", pid);
2137                 return NULL;
2138         }
2139         if (followfork) {
2140                 /* We assume it's a fork/vfork/clone child */
2141                 struct tcb *tcp = alloctcb(pid);
2142                 after_successful_attach(tcp, post_attach_sigstop);
2143                 if (!qflag)
2144                         error_msg("Process %d attached", pid);
2145                 return tcp;
2146         } else {
2147                 /*
2148                  * This can happen if a clone call misused CLONE_PTRACE itself.
2149                  *
2150                  * There used to be a dance around possible re-injection of
2151                  * WSTOPSIG(status), but it was later removed as the only
2152                  * observable stop here is the initial ptrace-stop.
2153                  */
2154                 ptrace(PTRACE_DETACH, pid, NULL, 0L);
2155                 error_msg("Detached unknown pid %d", pid);
2156                 return NULL;
2157         }
2158 }
2159
2160 /*
2161  * Under Linux, execve changes pid to thread leader's pid, and we see this
2162  * changed pid on EVENT_EXEC and later, execve sysexit.  Leader "disappears"
2163  * without exit notification.  Let user know that, drop leader's tcb, and fix
2164  * up pid in execve thread's tcb.  Effectively, execve thread's tcb replaces
2165  * leader's tcb.
2166  *
2167  * BTW, leader is 'stuck undead' (doesn't report WIFEXITED on exit syscall)
2168  * in multi-threaded programs exactly in order to handle this case.
2169  */
2170 static struct tcb *
2171 maybe_switch_tcbs(struct tcb *tcp, const int pid)
2172 {
2173         /*
2174          * PTRACE_GETEVENTMSG returns old pid starting from Linux 3.0.
2175          * On 2.6 and earlier it can return garbage.
2176          */
2177         if (os_release < KERNEL_VERSION(3, 0, 0))
2178                 return NULL;
2179
2180         const long old_pid = tcb_wait_tab[tcp->wait_data_idx].msg;
2181
2182         /* Avoid truncation in pid2tcb() param passing */
2183         if (old_pid <= 0 || old_pid == pid)
2184                 return NULL;
2185         if ((unsigned long) old_pid > UINT_MAX)
2186                 return NULL;
2187         struct tcb *execve_thread = pid2tcb(old_pid);
2188         /* It should be !NULL, but I feel paranoid */
2189         if (!execve_thread)
2190                 return NULL;
2191
2192         if (execve_thread->curcol != 0) {
2193                 /*
2194                  * One case we are here is -ff, try
2195                  * "strace -oLOG -ff test/threaded_execve".
2196                  * Another case is demonstrated by
2197                  * tests/maybe_switch_current_tcp.c
2198                  */
2199                 fprintf(execve_thread->outf, " <pid changed to %d ...>\n", pid);
2200                 /*execve_thread->curcol = 0; - no need, see code below */
2201         }
2202         /* Swap output FILEs and memstream (needed for -ff) */
2203         FILE *fp = execve_thread->outf;
2204         execve_thread->outf = tcp->outf;
2205         tcp->outf = fp;
2206         if (execve_thread->staged_output_data || tcp->staged_output_data) {
2207                 struct staged_output_data *staged_output_data;
2208
2209                 staged_output_data = execve_thread->staged_output_data;
2210                 execve_thread->staged_output_data = tcp->staged_output_data;
2211                 tcp->staged_output_data = staged_output_data;
2212         }
2213
2214         /* And their column positions */
2215         execve_thread->curcol = tcp->curcol;
2216         tcp->curcol = 0;
2217         /* Drop leader, but close execve'd thread outfile (if -ff) */
2218         droptcb(tcp);
2219         /* Switch to the thread, reusing leader's outfile and pid */
2220         tcp = execve_thread;
2221         tcp->pid = pid;
2222         if (cflag != CFLAG_ONLY_STATS) {
2223                 printleader(tcp);
2224                 tprintf("+++ superseded by execve in pid %lu +++\n", old_pid);
2225                 line_ended();
2226                 /*
2227                  * Need to reopen memstream for thread
2228                  * as we closed it in droptcb.
2229                  */
2230                 if (!is_complete_set(status_set, NUMBER_OF_STATUSES))
2231                         strace_open_memstream(tcp);
2232                 tcp->flags |= TCB_REPRINT;
2233         }
2234
2235         return tcp;
2236 }
2237
2238 static struct tcb *
2239 maybe_switch_current_tcp(void)
2240 {
2241         struct tcb *tcp = maybe_switch_tcbs(current_tcp, current_tcp->pid);
2242
2243         if (tcp)
2244                 set_current_tcp(tcp);
2245
2246         return tcp;
2247 }
2248
2249 static void
2250 print_signalled(struct tcb *tcp, const int pid, int status)
2251 {
2252         if (pid == strace_child) {
2253                 exit_code = 0x100 | WTERMSIG(status);
2254                 strace_child = 0;
2255         }
2256
2257         if (cflag != CFLAG_ONLY_STATS
2258             && is_number_in_set(WTERMSIG(status), signal_set)) {
2259                 printleader(tcp);
2260                 tprintf("+++ killed by %s %s+++\n",
2261                         sprintsigname(WTERMSIG(status)),
2262                         WCOREDUMP(status) ? "(core dumped) " : "");
2263                 line_ended();
2264         }
2265 }
2266
2267 static void
2268 print_exited(struct tcb *tcp, const int pid, int status)
2269 {
2270         if (pid == strace_child) {
2271                 exit_code = WEXITSTATUS(status);
2272                 strace_child = 0;
2273         }
2274
2275         if (cflag != CFLAG_ONLY_STATS &&
2276             qflag < 2) {
2277                 printleader(tcp);
2278                 tprintf("+++ exited with %d +++\n", WEXITSTATUS(status));
2279                 line_ended();
2280         }
2281 }
2282
2283 static void
2284 print_stopped(struct tcb *tcp, const siginfo_t *si, const unsigned int sig)
2285 {
2286         if (cflag != CFLAG_ONLY_STATS
2287             && !hide_log(tcp)
2288             && is_number_in_set(sig, signal_set)) {
2289                 printleader(tcp);
2290                 if (si) {
2291                         tprintf("--- %s ", sprintsigname(sig));
2292                         printsiginfo(si);
2293                         tprints(" ---\n");
2294                 } else
2295                         tprintf("--- stopped by %s ---\n", sprintsigname(sig));
2296                 line_ended();
2297
2298 #ifdef ENABLE_STACKTRACE
2299                 if (stack_trace_enabled)
2300                         unwind_tcb_print(tcp);
2301 #endif
2302         }
2303 }
2304
2305 static void
2306 startup_tcb(struct tcb *tcp)
2307 {
2308         debug_msg("pid %d has TCB_STARTUP, initializing it", tcp->pid);
2309
2310         tcp->flags &= ~TCB_STARTUP;
2311
2312         if (!use_seize) {
2313                 debug_msg("setting opts 0x%x on pid %d",
2314                           ptrace_setoptions, tcp->pid);
2315                 if (ptrace(PTRACE_SETOPTIONS, tcp->pid, NULL, ptrace_setoptions) < 0) {
2316                         if (errno != ESRCH) {
2317                                 /* Should never happen, really */
2318                                 perror_msg_and_die("PTRACE_SETOPTIONS");
2319                         }
2320                 }
2321         }
2322
2323         if ((tcp->flags & TCB_GRABBED) && (get_scno(tcp) == 1))
2324                 tcp->s_prev_ent = tcp->s_ent;
2325
2326         if (cflag) {
2327                 tcp->atime = tcp->stime;
2328         }
2329 }
2330
2331 static void
2332 print_event_exit(struct tcb *tcp)
2333 {
2334         if (entering(tcp) || filtered(tcp) || hide_log(tcp)
2335             || cflag == CFLAG_ONLY_STATS) {
2336                 return;
2337         }
2338
2339         if (followfork < 2 && printing_tcp && printing_tcp != tcp
2340             && printing_tcp->curcol != 0) {
2341                 set_current_tcp(printing_tcp);
2342                 tprints(" <unfinished ...>\n");
2343                 flush_tcp_output(printing_tcp);
2344                 printing_tcp->curcol = 0;
2345                 set_current_tcp(tcp);
2346         }
2347
2348         print_syscall_resume(tcp);
2349
2350         if (!(tcp->sys_func_rval & RVAL_DECODED)) {
2351                 /*
2352                  * The decoder has probably decided to print something
2353                  * on exiting syscall which is not going to happen.
2354                  */
2355                 tprints(" <unfinished ...>");
2356         }
2357
2358         printing_tcp = tcp;
2359         tprints(") ");
2360         tabto();
2361         tprints("= ?\n");
2362         if (!is_complete_set(status_set, NUMBER_OF_STATUSES)) {
2363                 bool publish = is_number_in_set(STATUS_UNFINISHED, status_set);
2364                 strace_close_memstream(tcp, publish);
2365         }
2366         line_ended();
2367 }
2368
2369 static size_t
2370 trace_wait_data_size(struct tcb *tcp)
2371 {
2372         return sizeof(struct tcb_wait_data);
2373 }
2374
2375 static struct tcb_wait_data *
2376 init_trace_wait_data(void *p)
2377 {
2378         struct tcb_wait_data *wd = p;
2379
2380         memset(wd, 0, sizeof(*wd));
2381
2382         return wd;
2383 }
2384
2385 static struct tcb_wait_data *
2386 copy_trace_wait_data(const struct tcb_wait_data *wd)
2387 {
2388         struct tcb_wait_data *new_wd = xmalloc(sizeof(*new_wd));
2389
2390         memcpy(new_wd, wd, sizeof(*wd));
2391
2392         return new_wd;
2393 }
2394
2395 static void
2396 free_trace_wait_data(struct tcb_wait_data *wd)
2397 {
2398         free(wd);
2399 }
2400
2401 static void
2402 tcb_wait_tab_check_size(const size_t size)
2403 {
2404         while (size >= tcb_wait_tab_size) {
2405                 tcb_wait_tab = xgrowarray(tcb_wait_tab,
2406                                           &tcb_wait_tab_size,
2407                                           sizeof(tcb_wait_tab[0]));
2408         }
2409 }
2410
2411 static const struct tcb_wait_data *
2412 next_event(void)
2413 {
2414         if (interrupted)
2415                 return NULL;
2416
2417         invalidate_umove_cache();
2418
2419         struct tcb *tcp = NULL;
2420         struct list_item *elem;
2421
2422         static EMPTY_LIST(pending_tcps);
2423         /* Handle the queued tcbs before waiting for new events.  */
2424         if (!list_is_empty(&pending_tcps))
2425                 goto next_event_get_tcp;
2426
2427         static struct tcb *extra_tcp;
2428         static size_t wait_extra_data_idx;
2429         /* Handle the extra tcb event.  */
2430         if (extra_tcp) {
2431                 tcp = extra_tcp;
2432                 extra_tcp = NULL;
2433                 tcp->wait_data_idx = wait_extra_data_idx;
2434
2435                 debug_msg("dequeued extra event for pid %u", tcp->pid);
2436                 goto next_event_exit;
2437         }
2438
2439         /*
2440          * Used to exit simply when nprocs hits zero, but in this testcase:
2441          *  int main(void) { _exit(!!fork()); }
2442          * under strace -f, parent sometimes (rarely) manages
2443          * to exit before we see the first stop of the child,
2444          * and we are losing track of it:
2445          *  19923 clone(...) = 19924
2446          *  19923 exit_group(1)     = ?
2447          *  19923 +++ exited with 1 +++
2448          * Exiting only when wait() returns ECHILD works better.
2449          */
2450         if (popen_pid != 0) {
2451                 /* However, if -o|logger is in use, we can't do that.
2452                  * Can work around that by double-forking the logger,
2453                  * but that loses the ability to wait for its completion
2454                  * on exit. Oh well...
2455                  */
2456                 if (nprocs == 0)
2457                         return NULL;
2458         }
2459
2460         const bool unblock_delay_timer = is_delay_timer_armed();
2461
2462         /*
2463          * The window of opportunity to handle expirations
2464          * of the delay timer opens here.
2465          *
2466          * Unblock the signal handler for the delay timer
2467          * iff the delay timer is already created.
2468          */
2469         if (unblock_delay_timer)
2470                 sigprocmask(SIG_UNBLOCK, &timer_set, NULL);
2471
2472         /*
2473          * If the delay timer has expired, then its expiration
2474          * has been handled already by the signal handler.
2475          *
2476          * If the delay timer expires during wait4(),
2477          * then the system call will be interrupted and
2478          * the expiration will be handled by the signal handler.
2479          */
2480         int status;
2481         struct rusage ru;
2482         int pid = wait4(-1, &status, __WALL, (cflag ? &ru : NULL));
2483         int wait_errno = errno;
2484
2485         /*
2486          * The window of opportunity to handle expirations
2487          * of the delay timer closes here.
2488          *
2489          * Block the signal handler for the delay timer
2490          * iff it was unblocked earlier.
2491          */
2492         if (unblock_delay_timer) {
2493                 sigprocmask(SIG_BLOCK, &timer_set, NULL);
2494
2495                 if (restart_failed)
2496                         return NULL;
2497         }
2498
2499         size_t wait_tab_pos = 0;
2500         bool wait_nohang = false;
2501
2502         /*
2503          * Wait for new events until wait4() returns 0 (meaning that there's
2504          * nothing more to wait for for now), or a second event for some tcb
2505          * appears (which may happen if a tracee was SIGKILL'ed, for example).
2506          */
2507         for (;;) {
2508                 struct tcb_wait_data *wd;
2509
2510                 if (pid < 0) {
2511                         if (wait_errno == EINTR)
2512                                 break;
2513                         if (wait_nohang)
2514                                 break;
2515                         if (nprocs == 0 && wait_errno == ECHILD)
2516                                 return NULL;
2517                         /*
2518                          * If nprocs > 0, ECHILD is not expected,
2519                          * treat it as any other error here:
2520                          */
2521                         errno = wait_errno;
2522                         perror_msg_and_die("wait4(__WALL)");
2523                 }
2524
2525                 if (!pid)
2526                         break;
2527
2528                 if (pid == popen_pid) {
2529                         if (!WIFSTOPPED(status))
2530                                 popen_pid = 0;
2531                         break;
2532                 }
2533
2534                 if (debug_flag)
2535                         print_debug_info(pid, status);
2536
2537                 /* Look up 'pid' in our table. */
2538                 tcp = pid2tcb(pid);
2539
2540                 if (!tcp) {
2541                         tcp = maybe_allocate_tcb(pid, status);
2542                         if (!tcp)
2543                                 goto next_event_wait_next;
2544                 }
2545
2546                 if (cflag) {
2547                         tcp->stime.tv_sec = ru.ru_stime.tv_sec;
2548                         tcp->stime.tv_nsec = ru.ru_stime.tv_usec * 1000;
2549                 }
2550
2551                 tcb_wait_tab_check_size(wait_tab_pos);
2552
2553                 /* Initialise a new wait data structure.  */
2554                 wd = tcb_wait_tab + wait_tab_pos;
2555                 init_trace_wait_data(wd);
2556                 wd->status = status;
2557
2558                 if (WIFSIGNALED(status)) {
2559                         wd->te = TE_SIGNALLED;
2560                 } else if (WIFEXITED(status)) {
2561                         wd->te = TE_EXITED;
2562                 } else {
2563                         /*
2564                          * As WCONTINUED flag has not been specified to wait4,
2565                          * it cannot be WIFCONTINUED(status), so the only case
2566                          * that remains is WIFSTOPPED(status).
2567                          */
2568
2569                         const unsigned int sig = WSTOPSIG(status);
2570                         const unsigned int event = (unsigned int) status >> 16;
2571
2572                         switch (event) {
2573                         case 0:
2574                                 /*
2575                                  * Is this post-attach SIGSTOP?
2576                                  * Interestingly, the process may stop
2577                                  * with STOPSIG equal to some other signal
2578                                  * than SIGSTOP if we happened to attach
2579                                  * just before the process takes a signal.
2580                                  */
2581                                 if (sig == SIGSTOP &&
2582                                     (tcp->flags & TCB_IGNORE_ONE_SIGSTOP)) {
2583                                         debug_func_msg("ignored SIGSTOP on "
2584                                                        "pid %d", tcp->pid);
2585                                         tcp->flags &= ~TCB_IGNORE_ONE_SIGSTOP;
2586                                         wd->te = TE_RESTART;
2587                                 } else if (sig == syscall_trap_sig) {
2588                                         wd->te = TE_SYSCALL_STOP;
2589                                 } else {
2590                                         /*
2591                                          * True if tracee is stopped by signal
2592                                          * (as opposed to "tracee received
2593                                          * signal").
2594                                          * TODO: shouldn't we check for
2595                                          * errno == EINVAL too?
2596                                          * We can get ESRCH instead, you know...
2597                                          */
2598                                         bool stopped = ptrace(PTRACE_GETSIGINFO,
2599                                                 pid, 0, &wd->si) < 0;
2600
2601                                         wd->te = stopped ? TE_GROUP_STOP
2602                                                          : TE_SIGNAL_DELIVERY_STOP;
2603                                 }
2604                                 break;
2605                         case PTRACE_EVENT_STOP:
2606                                 /*
2607                                  * PTRACE_INTERRUPT-stop or group-stop.
2608                                  * PTRACE_INTERRUPT-stop has sig == SIGTRAP here.
2609                                  */
2610                                 switch (sig) {
2611                                 case SIGSTOP:
2612                                 case SIGTSTP:
2613                                 case SIGTTIN:
2614                                 case SIGTTOU:
2615                                         wd->te = TE_GROUP_STOP;
2616                                         break;
2617                                 default:
2618                                         wd->te = TE_RESTART;
2619                                 }
2620                                 break;
2621                         case PTRACE_EVENT_EXEC:
2622                                         /*
2623                                          * TODO: shouldn't we check for
2624                                          * errno == EINVAL here, too?
2625                                          * We can get ESRCH instead, you know...
2626                                          */
2627                                 if (ptrace(PTRACE_GETEVENTMSG, pid, NULL,
2628                                     &wd->msg) < 0)
2629                                         wd->msg = 0;
2630
2631                                 wd->te = TE_STOP_BEFORE_EXECVE;
2632                                 break;
2633                         case PTRACE_EVENT_EXIT:
2634                                 wd->te = TE_STOP_BEFORE_EXIT;
2635                                 break;
2636                         case PTRACE_EVENT_SECCOMP:
2637                                 wd->te = TE_SECCOMP;
2638                                 break;
2639                         default:
2640                                 wd->te = TE_RESTART;
2641                         }
2642                 }
2643
2644                 if (!wd->te)
2645                         error_func_msg("Tracing event hasn't been determined "
2646                                        "for pid %d, status %0#x", pid, status);
2647
2648                 if (!list_is_empty(&tcp->wait_list)) {
2649                         wait_extra_data_idx = wait_tab_pos;
2650                         extra_tcp = tcp;
2651                         debug_func_msg("queued extra pid %d", tcp->pid);
2652                 } else {
2653                         tcp->wait_data_idx = wait_tab_pos;
2654                         list_append(&pending_tcps, &tcp->wait_list);
2655                         debug_func_msg("queued pid %d", tcp->pid);
2656                 }
2657
2658                 wait_tab_pos++;
2659
2660                 if (extra_tcp)
2661                         break;
2662
2663 next_event_wait_next:
2664                 pid = wait4(-1, &status, __WALL | WNOHANG, (cflag ? &ru : NULL));
2665                 wait_errno = errno;
2666                 wait_nohang = true;
2667         }
2668
2669 next_event_get_tcp:
2670         elem = list_remove_head(&pending_tcps);
2671
2672         if (!elem) {
2673                 tcb_wait_tab_check_size(0);
2674                 memset(tcb_wait_tab, 0, sizeof(*tcb_wait_tab));
2675                 tcb_wait_tab->te = TE_NEXT;
2676
2677                 return tcb_wait_tab;
2678         } else {
2679                 tcp = list_elem(elem, struct tcb, wait_list);
2680                 debug_func_msg("dequeued pid %d", tcp->pid);
2681         }
2682
2683 next_event_exit:
2684         /* Is this the very first time we see this tracee stopped? */
2685         if (tcp->flags & TCB_STARTUP)
2686                 startup_tcb(tcp);
2687
2688         clear_regs(tcp);
2689
2690         /* Set current output file */
2691         set_current_tcp(tcp);
2692
2693         return tcb_wait_tab + tcp->wait_data_idx;
2694 }
2695
2696 static int
2697 trace_syscall(struct tcb *tcp, unsigned int *sig)
2698 {
2699         if (entering(tcp)) {
2700                 int res = syscall_entering_decode(tcp);
2701                 switch (res) {
2702                 case 0:
2703                         return 0;
2704                 case 1:
2705                         res = syscall_entering_trace(tcp, sig);
2706                 }
2707                 syscall_entering_finish(tcp, res);
2708                 return res;
2709         } else {
2710                 struct timespec ts = {};
2711                 int res = syscall_exiting_decode(tcp, &ts);
2712                 if (res != 0) {
2713                         res = syscall_exiting_trace(tcp, &ts, res);
2714                 }
2715                 syscall_exiting_finish(tcp);
2716                 return res;
2717         }
2718 }
2719
2720 /* Returns true iff the main trace loop has to continue. */
2721 static bool
2722 dispatch_event(const struct tcb_wait_data *wd)
2723 {
2724         unsigned int restart_op;
2725         unsigned int restart_sig = 0;
2726         enum trace_event te = wd ? wd->te : TE_BREAK;
2727         /*
2728          * Copy wd->status to a non-const variable to workaround glibc bugs
2729          * around union wait fixed by glibc commit glibc-2.24~391
2730          */
2731         int status = wd ? wd->status : 0;
2732
2733         if (current_tcp && has_seccomp_filter(current_tcp))
2734                 restart_op = seccomp_filter_restart_operator(current_tcp);
2735         else
2736                 restart_op = PTRACE_SYSCALL;
2737
2738         switch (te) {
2739         case TE_BREAK:
2740                 return false;
2741
2742         case TE_NEXT:
2743                 return true;
2744
2745         case TE_RESTART:
2746                 break;
2747
2748         case TE_SECCOMP:
2749                 if (!has_seccomp_filter(current_tcp)) {
2750                         /*
2751                          * We don't know if forks/clones have a seccomp filter
2752                          * when they are created, but we can detect it when we
2753                          * have a seccomp-stop.
2754                          * In such a case, if !seccomp_before_sysentry, we have
2755                          * already processed the syscall entry, so we avoid
2756                          * processing it a second time.
2757                          */
2758                         current_tcp->flags |= TCB_SECCOMP_FILTER;
2759                         restart_op = PTRACE_SYSCALL;
2760                         break;
2761                 }
2762
2763                 if (seccomp_before_sysentry) {
2764                         restart_op = PTRACE_SYSCALL;
2765                         break;
2766                 }
2767                 ATTRIBUTE_FALLTHROUGH;
2768
2769         case TE_SYSCALL_STOP:
2770                 if (trace_syscall(current_tcp, &restart_sig) < 0) {
2771                         /*
2772                          * ptrace() failed in trace_syscall().
2773                          * Likely a result of process disappearing mid-flight.
2774                          * Observed case: exit_group() or SIGKILL terminating
2775                          * all processes in thread group.
2776                          * We assume that ptrace error was caused by process death.
2777                          * We used to detach(current_tcp) here, but since we no
2778                          * longer implement "detach before death" policy/hack,
2779                          * we can let this process to report its death to us
2780                          * normally, via WIFEXITED or WIFSIGNALED wait status.
2781                          */
2782                         return true;
2783                 }
2784                 if (has_seccomp_filter(current_tcp)) {
2785                         /*
2786                          * Syscall and seccomp stops can happen in different
2787                          * orders depending on kernel.  strace tests this in
2788                          * check_seccomp_order_tracer().
2789                          *
2790                          * Linux 3.5--4.7:
2791                          * (seccomp-stop before syscall-entry-stop)
2792                          *         +--> seccomp-stop ->-PTRACE_SYSCALL->-+
2793                          *         |                                     |
2794                          *     PTRACE_CONT                   syscall-entry-stop
2795                          *         |                                     |
2796                          * syscall-exit-stop <---PTRACE_SYSCALL-----<----+
2797                          *
2798                          * Linux 4.8+:
2799                          * (seccomp-stop after syscall-entry-stop)
2800                          *                 syscall-entry-stop
2801                          *
2802                          *         +---->-----PTRACE_CONT---->----+
2803                          *         |                              |
2804                          *  syscall-exit-stop               seccomp-stop
2805                          *         |                              |
2806                          *         +----<----PTRACE_SYSCALL---<---+
2807                          *
2808                          * Note in Linux 4.8+, we restart in PTRACE_CONT
2809                          * after syscall-exit to skip the syscall-entry-stop.
2810                          * The next seccomp-stop will be treated as a syscall
2811                          * entry.
2812                          *
2813                          * The line below implements this behavior.
2814                          * Note that exiting(current_tcp) actually marks
2815                          * a syscall-entry-stop because the flag was inverted
2816                          * in the above call to trace_syscall.
2817                          */
2818                         restart_op = exiting(current_tcp) ? PTRACE_SYSCALL : PTRACE_CONT;
2819                 }
2820                 break;
2821
2822         case TE_SIGNAL_DELIVERY_STOP:
2823                 restart_sig = WSTOPSIG(status);
2824                 print_stopped(current_tcp, &wd->si, restart_sig);
2825                 break;
2826
2827         case TE_SIGNALLED:
2828                 print_signalled(current_tcp, current_tcp->pid, status);
2829                 droptcb(current_tcp);
2830                 return true;
2831
2832         case TE_GROUP_STOP:
2833                 restart_sig = WSTOPSIG(status);
2834                 print_stopped(current_tcp, NULL, restart_sig);
2835                 if (use_seize) {
2836                         /*
2837                          * This ends ptrace-stop, but does *not* end group-stop.
2838                          * This makes stopping signals work properly on straced
2839                          * process (that is, process really stops. It used to
2840                          * continue to run).
2841                          */
2842                         restart_op = PTRACE_LISTEN;
2843                         restart_sig = 0;
2844                 }
2845                 break;
2846
2847         case TE_EXITED:
2848                 print_exited(current_tcp, current_tcp->pid, status);
2849                 droptcb(current_tcp);
2850                 return true;
2851
2852         case TE_STOP_BEFORE_EXECVE:
2853                 /* The syscall succeeded, clear the flag.  */
2854                 current_tcp->flags &= ~TCB_CHECK_EXEC_SYSCALL;
2855                 /*
2856                  * Check that we are inside syscall now (next event after
2857                  * PTRACE_EVENT_EXEC should be for syscall exiting).  If it is
2858                  * not the case, we might have a situation when we attach to a
2859                  * process and the first thing we see is a PTRACE_EVENT_EXEC
2860                  * and all the following syscall state tracking is screwed up
2861                  * otherwise.
2862                  */
2863                 if (!maybe_switch_current_tcp() && entering(current_tcp)) {
2864                         int ret;
2865
2866                         error_msg("Stray PTRACE_EVENT_EXEC from pid %d"
2867                                   ", trying to recover...",
2868                                   current_tcp->pid);
2869
2870                         current_tcp->flags |= TCB_RECOVERING;
2871                         ret = trace_syscall(current_tcp, &restart_sig);
2872                         current_tcp->flags &= ~TCB_RECOVERING;
2873
2874                         if (ret < 0) {
2875                                 /* The reason is described in TE_SYSCALL_STOP */
2876                                 return true;
2877                         }
2878                 }
2879
2880                 if (detach_on_execve) {
2881                         if (current_tcp->flags & TCB_SKIP_DETACH_ON_FIRST_EXEC) {
2882                                 current_tcp->flags &= ~TCB_SKIP_DETACH_ON_FIRST_EXEC;
2883                         } else {
2884                                 detach(current_tcp); /* do "-b execve" thingy */
2885                                 return true;
2886                         }
2887                 }
2888                 break;
2889
2890         case TE_STOP_BEFORE_EXIT:
2891                 print_event_exit(current_tcp);
2892                 break;
2893         }
2894
2895         /* We handled quick cases, we are permitted to interrupt now. */
2896         if (interrupted)
2897                 return false;
2898
2899         /* If the process is being delayed, do not ptrace_restart just yet */
2900         if (syscall_delayed(current_tcp)) {
2901                 if (current_tcp->delayed_wait_data)
2902                         error_func_msg("pid %d has delayed wait data set"
2903                                        " already", current_tcp->pid);
2904
2905                 current_tcp->delayed_wait_data = copy_trace_wait_data(wd);
2906
2907                 return true;
2908         }
2909
2910         if (ptrace_restart(restart_op, current_tcp, restart_sig) < 0) {
2911                 /* Note: ptrace_restart emitted error message */
2912                 exit_code = 1;
2913                 return false;
2914         }
2915         return true;
2916 }
2917
2918 static bool
2919 restart_delayed_tcb(struct tcb *const tcp)
2920 {
2921         struct tcb_wait_data *wd = tcp->delayed_wait_data;
2922
2923         if (!wd) {
2924                 error_func_msg("No delayed wait data found for pid %d",
2925                                tcp->pid);
2926                 wd = init_trace_wait_data(alloca(trace_wait_data_size(tcp)));
2927         }
2928
2929         wd->te = TE_RESTART;
2930
2931         debug_func_msg("pid %d", tcp->pid);
2932
2933         tcp->flags &= ~TCB_DELAYED;
2934
2935         struct tcb *const prev_tcp = current_tcp;
2936         current_tcp = tcp;
2937         bool ret = dispatch_event(wd);
2938         current_tcp = prev_tcp;
2939
2940         free_trace_wait_data(tcp->delayed_wait_data);
2941         tcp->delayed_wait_data = NULL;
2942
2943         return ret;
2944 }
2945
2946 static bool
2947 restart_delayed_tcbs(void)
2948 {
2949         struct tcb *tcp_next = NULL;
2950         struct timespec ts_now;
2951
2952         clock_gettime(CLOCK_MONOTONIC, &ts_now);
2953
2954         for (size_t i = 0; i < tcbtabsize; i++) {
2955                 struct tcb *tcp = tcbtab[i];
2956
2957                 if (tcp->pid && syscall_delayed(tcp)) {
2958                         if (ts_cmp(&ts_now, &tcp->delay_expiration_time) > 0) {
2959                                 if (!restart_delayed_tcb(tcp))
2960                                         return false;
2961                         } else {
2962                                 /* Check whether this tcb is the next.  */
2963                                 if (!tcp_next ||
2964                                     ts_cmp(&tcp_next->delay_expiration_time,
2965                                            &tcp->delay_expiration_time) > 0) {
2966                                         tcp_next = tcp;
2967                                 }
2968                         }
2969                 }
2970         }
2971
2972         if (tcp_next)
2973                 arm_delay_timer(tcp_next);
2974
2975         return true;
2976 }
2977
2978 /*
2979  * As this signal handler does a lot of work that is not suitable
2980  * for signal handlers, extra care must be taken to ensure that
2981  * it is enabled only in those places where it's safe.
2982  */
2983 static void
2984 timer_sighandler(int sig)
2985 {
2986         delay_timer_expired();
2987
2988         if (restart_failed)
2989                 return;
2990
2991         int saved_errno = errno;
2992
2993         if (!restart_delayed_tcbs())
2994                 restart_failed = 1;
2995
2996         errno = saved_errno;
2997 }
2998
2999 #ifdef ENABLE_COVERAGE_GCOV
3000 extern void __gcov_flush(void);
3001 #endif
3002
3003 static void ATTRIBUTE_NORETURN
3004 terminate(void)
3005 {
3006         int sig = interrupted;
3007
3008         cleanup(sig);
3009         if (cflag)
3010                 call_summary(shared_log);
3011         fflush(NULL);
3012         if (shared_log != stderr)
3013                 fclose(shared_log);
3014         if (popen_pid) {
3015                 while (waitpid(popen_pid, NULL, 0) < 0 && errno == EINTR)
3016                         ;
3017         }
3018         if (sig) {
3019                 exit_code = 0x100 | sig;
3020         }
3021         if (exit_code > 0xff) {
3022                 /* Avoid potential core file clobbering.  */
3023                 struct_rlimit rlim = {0, 0};
3024                 set_rlimit(RLIMIT_CORE, &rlim);
3025
3026                 /* Child was killed by a signal, mimic that.  */
3027                 exit_code &= 0xff;
3028                 signal(exit_code, SIG_DFL);
3029 #ifdef ENABLE_COVERAGE_GCOV
3030                 __gcov_flush();
3031 #endif
3032                 raise(exit_code);
3033
3034                 /* Unblock the signal.  */
3035                 sigset_t mask;
3036                 sigemptyset(&mask);
3037                 sigaddset(&mask, exit_code);
3038 #ifdef ENABLE_COVERAGE_GCOV
3039                 __gcov_flush();
3040 #endif
3041                 sigprocmask(SIG_UNBLOCK, &mask, NULL);
3042
3043                 /* Paranoia - what if this signal is not fatal?
3044                    Exit with 128 + signo then.  */
3045                 exit_code += 128;
3046         }
3047         exit(exit_code);
3048 }
3049
3050 int
3051 main(int argc, char *argv[])
3052 {
3053         setlocale(LC_ALL, "");
3054         init(argc, argv);
3055
3056         exit_code = !nprocs;
3057
3058         while (dispatch_event(next_event()))
3059                 ;
3060         terminate();
3061 }