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