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