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