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