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