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