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