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