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