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