]> granicus.if.org Git - strace/blob - strace.c
Refactor setting of signal handlers to reduce redundancy
[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 = false;
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 = 0;
78 unsigned int ptrace_setoptions = PTRACE_O_TRACESYSGOOD | PTRACE_O_TRACEEXEC
79                                  | PTRACE_O_TRACEEXIT;
80 unsigned int xflag = 0;
81 bool debug_flag = 0;
82 bool Tflag = 0;
83 bool iflag = 0;
84 bool count_wallclock = 0;
85 unsigned int qflag = 0;
86 static unsigned int tflag = 0;
87 static bool rflag = 0;
88 static bool print_pid_pfx = 0;
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 = 0;
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 = 0;
127
128 /* Show path associated with fd arguments */
129 unsigned int show_fd_path = 0;
130
131 static bool detach_on_execve = 0;
132
133 static int exit_code;
134 static int strace_child = 0;
135 static int strace_tracer_pid = 0;
136
137 static char *username = NULL;
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 = NULL;
146 /* If -ff, points to stderr. Else, it's our common output log */
147 static FILE *shared_log;
148
149 struct tcb *printing_tcp = NULL;
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 = 0;
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                 die_out_of_memory();
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                 }
694                 else if (tflag > 2) {
695                         tprintf("%ld.%06ld ",
696                                 (long) tv.tv_sec, (long) tv.tv_usec);
697                 }
698                 else {
699                         time_t local = tv.tv_sec;
700                         strftime(str, sizeof(str), "%T", localtime(&local));
701                         if (tflag > 1)
702                                 tprintf("%s.%06ld ", str, (long) tv.tv_usec);
703                         else
704                                 tprintf("%s ", str);
705                 }
706         }
707         if (iflag)
708                 print_pc(tcp);
709 }
710
711 void
712 tabto(void)
713 {
714         if (current_tcp->curcol < acolumn)
715                 tprints(acolumn_spaces + current_tcp->curcol);
716 }
717
718 /* Should be only called directly *after successful attach* to a tracee.
719  * Otherwise, "strace -oFILE -ff -p<nonexistant_pid>"
720  * may create bogus empty FILE.<nonexistant_pid>, and then die.
721  */
722 static void
723 newoutf(struct tcb *tcp)
724 {
725         tcp->outf = shared_log; /* if not -ff mode, the same file is for all */
726         if (followfork >= 2) {
727                 char name[520 + sizeof(int) * 3];
728                 sprintf(name, "%.512s.%u", outfname, tcp->pid);
729                 tcp->outf = strace_fopen(name);
730         }
731 }
732
733 static void
734 expand_tcbtab(void)
735 {
736         /* Allocate some (more) TCBs (and expand the table).
737            We don't want to relocate the TCBs because our
738            callers have pointers and it would be a pain.
739            So tcbtab is a table of pointers.  Since we never
740            free the TCBs, we allocate a single chunk of many.  */
741         unsigned int new_tcbtabsize, alloc_tcbtabsize;
742         struct tcb *newtcbs;
743
744         if (tcbtabsize) {
745                 alloc_tcbtabsize = tcbtabsize;
746                 new_tcbtabsize = tcbtabsize * 2;
747         } else {
748                 new_tcbtabsize = alloc_tcbtabsize = 1;
749         }
750
751         newtcbs = xcalloc(alloc_tcbtabsize, sizeof(newtcbs[0]));
752         tcbtab = xreallocarray(tcbtab, new_tcbtabsize, sizeof(tcbtab[0]));
753         while (tcbtabsize < new_tcbtabsize)
754                 tcbtab[tcbtabsize++] = newtcbs++;
755 }
756
757 static struct tcb *
758 alloctcb(int pid)
759 {
760         unsigned int i;
761         struct tcb *tcp;
762
763         if (nprocs == tcbtabsize)
764                 expand_tcbtab();
765
766         for (i = 0; i < tcbtabsize; i++) {
767                 tcp = tcbtab[i];
768                 if (!tcp->pid) {
769                         memset(tcp, 0, sizeof(*tcp));
770                         tcp->pid = pid;
771 #if SUPPORTED_PERSONALITIES > 1
772                         tcp->currpers = current_personality;
773 #endif
774
775 #ifdef USE_LIBUNWIND
776                         if (stack_trace_enabled)
777                                 unwind_tcb_init(tcp);
778 #endif
779
780                         nprocs++;
781                         if (debug_flag)
782                                 error_msg("new tcb for pid %d, active tcbs:%d",
783                                           tcp->pid, nprocs);
784                         return tcp;
785                 }
786         }
787         error_msg_and_die("bug in alloctcb");
788 }
789
790 void *
791 get_tcb_priv_data(const struct tcb *tcp)
792 {
793         return tcp->_priv_data;
794 }
795
796 int
797 set_tcb_priv_data(struct tcb *tcp, void *const priv_data,
798                   void (*const free_priv_data)(void *))
799 {
800         if (tcp->_priv_data)
801                 return -1;
802
803         tcp->_free_priv_data = free_priv_data;
804         tcp->_priv_data = priv_data;
805
806         return 0;
807 }
808
809 void
810 free_tcb_priv_data(struct tcb *tcp)
811 {
812         if (tcp->_priv_data) {
813                 if (tcp->_free_priv_data) {
814                         tcp->_free_priv_data(tcp->_priv_data);
815                         tcp->_free_priv_data = NULL;
816                 }
817                 tcp->_priv_data = NULL;
818         }
819 }
820
821 static void
822 droptcb(struct tcb *tcp)
823 {
824         if (tcp->pid == 0)
825                 return;
826
827         int p;
828         for (p = 0; p < SUPPORTED_PERSONALITIES; ++p)
829                 free(tcp->inject_vec[p]);
830
831         free_tcb_priv_data(tcp);
832
833 #ifdef USE_LIBUNWIND
834         if (stack_trace_enabled) {
835                 unwind_tcb_fin(tcp);
836         }
837 #endif
838
839         nprocs--;
840         if (debug_flag)
841                 error_msg("dropped tcb for pid %d, %d remain",
842                           tcp->pid, nprocs);
843
844         if (tcp->outf) {
845                 if (followfork >= 2) {
846                         if (tcp->curcol != 0)
847                                 fprintf(tcp->outf, " <detached ...>\n");
848                         fclose(tcp->outf);
849                 } else {
850                         if (printing_tcp == tcp && tcp->curcol != 0)
851                                 fprintf(tcp->outf, " <detached ...>\n");
852                         fflush(tcp->outf);
853                 }
854         }
855
856         if (current_tcp == tcp)
857                 current_tcp = NULL;
858         if (printing_tcp == tcp)
859                 printing_tcp = NULL;
860
861         memset(tcp, 0, sizeof(*tcp));
862 }
863
864 /* Detach traced process.
865  * Never call DETACH twice on the same process as both unattached and
866  * attached-unstopped processes give the same ESRCH.  For unattached process we
867  * would SIGSTOP it and wait for its SIGSTOP notification forever.
868  */
869 static void
870 detach(struct tcb *tcp)
871 {
872         int error;
873         int status;
874
875         /*
876          * Linux wrongly insists the child be stopped
877          * before detaching.  Arghh.  We go through hoops
878          * to make a clean break of things.
879          */
880
881         if (!(tcp->flags & TCB_ATTACHED))
882                 goto drop;
883
884         /* We attached but possibly didn't see the expected SIGSTOP.
885          * We must catch exactly one as otherwise the detached process
886          * would be left stopped (process state T).
887          */
888         if (tcp->flags & TCB_IGNORE_ONE_SIGSTOP)
889                 goto wait_loop;
890
891         error = ptrace(PTRACE_DETACH, tcp->pid, 0, 0);
892         if (!error) {
893                 /* On a clear day, you can see forever. */
894                 goto drop;
895         }
896         if (errno != ESRCH) {
897                 /* Shouldn't happen. */
898                 perror_msg("detach: ptrace(PTRACE_DETACH,%u)", tcp->pid);
899                 goto drop;
900         }
901         /* ESRCH: process is either not stopped or doesn't exist. */
902         if (my_tkill(tcp->pid, 0) < 0) {
903                 if (errno != ESRCH)
904                         /* Shouldn't happen. */
905                         perror_msg("detach: tkill(%u,0)", tcp->pid);
906                 /* else: process doesn't exist. */
907                 goto drop;
908         }
909         /* Process is not stopped, need to stop it. */
910         if (use_seize) {
911                 /*
912                  * With SEIZE, tracee can be in group-stop already.
913                  * In this state sending it another SIGSTOP does nothing.
914                  * Need to use INTERRUPT.
915                  * Testcase: trying to ^C a "strace -p <stopped_process>".
916                  */
917                 error = ptrace(PTRACE_INTERRUPT, tcp->pid, 0, 0);
918                 if (!error)
919                         goto wait_loop;
920                 if (errno != ESRCH)
921                         perror_msg("detach: ptrace(PTRACE_INTERRUPT,%u)", tcp->pid);
922         }
923         else {
924                 error = my_tkill(tcp->pid, SIGSTOP);
925                 if (!error)
926                         goto wait_loop;
927                 if (errno != ESRCH)
928                         perror_msg("detach: tkill(%u,SIGSTOP)", tcp->pid);
929         }
930         /* Either process doesn't exist, or some weird error. */
931         goto drop;
932
933  wait_loop:
934         /* We end up here in three cases:
935          * 1. We sent PTRACE_INTERRUPT (use_seize case)
936          * 2. We sent SIGSTOP (!use_seize)
937          * 3. Attach SIGSTOP was already pending (TCB_IGNORE_ONE_SIGSTOP set)
938          */
939         for (;;) {
940                 unsigned int sig;
941                 if (waitpid(tcp->pid, &status, __WALL) < 0) {
942                         if (errno == EINTR)
943                                 continue;
944                         /*
945                          * if (errno == ECHILD) break;
946                          * ^^^  WRONG! We expect this PID to exist,
947                          * and want to emit a message otherwise:
948                          */
949                         perror_msg("detach: waitpid(%u)", tcp->pid);
950                         break;
951                 }
952                 if (!WIFSTOPPED(status)) {
953                         /*
954                          * Tracee exited or was killed by signal.
955                          * We shouldn't normally reach this place:
956                          * we don't want to consume exit status.
957                          * Consider "strace -p PID" being ^C-ed:
958                          * we want merely to detach from PID.
959                          *
960                          * However, we _can_ end up here if tracee
961                          * was SIGKILLed.
962                          */
963                         break;
964                 }
965                 sig = WSTOPSIG(status);
966                 if (debug_flag)
967                         error_msg("detach wait: event:%d sig:%d",
968                                   (unsigned)status >> 16, sig);
969                 if (use_seize) {
970                         unsigned event = (unsigned)status >> 16;
971                         if (event == PTRACE_EVENT_STOP /*&& sig == SIGTRAP*/) {
972                                 /*
973                                  * sig == SIGTRAP: PTRACE_INTERRUPT stop.
974                                  * sig == other: process was already stopped
975                                  * with this stopping sig (see tests/detach-stopped).
976                                  * Looks like re-injecting this sig is not necessary
977                                  * in DETACH for the tracee to remain stopped.
978                                  */
979                                 sig = 0;
980                         }
981                         /*
982                          * PTRACE_INTERRUPT is not guaranteed to produce
983                          * the above event if other ptrace-stop is pending.
984                          * See tests/detach-sleeping testcase:
985                          * strace got SIGINT while tracee is sleeping.
986                          * We sent PTRACE_INTERRUPT.
987                          * We see syscall exit, not PTRACE_INTERRUPT stop.
988                          * We won't get PTRACE_INTERRUPT stop
989                          * if we would CONT now. Need to DETACH.
990                          */
991                         if (sig == syscall_trap_sig)
992                                 sig = 0;
993                         /* else: not sure in which case we can be here.
994                          * Signal stop? Inject it while detaching.
995                          */
996                         ptrace_restart(PTRACE_DETACH, tcp, sig);
997                         break;
998                 }
999                 /* Note: this check has to be after use_seize check */
1000                 /* (else, in use_seize case SIGSTOP will be mistreated) */
1001                 if (sig == SIGSTOP) {
1002                         /* Detach, suppressing SIGSTOP */
1003                         ptrace_restart(PTRACE_DETACH, tcp, 0);
1004                         break;
1005                 }
1006                 if (sig == syscall_trap_sig)
1007                         sig = 0;
1008                 /* Can't detach just yet, may need to wait for SIGSTOP */
1009                 error = ptrace_restart(PTRACE_CONT, tcp, sig);
1010                 if (error < 0) {
1011                         /* Should not happen.
1012                          * Note: ptrace_restart returns 0 on ESRCH, so it's not it.
1013                          * ptrace_restart already emitted error message.
1014                          */
1015                         break;
1016                 }
1017         }
1018
1019  drop:
1020         if (!qflag && (tcp->flags & TCB_ATTACHED))
1021                 error_msg("Process %u detached", tcp->pid);
1022
1023         droptcb(tcp);
1024 }
1025
1026 static void
1027 process_opt_p_list(char *opt)
1028 {
1029         while (*opt) {
1030                 /*
1031                  * We accept -p PID,PID; -p "`pidof PROG`"; -p "`pgrep PROG`".
1032                  * pidof uses space as delim, pgrep uses newline. :(
1033                  */
1034                 int pid;
1035                 char *delim = opt + strcspn(opt, ", \n\t");
1036                 char c = *delim;
1037
1038                 *delim = '\0';
1039                 pid = string_to_uint(opt);
1040                 if (pid <= 0) {
1041                         error_msg_and_die("Invalid process id: '%s'", opt);
1042                 }
1043                 if (pid == strace_tracer_pid) {
1044                         error_msg_and_die("I'm sorry, I can't let you do that, Dave.");
1045                 }
1046                 *delim = c;
1047                 alloctcb(pid);
1048                 if (c == '\0')
1049                         break;
1050                 opt = delim + 1;
1051         }
1052 }
1053
1054 static void
1055 attach_tcb(struct tcb *const tcp)
1056 {
1057         if (ptrace_attach_or_seize(tcp->pid) < 0) {
1058                 perror_msg("attach: ptrace(%s, %d)",
1059                            ptrace_attach_cmd, tcp->pid);
1060                 droptcb(tcp);
1061                 return;
1062         }
1063
1064         tcp->flags |= TCB_ATTACHED | TCB_STARTUP | post_attach_sigstop;
1065         newoutf(tcp);
1066         if (debug_flag)
1067                 error_msg("attach to pid %d (main) succeeded", tcp->pid);
1068
1069         char procdir[sizeof("/proc/%d/task") + sizeof(int) * 3];
1070         DIR *dir;
1071         unsigned int ntid = 0, nerr = 0;
1072
1073         if (followfork && tcp->pid != strace_child &&
1074             sprintf(procdir, "/proc/%d/task", tcp->pid) > 0 &&
1075             (dir = opendir(procdir)) != NULL) {
1076                 struct_dirent *de;
1077
1078                 while ((de = read_dir(dir)) != NULL) {
1079                         if (de->d_fileno == 0)
1080                                 continue;
1081
1082                         int tid = string_to_uint(de->d_name);
1083                         if (tid <= 0 || tid == tcp->pid)
1084                                 continue;
1085
1086                         ++ntid;
1087                         if (ptrace_attach_or_seize(tid) < 0) {
1088                                 ++nerr;
1089                                 if (debug_flag)
1090                                         perror_msg("attach: ptrace(%s, %d)",
1091                                                    ptrace_attach_cmd, tid);
1092                                 continue;
1093                         }
1094                         if (debug_flag)
1095                                 error_msg("attach to pid %d succeeded", tid);
1096
1097                         struct tcb *tid_tcp = alloctcb(tid);
1098                         tid_tcp->flags |= TCB_ATTACHED | TCB_STARTUP |
1099                                           post_attach_sigstop;
1100                         newoutf(tid_tcp);
1101                 }
1102
1103                 closedir(dir);
1104         }
1105
1106         if (!qflag) {
1107                 if (ntid > nerr)
1108                         error_msg("Process %u attached"
1109                                   " with %u threads",
1110                                   tcp->pid, ntid - nerr + 1);
1111                 else
1112                         error_msg("Process %u attached",
1113                                   tcp->pid);
1114         }
1115 }
1116
1117 static void
1118 startup_attach(void)
1119 {
1120         pid_t parent_pid = strace_tracer_pid;
1121         unsigned int tcbi;
1122         struct tcb *tcp;
1123
1124         /*
1125          * Block user interruptions as we would leave the traced
1126          * process stopped (process state T) if we would terminate in
1127          * between PTRACE_ATTACH and wait4() on SIGSTOP.
1128          * We rely on cleanup() from this point on.
1129          */
1130         if (interactive)
1131                 sigprocmask(SIG_SETMASK, &blocked_set, NULL);
1132
1133         if (daemonized_tracer) {
1134                 pid_t pid = fork();
1135                 if (pid < 0) {
1136                         perror_msg_and_die("fork");
1137                 }
1138                 if (pid) { /* parent */
1139                         /*
1140                          * Wait for grandchild to attach to straced process
1141                          * (grandparent). Grandchild SIGKILLs us after it attached.
1142                          * Grandparent's wait() is unblocked by our death,
1143                          * it proceeds to exec the straced program.
1144                          */
1145                         pause();
1146                         _exit(0); /* paranoia */
1147                 }
1148                 /* grandchild */
1149                 /* We will be the tracer process. Remember our new pid: */
1150                 strace_tracer_pid = getpid();
1151         }
1152
1153         for (tcbi = 0; tcbi < tcbtabsize; tcbi++) {
1154                 tcp = tcbtab[tcbi];
1155
1156                 if (!tcp->pid)
1157                         continue;
1158
1159                 /* Is this a process we should attach to, but not yet attached? */
1160                 if (tcp->flags & TCB_ATTACHED)
1161                         continue; /* no, we already attached it */
1162
1163                 if (tcp->pid == parent_pid || tcp->pid == strace_tracer_pid) {
1164                         errno = EPERM;
1165                         perror_msg("attach: pid %d", tcp->pid);
1166                         droptcb(tcp);
1167                         continue;
1168                 }
1169
1170                 attach_tcb(tcp);
1171
1172                 if (interactive) {
1173                         sigprocmask(SIG_SETMASK, &start_set, NULL);
1174                         if (interrupted)
1175                                 goto ret;
1176                         sigprocmask(SIG_SETMASK, &blocked_set, NULL);
1177                 }
1178         } /* for each tcbtab[] */
1179
1180         if (daemonized_tracer) {
1181                 /*
1182                  * Make parent go away.
1183                  * Also makes grandparent's wait() unblock.
1184                  */
1185                 kill(parent_pid, SIGKILL);
1186                 strace_child = 0;
1187         }
1188
1189  ret:
1190         if (interactive)
1191                 sigprocmask(SIG_SETMASK, &start_set, NULL);
1192 }
1193
1194 /* Stack-o-phobic exec helper, in the hope to work around
1195  * NOMMU + "daemonized tracer" difficulty.
1196  */
1197 struct exec_params {
1198         int fd_to_close;
1199         uid_t run_euid;
1200         gid_t run_egid;
1201         char **argv;
1202         char *pathname;
1203 };
1204 static struct exec_params params_for_tracee;
1205
1206 static void ATTRIBUTE_NOINLINE ATTRIBUTE_NORETURN
1207 exec_or_die(void)
1208 {
1209         struct exec_params *params = &params_for_tracee;
1210
1211         if (params->fd_to_close >= 0)
1212                 close(params->fd_to_close);
1213         if (!daemonized_tracer && !use_seize) {
1214                 if (ptrace(PTRACE_TRACEME, 0L, 0L, 0L) < 0) {
1215                         perror_msg_and_die("ptrace(PTRACE_TRACEME, ...)");
1216                 }
1217         }
1218
1219         if (username != NULL) {
1220                 /*
1221                  * It is important to set groups before we
1222                  * lose privileges on setuid.
1223                  */
1224                 if (initgroups(username, run_gid) < 0) {
1225                         perror_msg_and_die("initgroups");
1226                 }
1227                 if (setregid(run_gid, params->run_egid) < 0) {
1228                         perror_msg_and_die("setregid");
1229                 }
1230                 if (setreuid(run_uid, params->run_euid) < 0) {
1231                         perror_msg_and_die("setreuid");
1232                 }
1233         }
1234         else if (geteuid() != 0)
1235                 if (setreuid(run_uid, run_uid) < 0) {
1236                         perror_msg_and_die("setreuid");
1237                 }
1238
1239         if (!daemonized_tracer) {
1240                 /*
1241                  * Induce a ptrace stop. Tracer (our parent)
1242                  * will resume us with PTRACE_SYSCALL and display
1243                  * the immediately following execve syscall.
1244                  * Can't do this on NOMMU systems, we are after
1245                  * vfork: parent is blocked, stopping would deadlock.
1246                  */
1247                 if (!NOMMU_SYSTEM)
1248                         kill(getpid(), SIGSTOP);
1249         } else {
1250                 alarm(3);
1251                 /* we depend on SIGCHLD set to SIG_DFL by init code */
1252                 /* if it happens to be SIG_IGN'ed, wait won't block */
1253                 wait(NULL);
1254                 alarm(0);
1255         }
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                         }
1364                         else
1365                                 m = n = strlen(path);
1366                         if (n == 0) {
1367                                 if (!getcwd(pathname, PATH_MAX))
1368                                         continue;
1369                                 len = strlen(pathname);
1370                         }
1371                         else if (n > sizeof pathname - 1)
1372                                 continue;
1373                         else {
1374                                 strncpy(pathname, path, n);
1375                                 len = n;
1376                         }
1377                         if (len && pathname[len - 1] != '/')
1378                                 pathname[len++] = '/';
1379                         if (filename_len + len > sizeof(pathname) - 1)
1380                                 continue;
1381                         strcpy(pathname + len, filename);
1382                         if (stat_file(pathname, &statbuf) == 0 &&
1383                             /* Accept only regular files
1384                                with some execute bits set.
1385                                XXX not perfect, might still fail */
1386                             S_ISREG(statbuf.st_mode) &&
1387                             (statbuf.st_mode & 0111))
1388                                 break;
1389                 }
1390                 if (!path || !*path)
1391                         pathname[0] = '\0';
1392         }
1393         if (stat_file(pathname, &statbuf) < 0) {
1394                 perror_msg_and_die("Can't stat '%s'", filename);
1395         }
1396
1397         params_for_tracee.fd_to_close = (shared_log != stderr) ? fileno(shared_log) : -1;
1398         params_for_tracee.run_euid = (statbuf.st_mode & S_ISUID) ? statbuf.st_uid : run_uid;
1399         params_for_tracee.run_egid = (statbuf.st_mode & S_ISGID) ? statbuf.st_gid : run_gid;
1400         params_for_tracee.argv = argv;
1401         /*
1402          * On NOMMU, can be safely freed only after execve in tracee.
1403          * It's hard to know when that happens, so we just leak it.
1404          */
1405         params_for_tracee.pathname = NOMMU_SYSTEM ? xstrdup(pathname) : pathname;
1406
1407 #if defined HAVE_PRCTL && defined PR_SET_PTRACER && defined PR_SET_PTRACER_ANY
1408         if (daemonized_tracer)
1409                 prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY);
1410 #endif
1411
1412         pid = fork();
1413         if (pid < 0) {
1414                 perror_msg_and_die("fork");
1415         }
1416         if ((pid != 0 && daemonized_tracer)
1417          || (pid == 0 && !daemonized_tracer)
1418         ) {
1419                 /* We are to become the tracee. Two cases:
1420                  * -D: we are parent
1421                  * not -D: we are child
1422                  */
1423                 exec_or_die();
1424         }
1425
1426         /* We are the tracer */
1427
1428         if (!daemonized_tracer) {
1429                 strace_child = pid;
1430                 if (!use_seize) {
1431                         /* child did PTRACE_TRACEME, nothing to do in parent */
1432                 } else {
1433                         if (!NOMMU_SYSTEM) {
1434                                 /* Wait until child stopped itself */
1435                                 int status;
1436                                 while (waitpid(pid, &status, WSTOPPED) < 0) {
1437                                         if (errno == EINTR)
1438                                                 continue;
1439                                         perror_msg_and_die("waitpid");
1440                                 }
1441                                 if (!WIFSTOPPED(status) || WSTOPSIG(status) != SIGSTOP) {
1442                                         kill_save_errno(pid, SIGKILL);
1443                                         perror_msg_and_die("Unexpected wait status %#x",
1444                                                            status);
1445                                 }
1446                         }
1447                         /* Else: NOMMU case, we have no way to sync.
1448                          * Just attach to it as soon as possible.
1449                          * This means that we may miss a few first syscalls...
1450                          */
1451
1452                         if (ptrace_attach_or_seize(pid)) {
1453                                 kill_save_errno(pid, SIGKILL);
1454                                 perror_msg_and_die("attach: ptrace(%s, %d)",
1455                                                    ptrace_attach_cmd, pid);
1456                         }
1457                         if (!NOMMU_SYSTEM)
1458                                 kill(pid, SIGCONT);
1459                 }
1460                 tcp = alloctcb(pid);
1461                 tcp->flags |= TCB_ATTACHED | TCB_STARTUP
1462                             | TCB_SKIP_DETACH_ON_FIRST_EXEC
1463                             | (NOMMU_SYSTEM ? 0 : (TCB_HIDE_LOG | post_attach_sigstop));
1464                 newoutf(tcp);
1465         }
1466         else {
1467                 /* With -D, we are *child* here, the tracee is our parent. */
1468                 strace_child = strace_tracer_pid;
1469                 strace_tracer_pid = getpid();
1470                 tcp = alloctcb(strace_child);
1471                 tcp->flags |= TCB_SKIP_DETACH_ON_FIRST_EXEC | TCB_HIDE_LOG;
1472                 /* attaching will be done later, by startup_attach */
1473                 /* note: we don't do newoutf(tcp) here either! */
1474
1475                 /* NOMMU BUG! -D mode is active, we (child) return,
1476                  * and we will scribble over parent's stack!
1477                  * When parent later unpauses, it segfaults.
1478                  *
1479                  * We work around it
1480                  * (1) by declaring exec_or_die() NORETURN,
1481                  * hopefully compiler will just jump to it
1482                  * instead of call (won't push anything to stack),
1483                  * (2) by trying very hard in exec_or_die()
1484                  * to not use any stack,
1485                  * (3) having a really big (PATH_MAX) stack object
1486                  * in this function, which creates a "buffer" between
1487                  * child's and parent's stack pointers.
1488                  * This may save us if (1) and (2) failed
1489                  * and compiler decided to use stack in exec_or_die() anyway
1490                  * (happens on i386 because of stack parameter passing).
1491                  *
1492                  * A cleaner solution is to use makecontext + setcontext
1493                  * to create a genuine separate stack and execute on it.
1494                  */
1495         }
1496         /*
1497          * A case where straced process is part of a pipe:
1498          * { sleep 1; yes | head -n99999; } | strace -o/dev/null sh -c 'exec <&-; sleep 9'
1499          * If strace won't close its fd#0, closing it in tracee is not enough:
1500          * the pipe is still open, it has a reader. Thus, "head" will not get its
1501          * SIGPIPE at once, on the first write.
1502          *
1503          * Preventing it by redirecting strace's stdin/out.
1504          * (Don't leave fds 0 and 1 closed, this is bad practice: future opens
1505          * will reuse them, unexpectedly making a newly opened object "stdin").
1506          */
1507         redirect_standard_fds();
1508 }
1509
1510 #if USE_SEIZE
1511 static void
1512 test_ptrace_seize(void)
1513 {
1514         int pid;
1515
1516         /* Need fork for test. NOMMU has no forks */
1517         if (NOMMU_SYSTEM) {
1518                 post_attach_sigstop = 0; /* this sets use_seize to 1 */
1519                 return;
1520         }
1521
1522         pid = fork();
1523         if (pid < 0)
1524                 perror_msg_and_die("fork");
1525
1526         if (pid == 0) {
1527                 pause();
1528                 _exit(0);
1529         }
1530
1531         /* PTRACE_SEIZE, unlike ATTACH, doesn't force tracee to trap.  After
1532          * attaching tracee continues to run unless a trap condition occurs.
1533          * PTRACE_SEIZE doesn't affect signal or group stop state.
1534          */
1535         if (ptrace(PTRACE_SEIZE, pid, 0, 0) == 0) {
1536                 post_attach_sigstop = 0; /* this sets use_seize to 1 */
1537         } else if (debug_flag) {
1538                 error_msg("PTRACE_SEIZE doesn't work");
1539         }
1540
1541         kill(pid, SIGKILL);
1542
1543         while (1) {
1544                 int status, tracee_pid;
1545
1546                 errno = 0;
1547                 tracee_pid = waitpid(pid, &status, 0);
1548                 if (tracee_pid <= 0) {
1549                         if (errno == EINTR)
1550                                 continue;
1551                         perror_msg_and_die("%s: unexpected wait result %d",
1552                                          __func__, tracee_pid);
1553                 }
1554                 if (WIFSIGNALED(status)) {
1555                         return;
1556                 }
1557                 error_msg_and_die("%s: unexpected wait status %#x",
1558                                   __func__, status);
1559         }
1560 }
1561 #else /* !USE_SEIZE */
1562 # define test_ptrace_seize() ((void)0)
1563 #endif
1564
1565 static unsigned
1566 get_os_release(void)
1567 {
1568         unsigned rel;
1569         const char *p;
1570         struct utsname u;
1571         if (uname(&u) < 0)
1572                 perror_msg_and_die("uname");
1573         /* u.release has this form: "3.2.9[-some-garbage]" */
1574         rel = 0;
1575         p = u.release;
1576         for (;;) {
1577                 if (!(*p >= '0' && *p <= '9'))
1578                         error_msg_and_die("Bad OS release string: '%s'", u.release);
1579                 /* Note: this open-codes KERNEL_VERSION(): */
1580                 rel = (rel << 8) | atoi(p);
1581                 if (rel >= KERNEL_VERSION(1,0,0))
1582                         break;
1583                 while (*p >= '0' && *p <= '9')
1584                         p++;
1585                 if (*p != '.') {
1586                         if (rel >= KERNEL_VERSION(0,1,0)) {
1587                                 /* "X.Y-something" means "X.Y.0" */
1588                                 rel <<= 8;
1589                                 break;
1590                         }
1591                         error_msg_and_die("Bad OS release string: '%s'", u.release);
1592                 }
1593                 p++;
1594         }
1595         return rel;
1596 }
1597
1598 static void
1599 set_sigaction(int signo, void (*sighandler)(int), struct sigaction *oldact)
1600 {
1601         /* if signal handler is a function, add the signal to blocked_set */
1602         if (sighandler != SIG_IGN && sighandler != SIG_DFL)
1603                 sigaddset(&blocked_set, signo);
1604
1605         const struct sigaction sa = { .sa_handler = sighandler };
1606         sigaction(signo, &sa, oldact);
1607 }
1608
1609 /*
1610  * Initialization part of main() was eating much stack (~0.5k),
1611  * which was unused after init.
1612  * We can reuse it if we move init code into a separate function.
1613  *
1614  * Don't want main() to inline us and defeat the reason
1615  * we have a separate function.
1616  */
1617 static void ATTRIBUTE_NOINLINE
1618 init(int argc, char *argv[])
1619 {
1620         int c, i;
1621         int optF = 0;
1622
1623         progname = argv[0] ? argv[0] : "strace";
1624
1625         /* Make sure SIGCHLD has the default action so that waitpid
1626            definitely works without losing track of children.  The user
1627            should not have given us a bogus state to inherit, but he might
1628            have.  Arguably we should detect SIG_IGN here and pass it on
1629            to children, but probably noone really needs that.  */
1630         signal(SIGCHLD, SIG_DFL);
1631
1632         strace_tracer_pid = getpid();
1633
1634         os_release = get_os_release();
1635
1636         shared_log = stderr;
1637         set_sortby(DEFAULT_SORTBY);
1638         set_personality(DEFAULT_PERSONALITY);
1639         qualify("trace=all");
1640         qualify("abbrev=all");
1641         qualify("verbose=all");
1642 #if DEFAULT_QUAL_FLAGS != (QUAL_TRACE | QUAL_ABBREV | QUAL_VERBOSE)
1643 # error Bug in DEFAULT_QUAL_FLAGS
1644 #endif
1645         qualify("signal=all");
1646         while ((c = getopt(argc, argv,
1647                 "+b:cCdfFhiqrtTvVwxyz"
1648 #ifdef USE_LIBUNWIND
1649                 "k"
1650 #endif
1651                 "D"
1652                 "a:e:o:O:p:s:S:u:E:P:I:")) != EOF) {
1653                 switch (c) {
1654                 case 'b':
1655                         if (strcmp(optarg, "execve") != 0)
1656                                 error_msg_and_die("Syscall '%s' for -b isn't supported",
1657                                         optarg);
1658                         detach_on_execve = 1;
1659                         break;
1660                 case 'c':
1661                         if (cflag == CFLAG_BOTH) {
1662                                 error_msg_and_help("-c and -C are mutually exclusive");
1663                         }
1664                         cflag = CFLAG_ONLY_STATS;
1665                         break;
1666                 case 'C':
1667                         if (cflag == CFLAG_ONLY_STATS) {
1668                                 error_msg_and_help("-c and -C are mutually exclusive");
1669                         }
1670                         cflag = CFLAG_BOTH;
1671                         break;
1672                 case 'd':
1673                         debug_flag = 1;
1674                         break;
1675                 case 'D':
1676                         daemonized_tracer = 1;
1677                         break;
1678                 case 'F':
1679                         optF = 1;
1680                         break;
1681                 case 'f':
1682                         followfork++;
1683                         break;
1684                 case 'h':
1685                         usage();
1686                         break;
1687                 case 'i':
1688                         iflag = 1;
1689                         break;
1690                 case 'q':
1691                         qflag++;
1692                         break;
1693                 case 'r':
1694                         rflag = 1;
1695                         break;
1696                 case 't':
1697                         tflag++;
1698                         break;
1699                 case 'T':
1700                         Tflag = 1;
1701                         break;
1702                 case 'w':
1703                         count_wallclock = 1;
1704                         break;
1705                 case 'x':
1706                         xflag++;
1707                         break;
1708                 case 'y':
1709                         show_fd_path++;
1710                         break;
1711                 case 'v':
1712                         qualify("abbrev=none");
1713                         break;
1714                 case 'V':
1715                         print_version();
1716                         exit(0);
1717                         break;
1718                 case 'z':
1719                         not_failing_only = 1;
1720                         break;
1721                 case 'a':
1722                         acolumn = string_to_uint(optarg);
1723                         if (acolumn < 0)
1724                                 error_opt_arg(c, optarg);
1725                         break;
1726                 case 'e':
1727                         qualify(optarg);
1728                         break;
1729                 case 'o':
1730                         outfname = xstrdup(optarg);
1731                         break;
1732                 case 'O':
1733                         i = string_to_uint(optarg);
1734                         if (i < 0)
1735                                 error_opt_arg(c, optarg);
1736                         set_overhead(i);
1737                         break;
1738                 case 'p':
1739                         process_opt_p_list(optarg);
1740                         break;
1741                 case 'P':
1742                         pathtrace_select(optarg);
1743                         break;
1744                 case 's':
1745                         i = string_to_uint(optarg);
1746                         if (i < 0)
1747                                 error_opt_arg(c, optarg);
1748                         max_strlen = i;
1749                         break;
1750                 case 'S':
1751                         set_sortby(optarg);
1752                         break;
1753                 case 'u':
1754                         username = xstrdup(optarg);
1755                         break;
1756 #ifdef USE_LIBUNWIND
1757                 case 'k':
1758                         stack_trace_enabled = true;
1759                         break;
1760 #endif
1761                 case 'E':
1762                         if (putenv(optarg) < 0)
1763                                 die_out_of_memory();
1764                         break;
1765                 case 'I':
1766                         opt_intr = string_to_uint_upto(optarg, NUM_INTR_OPTS - 1);
1767                         if (opt_intr <= 0)
1768                                 error_opt_arg(c, optarg);
1769                         break;
1770                 default:
1771                         error_msg_and_help(NULL);
1772                         break;
1773                 }
1774         }
1775         argv += optind;
1776         /* argc -= optind; - no need, argc is not used below */
1777
1778         acolumn_spaces = xmalloc(acolumn + 1);
1779         memset(acolumn_spaces, ' ', acolumn);
1780         acolumn_spaces[acolumn] = '\0';
1781
1782         if (!argv[0] && !nprocs) {
1783                 error_msg_and_help("must have PROG [ARGS] or -p PID");
1784         }
1785
1786         if (!argv[0] && daemonized_tracer) {
1787                 error_msg_and_help("PROG [ARGS] must be specified with -D");
1788         }
1789
1790         if (!followfork)
1791                 followfork = optF;
1792
1793         if (followfork >= 2 && cflag) {
1794                 error_msg_and_help("(-c or -C) and -ff are mutually exclusive");
1795         }
1796
1797         if (count_wallclock && !cflag) {
1798                 error_msg_and_help("-w must be given with (-c or -C)");
1799         }
1800
1801         if (cflag == CFLAG_ONLY_STATS) {
1802                 if (iflag)
1803                         error_msg("-%c has no effect with -c", 'i');
1804 #ifdef USE_LIBUNWIND
1805                 if (stack_trace_enabled)
1806                         error_msg("-%c has no effect with -c", 'k');
1807 #endif
1808                 if (rflag)
1809                         error_msg("-%c has no effect with -c", 'r');
1810                 if (tflag)
1811                         error_msg("-%c has no effect with -c", 't');
1812                 if (Tflag)
1813                         error_msg("-%c has no effect with -c", 'T');
1814                 if (show_fd_path)
1815                         error_msg("-%c has no effect with -c", 'y');
1816         }
1817
1818         if (rflag) {
1819                 if (tflag > 1)
1820                         error_msg("-tt has no effect with -r");
1821                 tflag = 1;
1822         }
1823
1824 #ifdef USE_LIBUNWIND
1825         if (stack_trace_enabled) {
1826                 unsigned int tcbi;
1827
1828                 unwind_init();
1829                 for (tcbi = 0; tcbi < tcbtabsize; ++tcbi) {
1830                         unwind_tcb_init(tcbtab[tcbi]);
1831                 }
1832         }
1833 #endif
1834
1835         /* See if they want to run as another user. */
1836         if (username != NULL) {
1837                 struct passwd *pent;
1838
1839                 if (getuid() != 0 || geteuid() != 0) {
1840                         error_msg_and_die("You must be root to use the -u option");
1841                 }
1842                 pent = getpwnam(username);
1843                 if (pent == NULL) {
1844                         error_msg_and_die("Cannot find user '%s'", username);
1845                 }
1846                 run_uid = pent->pw_uid;
1847                 run_gid = pent->pw_gid;
1848         }
1849         else {
1850                 run_uid = getuid();
1851                 run_gid = getgid();
1852         }
1853
1854         if (followfork)
1855                 ptrace_setoptions |= PTRACE_O_TRACECLONE |
1856                                      PTRACE_O_TRACEFORK |
1857                                      PTRACE_O_TRACEVFORK;
1858         if (debug_flag)
1859                 error_msg("ptrace_setoptions = %#x", ptrace_setoptions);
1860         test_ptrace_seize();
1861
1862         /*
1863          * Is something weird with our stdin and/or stdout -
1864          * for example, may they be not open? In this case,
1865          * ensure that none of the future opens uses them.
1866          *
1867          * This was seen in the wild when /proc/sys/kernel/core_pattern
1868          * was set to "|/bin/strace -o/tmp/LOG PROG":
1869          * kernel runs coredump helper with fd#0 open but fd#1 closed (!),
1870          * therefore LOG gets opened to fd#1, and fd#1 is closed by
1871          * "don't hold up stdin/out open" code soon after.
1872          */
1873         ensure_standard_fds_opened();
1874
1875         /* Check if they want to redirect the output. */
1876         if (outfname) {
1877                 /* See if they want to pipe the output. */
1878                 if (outfname[0] == '|' || outfname[0] == '!') {
1879                         /*
1880                          * We can't do the <outfname>.PID funny business
1881                          * when using popen, so prohibit it.
1882                          */
1883                         if (followfork >= 2)
1884                                 error_msg_and_help("piping the output and -ff are mutually exclusive");
1885                         shared_log = strace_popen(outfname + 1);
1886                 }
1887                 else if (followfork < 2)
1888                         shared_log = strace_fopen(outfname);
1889         } else {
1890                 /* -ff without -o FILE is the same as single -f */
1891                 if (followfork >= 2)
1892                         followfork = 1;
1893         }
1894
1895         if (!outfname || outfname[0] == '|' || outfname[0] == '!') {
1896                 setvbuf(shared_log, NULL, _IOLBF, 0);
1897         }
1898
1899         /*
1900          * argv[0]      -pPID   -oFILE  Default interactive setting
1901          * yes          *       0       INTR_WHILE_WAIT
1902          * no           1       0       INTR_WHILE_WAIT
1903          * yes          *       1       INTR_NEVER
1904          * no           1       1       INTR_WHILE_WAIT
1905          */
1906
1907         if (outfname && argv[0]) {
1908                 if (!opt_intr)
1909                         opt_intr = INTR_NEVER;
1910                 if (!qflag)
1911                         qflag = 1;
1912         }
1913         if (!opt_intr)
1914                 opt_intr = INTR_WHILE_WAIT;
1915
1916         sigprocmask(SIG_SETMASK, NULL, &start_set);
1917         memcpy(&blocked_set, &start_set, sizeof(blocked_set));
1918
1919         /*
1920          * startup_child() must be called before the signal handlers get
1921          * installed below as they are inherited into the spawned process.
1922          * Also we do not need to be protected by them as during interruption
1923          * in the startup_child() mode we kill the spawned process anyway.
1924          */
1925         if (argv[0]) {
1926                 startup_child(argv);
1927         }
1928
1929         set_sigaction(SIGTTOU, SIG_IGN, NULL);
1930         set_sigaction(SIGTTIN, SIG_IGN, NULL);
1931         if (opt_intr != INTR_ANYWHERE) {
1932                 if (opt_intr == INTR_BLOCK_TSTP_TOO)
1933                         set_sigaction(SIGTSTP, SIG_IGN, NULL);
1934                 /*
1935                  * In interactive mode (if no -o OUTFILE, or -p PID is used),
1936                  * fatal signals are blocked while syscall stop is processed,
1937                  * and acted on in between, when waiting for new syscall stops.
1938                  * In non-interactive mode, signals are ignored.
1939                  */
1940                 set_sigaction(SIGHUP, interactive ? interrupt : SIG_IGN, NULL);
1941                 set_sigaction(SIGINT, interactive ? interrupt : SIG_IGN, NULL);
1942                 set_sigaction(SIGQUIT, interactive ? interrupt : SIG_IGN, NULL);
1943                 set_sigaction(SIGPIPE, interactive ? interrupt : SIG_IGN, NULL);
1944                 set_sigaction(SIGTERM, interactive ? interrupt : SIG_IGN, NULL);
1945         }
1946
1947         if (nprocs != 0 || daemonized_tracer)
1948                 startup_attach();
1949
1950         /* Do we want pids printed in our -o OUTFILE?
1951          * -ff: no (every pid has its own file); or
1952          * -f: yes (there can be more pids in the future); or
1953          * -p PID1,PID2: yes (there are already more than one pid)
1954          */
1955         print_pid_pfx = (outfname && followfork < 2 && (followfork == 1 || nprocs > 1));
1956 }
1957
1958 static struct tcb *
1959 pid2tcb(int pid)
1960 {
1961         unsigned int i;
1962
1963         if (pid <= 0)
1964                 return NULL;
1965
1966         for (i = 0; i < tcbtabsize; i++) {
1967                 struct tcb *tcp = tcbtab[i];
1968                 if (tcp->pid == pid)
1969                         return tcp;
1970         }
1971
1972         return NULL;
1973 }
1974
1975 static void
1976 cleanup(void)
1977 {
1978         unsigned int i;
1979         struct tcb *tcp;
1980         int fatal_sig;
1981
1982         /* 'interrupted' is a volatile object, fetch it only once */
1983         fatal_sig = interrupted;
1984         if (!fatal_sig)
1985                 fatal_sig = SIGTERM;
1986
1987         for (i = 0; i < tcbtabsize; i++) {
1988                 tcp = tcbtab[i];
1989                 if (!tcp->pid)
1990                         continue;
1991                 if (debug_flag)
1992                         error_msg("cleanup: looking at pid %u", tcp->pid);
1993                 if (tcp->pid == strace_child) {
1994                         kill(tcp->pid, SIGCONT);
1995                         kill(tcp->pid, fatal_sig);
1996                 }
1997                 detach(tcp);
1998         }
1999         if (cflag)
2000                 call_summary(shared_log);
2001 }
2002
2003 static void
2004 interrupt(int sig)
2005 {
2006         interrupted = sig;
2007 }
2008
2009 static void
2010 print_debug_info(const int pid, int status)
2011 {
2012         const unsigned int event = (unsigned int) status >> 16;
2013         char buf[sizeof("WIFEXITED,exitcode=%u") + sizeof(int)*3 /*paranoia:*/ + 16];
2014         char evbuf[sizeof(",EVENT_VFORK_DONE (%u)") + sizeof(int)*3 /*paranoia:*/ + 16];
2015
2016         strcpy(buf, "???");
2017         if (WIFSIGNALED(status))
2018 #ifdef WCOREDUMP
2019                 sprintf(buf, "WIFSIGNALED,%ssig=%s",
2020                                 WCOREDUMP(status) ? "core," : "",
2021                                 signame(WTERMSIG(status)));
2022 #else
2023                 sprintf(buf, "WIFSIGNALED,sig=%s",
2024                                 signame(WTERMSIG(status)));
2025 #endif
2026         if (WIFEXITED(status))
2027                 sprintf(buf, "WIFEXITED,exitcode=%u", WEXITSTATUS(status));
2028         if (WIFSTOPPED(status))
2029                 sprintf(buf, "WIFSTOPPED,sig=%s", signame(WSTOPSIG(status)));
2030 #ifdef WIFCONTINUED
2031         /* Should never be seen */
2032         if (WIFCONTINUED(status))
2033                 strcpy(buf, "WIFCONTINUED");
2034 #endif
2035         evbuf[0] = '\0';
2036         if (event != 0) {
2037                 static const char *const event_names[] = {
2038                         [PTRACE_EVENT_CLONE] = "CLONE",
2039                         [PTRACE_EVENT_FORK]  = "FORK",
2040                         [PTRACE_EVENT_VFORK] = "VFORK",
2041                         [PTRACE_EVENT_VFORK_DONE] = "VFORK_DONE",
2042                         [PTRACE_EVENT_EXEC]  = "EXEC",
2043                         [PTRACE_EVENT_EXIT]  = "EXIT",
2044                         /* [PTRACE_EVENT_STOP (=128)] would make biggish array */
2045                 };
2046                 const char *e = "??";
2047                 if (event < ARRAY_SIZE(event_names))
2048                         e = event_names[event];
2049                 else if (event == PTRACE_EVENT_STOP)
2050                         e = "STOP";
2051                 sprintf(evbuf, ",EVENT_%s (%u)", e, event);
2052         }
2053         error_msg("[wait(0x%06x) = %u] %s%s", status, pid, buf, evbuf);
2054 }
2055
2056 static struct tcb *
2057 maybe_allocate_tcb(const int pid, int status)
2058 {
2059         if (!WIFSTOPPED(status)) {
2060                 if (detach_on_execve && pid == strace_child) {
2061                         /* example: strace -bexecve sh -c 'exec true' */
2062                         strace_child = 0;
2063                         return NULL;
2064                 }
2065                 /*
2066                  * This can happen if we inherited an unknown child.
2067                  * Example: (sleep 1 & exec strace true)
2068                  */
2069                 error_msg("Exit of unknown pid %u ignored", pid);
2070                 return NULL;
2071         }
2072         if (followfork) {
2073                 /* We assume it's a fork/vfork/clone child */
2074                 struct tcb *tcp = alloctcb(pid);
2075                 tcp->flags |= TCB_ATTACHED | TCB_STARTUP | post_attach_sigstop;
2076                 newoutf(tcp);
2077                 if (!qflag)
2078                         error_msg("Process %d attached", pid);
2079                 return tcp;
2080         } else {
2081                 /* This can happen if a clone call used
2082                  * CLONE_PTRACE itself.
2083                  */
2084                 ptrace(PTRACE_CONT, pid, NULL, 0);
2085                 error_msg("Stop of unknown pid %u seen, PTRACE_CONTed it", pid);
2086                 return NULL;
2087         }
2088 }
2089
2090 static struct tcb *
2091 maybe_switch_tcbs(struct tcb *tcp, const int pid)
2092 {
2093         FILE *fp;
2094         struct tcb *execve_thread;
2095         long old_pid = 0;
2096
2097         if (ptrace(PTRACE_GETEVENTMSG, pid, NULL, &old_pid) < 0)
2098                 return tcp;
2099         /* Avoid truncation in pid2tcb() param passing */
2100         if (old_pid <= 0 || old_pid == pid)
2101                 return tcp;
2102         if ((unsigned long) old_pid > UINT_MAX)
2103                 return tcp;
2104         execve_thread = pid2tcb(old_pid);
2105         /* It should be !NULL, but I feel paranoid */
2106         if (!execve_thread)
2107                 return tcp;
2108
2109         if (execve_thread->curcol != 0) {
2110                 /*
2111                  * One case we are here is -ff:
2112                  * try "strace -oLOG -ff test/threaded_execve"
2113                  */
2114                 fprintf(execve_thread->outf, " <pid changed to %d ...>\n", pid);
2115                 /*execve_thread->curcol = 0; - no need, see code below */
2116         }
2117         /* Swap output FILEs (needed for -ff) */
2118         fp = execve_thread->outf;
2119         execve_thread->outf = tcp->outf;
2120         tcp->outf = fp;
2121         /* And their column positions */
2122         execve_thread->curcol = tcp->curcol;
2123         tcp->curcol = 0;
2124         /* Drop leader, but close execve'd thread outfile (if -ff) */
2125         droptcb(tcp);
2126         /* Switch to the thread, reusing leader's outfile and pid */
2127         tcp = execve_thread;
2128         tcp->pid = pid;
2129         if (cflag != CFLAG_ONLY_STATS) {
2130                 printleader(tcp);
2131                 tprintf("+++ superseded by execve in pid %lu +++\n", old_pid);
2132                 line_ended();
2133                 tcp->flags |= TCB_REPRINT;
2134         }
2135
2136         return tcp;
2137 }
2138
2139 static void
2140 print_signalled(struct tcb *tcp, const int pid, int status)
2141 {
2142         if (pid == strace_child) {
2143                 exit_code = 0x100 | WTERMSIG(status);
2144                 strace_child = 0;
2145         }
2146
2147         if (cflag != CFLAG_ONLY_STATS
2148             && is_number_in_set(WTERMSIG(status), &signal_set)) {
2149                 printleader(tcp);
2150 #ifdef WCOREDUMP
2151                 tprintf("+++ killed by %s %s+++\n",
2152                         signame(WTERMSIG(status)),
2153                         WCOREDUMP(status) ? "(core dumped) " : "");
2154 #else
2155                 tprintf("+++ killed by %s +++\n",
2156                         signame(WTERMSIG(status)));
2157 #endif
2158                 line_ended();
2159         }
2160 }
2161
2162 static void
2163 print_exited(struct tcb *tcp, const int pid, int status)
2164 {
2165         if (pid == strace_child) {
2166                 exit_code = WEXITSTATUS(status);
2167                 strace_child = 0;
2168         }
2169
2170         if (cflag != CFLAG_ONLY_STATS &&
2171             qflag < 2) {
2172                 printleader(tcp);
2173                 tprintf("+++ exited with %d +++\n", WEXITSTATUS(status));
2174                 line_ended();
2175         }
2176 }
2177
2178 static void
2179 print_stopped(struct tcb *tcp, const siginfo_t *si, const unsigned int sig)
2180 {
2181         if (cflag != CFLAG_ONLY_STATS
2182             && !hide_log(tcp)
2183             && is_number_in_set(sig, &signal_set)) {
2184                 printleader(tcp);
2185                 if (si) {
2186                         tprintf("--- %s ", signame(sig));
2187                         printsiginfo(si);
2188                         tprints(" ---\n");
2189                 } else
2190                         tprintf("--- stopped by %s ---\n", signame(sig));
2191                 line_ended();
2192         }
2193 }
2194
2195 static void
2196 startup_tcb(struct tcb *tcp)
2197 {
2198         if (debug_flag)
2199                 error_msg("pid %d has TCB_STARTUP, initializing it", tcp->pid);
2200
2201         tcp->flags &= ~TCB_STARTUP;
2202
2203         if (!use_seize) {
2204                 if (debug_flag)
2205                         error_msg("setting opts 0x%x on pid %d",
2206                                   ptrace_setoptions, tcp->pid);
2207                 if (ptrace(PTRACE_SETOPTIONS, tcp->pid, NULL, ptrace_setoptions) < 0) {
2208                         if (errno != ESRCH) {
2209                                 /* Should never happen, really */
2210                                 perror_msg_and_die("PTRACE_SETOPTIONS");
2211                         }
2212                 }
2213         }
2214
2215         if (get_scno(tcp) == 1)
2216                 tcp->s_prev_ent = tcp->s_ent;
2217 }
2218
2219 static void
2220 print_event_exit(struct tcb *tcp)
2221 {
2222         if (entering(tcp) || filtered(tcp) || hide_log(tcp)
2223             || cflag == CFLAG_ONLY_STATS) {
2224                 return;
2225         }
2226
2227         if (followfork < 2 && printing_tcp && printing_tcp != tcp
2228             && printing_tcp->curcol != 0) {
2229                 current_tcp = printing_tcp;
2230                 tprints(" <unfinished ...>\n");
2231                 fflush(printing_tcp->outf);
2232                 printing_tcp->curcol = 0;
2233                 current_tcp = tcp;
2234         }
2235
2236         if ((followfork < 2 && printing_tcp != tcp)
2237             || (tcp->flags & TCB_REPRINT)) {
2238                 tcp->flags &= ~TCB_REPRINT;
2239                 printleader(tcp);
2240                 tprintf("<... %s resumed>", tcp->s_ent->sys_name);
2241         }
2242
2243         if (!(tcp->sys_func_rval & RVAL_DECODED)) {
2244                 /*
2245                  * The decoder has probably decided to print something
2246                  * on exiting syscall which is not going to happen.
2247                  */
2248                 tprints(" <unfinished ...>");
2249         }
2250         tprints(") ");
2251         tabto();
2252         tprints("= ?\n");
2253         line_ended();
2254 }
2255
2256 /* Returns true iff the main trace loop has to continue. */
2257 static bool
2258 trace(void)
2259 {
2260         int pid;
2261         int wait_errno;
2262         int status;
2263         bool stopped;
2264         unsigned int sig;
2265         unsigned int event;
2266         struct tcb *tcp;
2267         struct rusage ru;
2268
2269         if (interrupted)
2270                 return false;
2271
2272         /*
2273          * Used to exit simply when nprocs hits zero, but in this testcase:
2274          *  int main() { _exit(!!fork()); }
2275          * under strace -f, parent sometimes (rarely) manages
2276          * to exit before we see the first stop of the child,
2277          * and we are losing track of it:
2278          *  19923 clone(...) = 19924
2279          *  19923 exit_group(1)     = ?
2280          *  19923 +++ exited with 1 +++
2281          * Exiting only when wait() returns ECHILD works better.
2282          */
2283         if (popen_pid != 0) {
2284                 /* However, if -o|logger is in use, we can't do that.
2285                  * Can work around that by double-forking the logger,
2286                  * but that loses the ability to wait for its completion
2287                  * on exit. Oh well...
2288                  */
2289                 if (nprocs == 0)
2290                         return false;
2291         }
2292
2293         if (interactive)
2294                 sigprocmask(SIG_SETMASK, &start_set, NULL);
2295         pid = wait4(-1, &status, __WALL, (cflag ? &ru : NULL));
2296         wait_errno = errno;
2297         if (interactive)
2298                 sigprocmask(SIG_SETMASK, &blocked_set, NULL);
2299
2300         if (pid < 0) {
2301                 if (wait_errno == EINTR)
2302                         return true;
2303                 if (nprocs == 0 && wait_errno == ECHILD)
2304                         return false;
2305                 /*
2306                  * If nprocs > 0, ECHILD is not expected,
2307                  * treat it as any other error here:
2308                  */
2309                 errno = wait_errno;
2310                 perror_msg_and_die("wait4(__WALL)");
2311         }
2312
2313         if (pid == popen_pid) {
2314                 if (!WIFSTOPPED(status))
2315                         popen_pid = 0;
2316                 return true;
2317         }
2318
2319         if (debug_flag)
2320                 print_debug_info(pid, status);
2321
2322         /* Look up 'pid' in our table. */
2323         tcp = pid2tcb(pid);
2324
2325         if (!tcp) {
2326                 tcp = maybe_allocate_tcb(pid, status);
2327                 if (!tcp)
2328                         return true;
2329         }
2330
2331         clear_regs();
2332
2333         event = (unsigned int) status >> 16;
2334
2335         if (event == PTRACE_EVENT_EXEC) {
2336                 /*
2337                  * Under Linux, execve changes pid to thread leader's pid,
2338                  * and we see this changed pid on EVENT_EXEC and later,
2339                  * execve sysexit. Leader "disappears" without exit
2340                  * notification. Let user know that, drop leader's tcb,
2341                  * and fix up pid in execve thread's tcb.
2342                  * Effectively, execve thread's tcb replaces leader's tcb.
2343                  *
2344                  * BTW, leader is 'stuck undead' (doesn't report WIFEXITED
2345                  * on exit syscall) in multithreaded programs exactly
2346                  * in order to handle this case.
2347                  *
2348                  * PTRACE_GETEVENTMSG returns old pid starting from Linux 3.0.
2349                  * On 2.6 and earlier, it can return garbage.
2350                  */
2351                 if (os_release >= KERNEL_VERSION(3,0,0))
2352                         tcp = maybe_switch_tcbs(tcp, pid);
2353
2354                 if (detach_on_execve) {
2355                         if (tcp->flags & TCB_SKIP_DETACH_ON_FIRST_EXEC) {
2356                                 tcp->flags &= ~TCB_SKIP_DETACH_ON_FIRST_EXEC;
2357                         } else {
2358                                 detach(tcp); /* do "-b execve" thingy */
2359                                 return true;
2360                         }
2361                 }
2362         }
2363
2364         /* Set current output file */
2365         current_tcp = tcp;
2366
2367         if (cflag) {
2368                 tv_sub(&tcp->dtime, &ru.ru_stime, &tcp->stime);
2369                 tcp->stime = ru.ru_stime;
2370         }
2371
2372         if (WIFSIGNALED(status)) {
2373                 print_signalled(tcp, pid, status);
2374                 droptcb(tcp);
2375                 return true;
2376         }
2377
2378         if (WIFEXITED(status)) {
2379                 print_exited(tcp, pid, status);
2380                 droptcb(tcp);
2381                 return true;
2382         }
2383
2384         if (!WIFSTOPPED(status)) {
2385                 /*
2386                  * Neither signalled, exited or stopped.
2387                  * How could that be?
2388                  */
2389                 error_msg("pid %u not stopped!", pid);
2390                 droptcb(tcp);
2391                 return true;
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
2399         sig = WSTOPSIG(status);
2400
2401         switch (event) {
2402                 case 0:
2403                         break;
2404                 case PTRACE_EVENT_EXIT:
2405                         print_event_exit(tcp);
2406                         goto restart_tracee_with_sig_0;
2407 #if USE_SEIZE
2408                 case PTRACE_EVENT_STOP:
2409                         /*
2410                          * PTRACE_INTERRUPT-stop or group-stop.
2411                          * PTRACE_INTERRUPT-stop has sig == SIGTRAP here.
2412                          */
2413                         switch (sig) {
2414                                 case SIGSTOP:
2415                                 case SIGTSTP:
2416                                 case SIGTTIN:
2417                                 case SIGTTOU:
2418                                         stopped = true;
2419                                         goto show_stopsig;
2420                         }
2421                         /* fall through */
2422 #endif
2423                 default:
2424                         goto restart_tracee_with_sig_0;
2425         }
2426
2427         /*
2428          * Is this post-attach SIGSTOP?
2429          * Interestingly, the process may stop
2430          * with STOPSIG equal to some other signal
2431          * than SIGSTOP if we happend to attach
2432          * just before the process takes a signal.
2433          */
2434         if (sig == SIGSTOP && (tcp->flags & TCB_IGNORE_ONE_SIGSTOP)) {
2435                 if (debug_flag)
2436                         error_msg("ignored SIGSTOP on pid %d", tcp->pid);
2437                 tcp->flags &= ~TCB_IGNORE_ONE_SIGSTOP;
2438                 goto restart_tracee_with_sig_0;
2439         }
2440
2441         if (sig != syscall_trap_sig) {
2442                 siginfo_t si = {};
2443
2444                 /*
2445                  * True if tracee is stopped by signal
2446                  * (as opposed to "tracee received signal").
2447                  * TODO: shouldn't we check for errno == EINVAL too?
2448                  * We can get ESRCH instead, you know...
2449                  */
2450                 stopped = ptrace(PTRACE_GETSIGINFO, pid, 0, &si) < 0;
2451 #if USE_SEIZE
2452 show_stopsig:
2453 #endif
2454                 print_stopped(tcp, stopped ? NULL : &si, sig);
2455
2456                 if (!stopped)
2457                         /* It's signal-delivery-stop. Inject the signal */
2458                         goto restart_tracee;
2459
2460                 /* It's group-stop */
2461                 if (use_seize) {
2462                         /*
2463                          * This ends ptrace-stop, but does *not* end group-stop.
2464                          * This makes stopping signals work properly on straced process
2465                          * (that is, process really stops. It used to continue to run).
2466                          */
2467                         if (ptrace_restart(PTRACE_LISTEN, tcp, 0) < 0) {
2468                                 /* Note: ptrace_restart emitted error message */
2469                                 exit_code = 1;
2470                                 return false;
2471                         }
2472                         return true;
2473                 }
2474                 /* We don't have PTRACE_LISTEN support... */
2475                 goto restart_tracee;
2476         }
2477
2478         /* We handled quick cases, we are permitted to interrupt now. */
2479         if (interrupted)
2480                 return false;
2481
2482         /*
2483          * This should be syscall entry or exit.
2484          * Handle it.
2485          */
2486         sig = 0;
2487         if (trace_syscall(tcp, &sig) < 0) {
2488                 /*
2489                  * ptrace() failed in trace_syscall().
2490                  * Likely a result of process disappearing mid-flight.
2491                  * Observed case: exit_group() or SIGKILL terminating
2492                  * all processes in thread group.
2493                  * We assume that ptrace error was caused by process death.
2494                  * We used to detach(tcp) here, but since we no longer
2495                  * implement "detach before death" policy/hack,
2496                  * we can let this process to report its death to us
2497                  * normally, via WIFEXITED or WIFSIGNALED wait status.
2498                  */
2499                 return true;
2500         }
2501         goto restart_tracee;
2502
2503 restart_tracee_with_sig_0:
2504         sig = 0;
2505
2506 restart_tracee:
2507         if (ptrace_restart(PTRACE_SYSCALL, tcp, sig) < 0) {
2508                 /* Note: ptrace_restart emitted error message */
2509                 exit_code = 1;
2510                 return false;
2511         }
2512
2513         return true;
2514 }
2515
2516 int
2517 main(int argc, char *argv[])
2518 {
2519         init(argc, argv);
2520
2521         exit_code = !nprocs;
2522
2523         while (trace())
2524                 ;
2525
2526         cleanup();
2527         fflush(NULL);
2528         if (shared_log != stderr)
2529                 fclose(shared_log);
2530         if (popen_pid) {
2531                 while (waitpid(popen_pid, NULL, 0) < 0 && errno == EINTR)
2532                         ;
2533         }
2534         if (exit_code > 0xff) {
2535                 /* Avoid potential core file clobbering.  */
2536                 struct_rlimit rlim = {0, 0};
2537                 set_rlimit(RLIMIT_CORE, &rlim);
2538
2539                 /* Child was killed by a signal, mimic that.  */
2540                 exit_code &= 0xff;
2541                 signal(exit_code, SIG_DFL);
2542                 raise(exit_code);
2543                 /* Paranoia - what if this signal is not fatal?
2544                    Exit with 128 + signo then.  */
2545                 exit_code += 128;
2546         }
2547
2548         return exit_code;
2549 }