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