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