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