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