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