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