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