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