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