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