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