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