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>
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
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.
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.
35 #include <sys/types.h>
39 #include <sys/param.h>
41 #include <sys/resource.h>
51 # include <asm/unistd.h>
52 # if defined __NR_tgkill
53 # define my_tgkill(pid, tid, sig) syscall(__NR_tgkill, (pid), (tid), (sig))
54 # elif defined __NR_tkill
55 # define my_tgkill(pid, tid, sig) syscall(__NR_tkill, (tid), (sig))
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 "Neither tkill(2) nor tgkill(2) available, risk of strace hangs!"
61 # define my_tgkill(pid, tid, sig) kill((tid), (sig))
65 #if defined(IA64) && defined(LINUX)
66 # include <asm/ptrace_offsets.h>
74 #include <sys/stropts.h>
81 extern char **environ;
86 int debug = 0, followfork = 0;
87 unsigned int ptrace_setoptions = 0;
88 /* Which WSTOPSIG(status) value marks syscall traps? */
89 static unsigned int syscall_trap_sig = SIGTRAP;
90 int dtime = 0, xflag = 0, qflag = 0;
91 cflag_t cflag = CFLAG_NONE;
92 static int iflag = 0, interactive = 0, pflag_seen = 0, rflag = 0, tflag = 0;
94 * daemonized_tracer supports -D option.
95 * With this option, strace forks twice.
96 * Unlike normal case, with -D *grandparent* process exec's,
97 * becoming a traced process. Child exits (this prevents traced process
98 * from having children it doesn't expect to have), and grandchild
99 * attaches to grandparent similarly to strace -p PID.
100 * This allows for more transparent interaction in cases
101 * when process and its parent are communicating via signals,
102 * wait() etc. Without -D, strace process gets lodged in between,
103 * disrupting parent<->child link.
105 static bool daemonized_tracer = 0;
107 /* Sometimes we want to print only succeeding syscalls. */
108 int not_failing_only = 0;
110 /* Show path associated with fd arguments */
111 int show_fd_path = 0;
113 /* are we filtering traces based on paths? */
114 int tracing_paths = 0;
116 static int exit_code = 0;
117 static int strace_child = 0;
118 static int strace_tracer_pid = 0;
120 static char *username = NULL;
124 int acolumn = DEFAULT_ACOLUMN;
125 int max_strlen = DEFAULT_STRLEN;
126 static char *outfname = NULL;
130 unsigned int nprocs, tcbtabsize;
131 const char *progname;
132 extern char **environ;
134 static int detach(struct tcb *tcp, int sig);
135 static int trace(void);
136 static void cleanup(void);
137 static void interrupt(int sig);
138 static sigset_t empty_set, blocked_set;
140 #ifdef HAVE_SIG_ATOMIC_T
141 static volatile sig_atomic_t interrupted;
142 #else /* !HAVE_SIG_ATOMIC_T */
143 static volatile int interrupted;
144 #endif /* !HAVE_SIG_ATOMIC_T */
148 static struct tcb *pfd2tcb(int pfd);
149 static void reaper(int sig);
150 static void rebuild_pollv(void);
151 static struct pollfd *pollv;
153 #ifndef HAVE_POLLABLE_PROCFS
155 static void proc_poll_open(void);
156 static void proc_poller(int pfd);
164 static int poller_pid;
165 static int proc_poll_pipe[2] = { -1, -1 };
167 #endif /* !HAVE_POLLABLE_PROCFS */
169 #ifdef HAVE_MP_PROCFS
170 #define POLLWANT POLLWRNORM
172 #define POLLWANT POLLPRI
174 #endif /* USE_PROCFS */
182 usage: strace [-CdDffhiqrtttTvVxxy] [-a column] [-e expr] ... [-o file]\n\
183 [-p pid] ... [-s strsize] [-u username] [-E var=val] ...\n\
184 [-P path] [command [arg ...]]\n\
185 or: strace -c [-D] [-e expr] ... [-O overhead] [-S sortby] [-E var=val] ...\n\
186 [command [arg ...]]\n\
187 -c -- count time, calls, and errors for each syscall and report summary\n\
188 -C -- like -c but also print regular output while processes are running\n\
189 -f -- follow forks, -ff -- with output into separate files\n\
190 -F -- attempt to follow vforks, -h -- print help message\n\
191 -i -- print instruction pointer at time of syscall\n\
192 -q -- suppress messages about attaching, detaching, etc.\n\
193 -r -- print relative timestamp, -t -- absolute timestamp, -tt -- with usecs\n\
194 -T -- print time spent in each syscall, -V -- print version\n\
195 -v -- verbose mode: print unabbreviated argv, stat, termio[s], etc. args\n\
196 -x -- print non-ascii strings in hex, -xx -- print all strings in hex\n\
197 -y -- print paths associated with file descriptor arguments\n\
198 -a column -- alignment COLUMN for printing syscall results (default %d)\n\
199 -e expr -- a qualifying expression: option=[!]all or option=[!]val1[,val2]...\n\
200 options: trace, abbrev, verbose, raw, signal, read, or write\n\
201 -o file -- send trace output to FILE instead of stderr\n\
202 -O overhead -- set overhead for tracing syscalls to OVERHEAD usecs\n\
203 -p pid -- trace process with process id PID, may be repeated\n\
204 -D -- run tracer process as a detached grandchild, not as parent\n\
205 -s strsize -- limit length of print strings to STRSIZE chars (default %d)\n\
206 -S sortby -- sort syscall counts by: time, calls, name, nothing (default %s)\n\
207 -u username -- run command as username handling setuid and/or setgid\n\
208 -E var=val -- put var=val in the environment for command\n\
209 -E var -- remove var from the environment for command\n\
210 -P path -- trace accesses to path\n\
211 " /* this is broken, so don't document it
212 -z -- print only succeeding syscalls\n\
214 , DEFAULT_ACOLUMN, DEFAULT_STRLEN, DEFAULT_SORTBY);
218 static void die(void) __attribute__ ((noreturn));
219 static void die(void)
221 if (strace_tracer_pid == getpid()) {
228 static void verror_msg(int err_no, const char *fmt, va_list p)
231 fprintf(stderr, "%s: ", progname);
232 vfprintf(stderr, fmt, p);
234 fprintf(stderr, ": %s\n", strerror(err_no));
240 void error_msg(const char *fmt, ...)
244 verror_msg(0, fmt, p);
248 void error_msg_and_die(const char *fmt, ...)
252 verror_msg(0, fmt, p);
256 void perror_msg(const char *fmt, ...)
260 verror_msg(errno, fmt, p);
264 void perror_msg_and_die(const char *fmt, ...)
268 verror_msg(errno, fmt, p);
281 /* Glue for systems without a MMU that cannot provide fork() */
283 # define strace_vforked 0
285 # define strace_vforked 1
286 # define fork() vfork()
290 set_cloexec_flag(int fd)
294 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
296 fprintf(stderr, "%s: fcntl F_GETFD: %s\n",
297 progname, strerror(errno));
301 newflags = flags | FD_CLOEXEC;
302 if (flags == newflags)
305 if (fcntl(fd, F_SETFD, newflags) < 0)
307 fprintf(stderr, "%s: fcntl F_SETFD: %s\n",
308 progname, strerror(errno));
316 * When strace is setuid executable, we have to swap uids
317 * before and after filesystem and process management operations.
323 int euid = geteuid(), uid = getuid();
325 if (euid != uid && setreuid(euid, uid) < 0)
327 fprintf(stderr, "%s: setreuid: %s\n",
328 progname, strerror(errno));
335 # define fopen_for_output fopen64
337 # define fopen_for_output fopen
341 strace_fopen(const char *path, const char *mode)
346 if ((fp = fopen_for_output(path, mode)) == NULL)
347 fprintf(stderr, "%s: can't fopen '%s': %s\n",
348 progname, path, strerror(errno));
350 if (fp && set_cloexec_flag(fileno(fp)) < 0)
358 static int popen_pid = -1;
361 # define _PATH_BSHELL "/bin/sh"
365 * We cannot use standard popen(3) here because we have to distinguish
366 * popen child process from other processes we trace, and standard popen(3)
367 * does not export its child's pid.
370 strace_popen(const char *command)
377 fprintf(stderr, "%s: pipe: %s\n",
378 progname, strerror(errno));
383 if (set_cloexec_flag(fds[1]) < 0)
391 if ((popen_pid = fork()) == -1)
393 fprintf(stderr, "%s: fork: %s\n",
394 progname, strerror(errno));
406 return fdopen(fds[1], "w");
411 if (fds[0] && (dup2(fds[0], 0) || close(fds[0])))
413 fprintf(stderr, "%s: dup2: %s\n",
414 progname, strerror(errno));
417 execl(_PATH_BSHELL, "sh", "-c", command, NULL);
418 fprintf(stderr, "%s: execl: %s: %s\n",
419 progname, _PATH_BSHELL, strerror(errno));
425 newoutf(struct tcb *tcp)
427 if (outfname && followfork > 1) {
428 char name[520 + sizeof(int) * 3];
431 sprintf(name, "%.512s.%u", outfname, tcp->pid);
432 if ((fp = strace_fopen(name, "w")) == NULL)
446 * Block user interruptions as we would leave the traced
447 * process stopped (process state T) if we would terminate in
448 * between PTRACE_ATTACH and wait4 () on SIGSTOP.
449 * We rely on cleanup() from this point on.
452 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
454 if (daemonized_tracer) {
459 if (pid) { /* parent */
461 * Wait for grandchild to attach to straced process
462 * (grandparent). Grandchild SIGKILLs us after it attached.
463 * Grandparent's wait() is unblocked by our death,
464 * it proceeds to exec the straced program.
467 _exit(0); /* paranoia */
470 /* We will be the tracer process. Remember our new pid: */
471 strace_tracer_pid = getpid();
474 for (tcbi = 0; tcbi < tcbtabsize; tcbi++) {
476 if (!(tcp->flags & TCB_INUSE) || !(tcp->flags & TCB_ATTACHED))
479 if (tcp->flags & TCB_CLONE_THREAD)
482 /* Reinitialize the output since it may have changed. */
484 if (newoutf(tcp) < 0)
488 if (proc_open(tcp, 1) < 0) {
489 fprintf(stderr, "trouble opening proc file\n");
493 #else /* !USE_PROCFS */
495 if (followfork && !daemonized_tracer) {
496 char procdir[sizeof("/proc/%d/task") + sizeof(int) * 3];
499 sprintf(procdir, "/proc/%d/task", tcp->pid);
500 dir = opendir(procdir);
502 unsigned int ntid = 0, nerr = 0;
505 while ((de = readdir(dir)) != NULL) {
506 if (de->d_fileno == 0)
508 tid = atoi(de->d_name);
512 if (ptrace(PTRACE_ATTACH, tid, (char *) 1, 0) < 0)
514 else if (tid != tcbtab[tcbi]->pid) {
516 tcp->flags |= TCB_ATTACHED|TCB_CLONE_THREAD|TCB_FOLLOWFORK;
517 tcbtab[tcbi]->nclone_threads++;
518 tcp->parent = tcbtab[tcbi];
521 sigprocmask(SIG_SETMASK, &empty_set, NULL);
524 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
530 perror("attach: ptrace(PTRACE_ATTACH, ...)");
535 fprintf(stderr, ntid > 1
536 ? "Process %u attached with %u threads - interrupt to quit\n"
537 : "Process %u attached - interrupt to quit\n",
538 tcbtab[tcbi]->pid, ntid);
541 } /* if (opendir worked) */
544 if (ptrace(PTRACE_ATTACH, tcp->pid, (char *) 1, 0) < 0) {
545 perror("attach: ptrace(PTRACE_ATTACH, ...)");
549 /* INTERRUPTED is going to be checked at the top of TRACE. */
551 if (daemonized_tracer) {
553 * It is our grandparent we trace, not a -p PID.
554 * Don't want to just detach on exit, so...
556 tcp->flags &= ~TCB_ATTACHED;
558 * Make parent go away.
559 * Also makes grandparent's wait() unblock.
561 kill(getppid(), SIGKILL);
564 #endif /* !USE_PROCFS */
567 "Process %u attached - interrupt to quit\n",
572 sigprocmask(SIG_SETMASK, &empty_set, NULL);
576 startup_child(char **argv)
579 const char *filename;
580 char pathname[MAXPATHLEN];
585 if (strchr(filename, '/')) {
586 if (strlen(filename) > sizeof pathname - 1) {
587 errno = ENAMETOOLONG;
588 perror("strace: exec");
591 strcpy(pathname, filename);
593 #ifdef USE_DEBUGGING_EXEC
595 * Debuggers customarily check the current directory
596 * first regardless of the path but doing that gives
597 * security geeks a panic attack.
599 else if (stat(filename, &statbuf) == 0)
600 strcpy(pathname, filename);
601 #endif /* USE_DEBUGGING_EXEC */
606 for (path = getenv("PATH"); path && *path; path += m) {
607 if (strchr(path, ':')) {
608 n = strchr(path, ':') - path;
612 m = n = strlen(path);
614 if (!getcwd(pathname, MAXPATHLEN))
616 len = strlen(pathname);
618 else if (n > sizeof pathname - 1)
621 strncpy(pathname, path, n);
624 if (len && pathname[len - 1] != '/')
625 pathname[len++] = '/';
626 strcpy(pathname + len, filename);
627 if (stat(pathname, &statbuf) == 0 &&
628 /* Accept only regular files
629 with some execute bits set.
630 XXX not perfect, might still fail */
631 S_ISREG(statbuf.st_mode) &&
632 (statbuf.st_mode & 0111))
636 if (stat(pathname, &statbuf) < 0) {
637 fprintf(stderr, "%s: %s: command not found\n",
641 strace_child = pid = fork();
643 perror("strace: fork");
647 if ((pid != 0 && daemonized_tracer) /* -D: parent to become a traced process */
648 || (pid == 0 && !daemonized_tracer) /* not -D: child to become a traced process */
652 if (outf != stderr) close(fileno(outf));
654 /* Kludge for SGI, see proc_open for details. */
655 sa.sa_handler = foobar;
657 sigemptyset(&sa.sa_mask);
658 sigaction(SIGINT, &sa, NULL);
663 kill(pid, SIGSTOP); /* stop HERE */
665 #else /* !USE_PROCFS */
669 if (!daemonized_tracer) {
670 if (ptrace(PTRACE_TRACEME, 0, (char *) 1, 0) < 0) {
671 perror("strace: ptrace(PTRACE_TRACEME, ...)");
678 if (username != NULL || geteuid() == 0) {
679 uid_t run_euid = run_uid;
680 gid_t run_egid = run_gid;
682 if (statbuf.st_mode & S_ISUID)
683 run_euid = statbuf.st_uid;
684 if (statbuf.st_mode & S_ISGID)
685 run_egid = statbuf.st_gid;
688 * It is important to set groups before we
689 * lose privileges on setuid.
691 if (username != NULL) {
692 if (initgroups(username, run_gid) < 0) {
693 perror("initgroups");
696 if (setregid(run_gid, run_egid) < 0) {
700 if (setreuid(run_uid, run_euid) < 0) {
707 setreuid(run_uid, run_uid);
709 if (!daemonized_tracer) {
711 * Induce an immediate stop so that the parent
712 * will resume us with PTRACE_SYSCALL and display
713 * this execve call normally.
714 * Unless of course we're on a no-MMU system where
715 * we vfork()-ed, so we cannot stop the child.
718 kill(getpid(), SIGSTOP);
720 struct sigaction sv_sigchld;
721 sigaction(SIGCHLD, NULL, &sv_sigchld);
723 * Make sure it is not SIG_IGN, otherwise wait
726 signal(SIGCHLD, SIG_DFL);
728 * Wait for grandchild to attach to us.
729 * It kills child after that, and wait() unblocks.
734 sigaction(SIGCHLD, &sv_sigchld, NULL);
736 #endif /* !USE_PROCFS */
738 execv(pathname, argv);
739 perror("strace: exec");
743 /* We are the tracer. */
744 /* With -D, we are *child* here, IOW: different pid. Fetch it. */
745 strace_tracer_pid = getpid();
747 tcp = alloctcb(daemonized_tracer ? getppid() : pid);
748 if (daemonized_tracer) {
749 /* We want subsequent startup_attach() to attach to it. */
750 tcp->flags |= TCB_ATTACHED;
753 if (proc_open(tcp, 0) < 0) {
754 fprintf(stderr, "trouble opening proc file\n");
758 #endif /* USE_PROCFS */
763 * Test whether the kernel support PTRACE_O_TRACECLONE et al options.
764 * First fork a new child, call ptrace with PTRACE_SETOPTIONS on it,
765 * and then see which options are supported by the kernel.
768 test_ptrace_setoptions_followfork(void)
770 int pid, expected_grandchild = 0, found_grandchild = 0;
771 const unsigned int test_options = PTRACE_O_TRACECLONE |
775 if ((pid = fork()) < 0)
778 if (ptrace(PTRACE_TRACEME, 0, (char *)1, 0) < 0)
780 kill(getpid(), SIGSTOP);
785 int status, tracee_pid;
787 tracee_pid = wait(&status);
788 if (tracee_pid == -1) {
791 else if (errno == ECHILD)
793 perror("test_ptrace_setoptions_followfork");
796 if (tracee_pid != pid) {
797 found_grandchild = tracee_pid;
798 if (ptrace(PTRACE_CONT, tracee_pid, 0, 0) < 0 &&
800 kill(tracee_pid, SIGKILL);
802 else if (WIFSTOPPED(status)) {
803 switch (WSTOPSIG(status)) {
805 if (ptrace(PTRACE_SETOPTIONS, pid,
806 NULL, test_options) < 0) {
812 if (status >> 16 == PTRACE_EVENT_FORK) {
815 if (ptrace(PTRACE_GETEVENTMSG, pid,
816 NULL, (long) &msg) == 0)
817 expected_grandchild = msg;
821 if (ptrace(PTRACE_SYSCALL, pid, 0, 0) < 0 &&
826 if (expected_grandchild && expected_grandchild == found_grandchild)
827 ptrace_setoptions |= test_options;
832 * Test whether the kernel support PTRACE_O_TRACESYSGOOD.
833 * First fork a new child, call ptrace(PTRACE_SETOPTIONS) on it,
834 * and then see whether it will stop with (SIGTRAP | 0x80).
836 * Use of this option enables correct handling of user-generated SIGTRAPs,
837 * and SIGTRAPs generated by special instructions such as int3 on x86:
838 * _start: .globl _start
843 * (compile with: "gcc -nostartfiles -nostdlib -o int3 int3.S")
846 test_ptrace_setoptions_for_all(void)
848 const unsigned int test_options = PTRACE_O_TRACESYSGOOD | PTRACE_O_TRACEEXEC;
854 perror_msg_and_die("fork");
858 if (ptrace(PTRACE_TRACEME, 0L, 0L, 0L) < 0)
859 /* Note: exits with exitcode 1 */
860 perror_msg_and_die("%s: PTRACE_TRACEME doesn't work", __func__);
862 _exit(0); /* parent should see entry into this syscall */
866 int status, tracee_pid;
869 tracee_pid = wait(&status);
870 if (tracee_pid <= 0) {
874 perror_msg_and_die("%s: unexpected wait result %d", __func__, tracee_pid);
876 if (WIFEXITED(status)) {
877 if (WEXITSTATUS(status) == 0)
879 /* PTRACE_TRACEME failed in child. This is fatal. */
882 if (!WIFSTOPPED(status)) {
884 error_msg_and_die("%s: unexpected wait status %x", __func__, status);
886 if (WSTOPSIG(status) == SIGSTOP) {
888 * We don't check "options aren't accepted" error.
889 * If it happens, we'll never get (SIGTRAP | 0x80),
890 * and thus will decide to not use the option.
891 * IOW: the outcome of the test will be correct.
893 if (ptrace(PTRACE_SETOPTIONS, pid, 0L, test_options) < 0)
895 perror_msg("PTRACE_SETOPTIONS");
897 if (WSTOPSIG(status) == (SIGTRAP | 0x80)) {
900 if (ptrace(PTRACE_SYSCALL, pid, 0L, 0L) < 0) {
902 perror_msg_and_die("PTRACE_SYSCALL doesn't work");
907 syscall_trap_sig = (SIGTRAP | 0x80);
908 ptrace_setoptions |= test_options;
910 fprintf(stderr, "ptrace_setoptions = %#x\n",
916 "Test for PTRACE_O_TRACESYSGOOD failed, giving up using this feature.\n");
921 main(int argc, char *argv[])
928 static char buf[BUFSIZ];
930 progname = argv[0] ? argv[0] : "strace";
932 strace_tracer_pid = getpid();
934 /* Allocate the initial tcbtab. */
935 tcbtabsize = argc; /* Surely enough for all -p args. */
936 if ((tcbtab = calloc(tcbtabsize, sizeof tcbtab[0])) == NULL) {
937 fprintf(stderr, "%s: out of memory\n", progname);
940 if ((tcbtab[0] = calloc(tcbtabsize, sizeof tcbtab[0][0])) == NULL) {
941 fprintf(stderr, "%s: out of memory\n", progname);
944 for (tcp = tcbtab[0]; tcp < &tcbtab[0][tcbtabsize]; ++tcp)
945 tcbtab[tcp - tcbtab[0]] = &tcbtab[0][tcp - tcbtab[0]];
949 set_sortby(DEFAULT_SORTBY);
950 set_personality(DEFAULT_PERSONALITY);
951 qualify("trace=all");
952 qualify("abbrev=all");
953 qualify("verbose=all");
954 qualify("signal=all");
955 while ((c = getopt(argc, argv,
960 "a:e:o:O:p:s:S:u:E:P:")) != EOF) {
963 if (cflag == CFLAG_BOTH) {
964 fprintf(stderr, "%s: -c and -C are mutually exclusive options\n",
968 cflag = CFLAG_ONLY_STATS;
971 if (cflag == CFLAG_ONLY_STATS) {
972 fprintf(stderr, "%s: -c and -C are mutually exclusive options\n",
983 daemonized_tracer = 1;
1018 qualify("abbrev=none");
1021 printf("%s -- version %s\n", PACKAGE_NAME, VERSION);
1025 not_failing_only = 1;
1028 acolumn = atoi(optarg);
1034 outfname = strdup(optarg);
1037 set_overhead(atoi(optarg));
1040 if ((pid = atoi(optarg)) <= 0) {
1041 fprintf(stderr, "%s: Invalid process id: %s\n",
1045 if (pid == strace_tracer_pid) {
1046 fprintf(stderr, "%s: I'm sorry, I can't let you do that, Dave.\n", progname);
1049 tcp = alloc_tcb(pid, 0);
1050 tcp->flags |= TCB_ATTACHED;
1055 if (pathtrace_select(optarg)) {
1056 fprintf(stderr, "%s : failed to select path '%s'\n", progname, optarg);
1061 max_strlen = atoi(optarg);
1062 if (max_strlen < 0) {
1064 "%s: invalid -s argument: %s\n",
1073 username = strdup(optarg);
1076 if (putenv(optarg) < 0) {
1077 fprintf(stderr, "%s: out of memory\n",
1088 if ((optind == argc) == !pflag_seen)
1091 if (pflag_seen && daemonized_tracer) {
1093 "%s: -D and -p are mutually exclusive options\n",
1101 if (followfork > 1 && cflag) {
1103 "%s: (-c or -C) and -ff are mutually exclusive options\n",
1108 /* See if they want to run as another user. */
1109 if (username != NULL) {
1110 struct passwd *pent;
1112 if (getuid() != 0 || geteuid() != 0) {
1114 "%s: you must be root to use the -u option\n",
1118 if ((pent = getpwnam(username)) == NULL) {
1119 fprintf(stderr, "%s: cannot find user `%s'\n",
1120 progname, username);
1123 run_uid = pent->pw_uid;
1124 run_gid = pent->pw_gid;
1133 if (test_ptrace_setoptions_followfork() < 0) {
1135 "Test for options supported by PTRACE_SETOPTIONS "
1136 "failed, giving up using this feature.\n");
1137 ptrace_setoptions = 0;
1140 fprintf(stderr, "ptrace_setoptions = %#x\n",
1143 test_ptrace_setoptions_for_all();
1146 /* Check if they want to redirect the output. */
1148 /* See if they want to pipe the output. */
1149 if (outfname[0] == '|' || outfname[0] == '!') {
1151 * We can't do the <outfname>.PID funny business
1152 * when using popen, so prohibit it.
1154 if (followfork > 1) {
1156 %s: piping the output and -ff are mutually exclusive options\n",
1161 if ((outf = strace_popen(outfname + 1)) == NULL)
1164 else if (followfork <= 1 &&
1165 (outf = strace_fopen(outfname, "w")) == NULL)
1169 if (!outfname || outfname[0] == '|' || outfname[0] == '!')
1170 setvbuf(outf, buf, _IOLBF, BUFSIZ);
1171 if (outfname && optind < argc) {
1176 /* Valid states here:
1177 optind < argc pflag_seen outfname interactive
1184 /* STARTUP_CHILD must be called before the signal handlers get
1185 installed below as they are inherited into the spawned process.
1186 Also we do not need to be protected by them as during interruption
1187 in the STARTUP_CHILD mode we kill the spawned process anyway. */
1189 startup_child(&argv[optind]);
1191 sigemptyset(&empty_set);
1192 sigemptyset(&blocked_set);
1193 sa.sa_handler = SIG_IGN;
1194 sigemptyset(&sa.sa_mask);
1196 sigaction(SIGTTOU, &sa, NULL);
1197 sigaction(SIGTTIN, &sa, NULL);
1199 sigaddset(&blocked_set, SIGHUP);
1200 sigaddset(&blocked_set, SIGINT);
1201 sigaddset(&blocked_set, SIGQUIT);
1202 sigaddset(&blocked_set, SIGPIPE);
1203 sigaddset(&blocked_set, SIGTERM);
1204 sa.sa_handler = interrupt;
1206 /* POSIX signals on sunos4.1 are a little broken. */
1207 sa.sa_flags = SA_INTERRUPT;
1210 sigaction(SIGHUP, &sa, NULL);
1211 sigaction(SIGINT, &sa, NULL);
1212 sigaction(SIGQUIT, &sa, NULL);
1213 sigaction(SIGPIPE, &sa, NULL);
1214 sigaction(SIGTERM, &sa, NULL);
1216 sa.sa_handler = reaper;
1217 sigaction(SIGCHLD, &sa, NULL);
1219 /* Make sure SIGCHLD has the default action so that waitpid
1220 definitely works without losing track of children. The user
1221 should not have given us a bogus state to inherit, but he might
1222 have. Arguably we should detect SIG_IGN here and pass it on
1223 to children, but probably noone really needs that. */
1224 sa.sa_handler = SIG_DFL;
1225 sigaction(SIGCHLD, &sa, NULL);
1226 #endif /* USE_PROCFS */
1228 if (pflag_seen || daemonized_tracer)
1235 if (exit_code > 0xff) {
1236 /* Child was killed by a signal, mimic that. */
1238 signal(exit_code, SIG_DFL);
1240 /* Paranoia - what if this signal is not fatal?
1241 Exit with 128 + signo then. */
1250 /* Allocate some more TCBs and expand the table.
1251 We don't want to relocate the TCBs because our
1252 callers have pointers and it would be a pain.
1253 So tcbtab is a table of pointers. Since we never
1254 free the TCBs, we allocate a single chunk of many. */
1255 struct tcb **newtab = (struct tcb **)
1256 realloc(tcbtab, 2 * tcbtabsize * sizeof tcbtab[0]);
1257 struct tcb *newtcbs = (struct tcb *) calloc(tcbtabsize,
1260 if (newtab == NULL || newtcbs == NULL) {
1261 fprintf(stderr, "%s: expand_tcbtab: out of memory\n",
1266 for (i = tcbtabsize; i < 2 * tcbtabsize; ++i)
1267 newtab[i] = &newtcbs[i - tcbtabsize];
1273 alloc_tcb(int pid, int command_options_parsed)
1278 if (nprocs == tcbtabsize)
1281 for (i = 0; i < tcbtabsize; i++) {
1283 if ((tcp->flags & TCB_INUSE) == 0) {
1286 #ifdef TCB_CLONE_THREAD
1287 tcp->nclone_threads = 0;
1289 tcp->flags = TCB_INUSE | TCB_STARTUP;
1290 tcp->outf = outf; /* Initialise to current out file */
1292 tcp->stime.tv_sec = 0;
1293 tcp->stime.tv_usec = 0;
1296 if (command_options_parsed)
1301 fprintf(stderr, "%s: bug in alloc_tcb\n", progname);
1308 proc_open(struct tcb *tcp, int attaching)
1318 #ifndef HAVE_POLLABLE_PROCFS
1319 static int last_pfd;
1322 #ifdef HAVE_MP_PROCFS
1323 /* Open the process pseudo-files in /proc. */
1324 sprintf(proc, "/proc/%d/ctl", tcp->pid);
1325 if ((tcp->pfd = open(proc, O_WRONLY|O_EXCL)) < 0) {
1326 perror("strace: open(\"/proc/...\", ...)");
1329 if (set_cloexec_flag(tcp->pfd) < 0) {
1332 sprintf(proc, "/proc/%d/status", tcp->pid);
1333 if ((tcp->pfd_stat = open(proc, O_RDONLY|O_EXCL)) < 0) {
1334 perror("strace: open(\"/proc/...\", ...)");
1337 if (set_cloexec_flag(tcp->pfd_stat) < 0) {
1340 sprintf(proc, "/proc/%d/as", tcp->pid);
1341 if ((tcp->pfd_as = open(proc, O_RDONLY|O_EXCL)) < 0) {
1342 perror("strace: open(\"/proc/...\", ...)");
1345 if (set_cloexec_flag(tcp->pfd_as) < 0) {
1349 /* Open the process pseudo-file in /proc. */
1351 sprintf(proc, "/proc/%d", tcp->pid);
1352 tcp->pfd = open(proc, O_RDWR|O_EXCL);
1354 sprintf(proc, "/proc/%d/mem", tcp->pid);
1355 tcp->pfd = open(proc, O_RDWR);
1356 #endif /* FREEBSD */
1358 perror("strace: open(\"/proc/...\", ...)");
1361 if (set_cloexec_flag(tcp->pfd) < 0) {
1366 sprintf(proc, "/proc/%d/regs", tcp->pid);
1367 if ((tcp->pfd_reg = open(proc, O_RDONLY)) < 0) {
1368 perror("strace: open(\"/proc/.../regs\", ...)");
1372 sprintf(proc, "/proc/%d/status", tcp->pid);
1373 if ((tcp->pfd_status = open(proc, O_RDONLY)) < 0) {
1374 perror("strace: open(\"/proc/.../status\", ...)");
1378 tcp->pfd_status = -1;
1379 #endif /* FREEBSD */
1383 * Wait for the child to pause. Because of a race
1384 * condition we have to poll for the event.
1387 if (IOCTL_STATUS(tcp) < 0) {
1388 perror("strace: PIOCSTATUS");
1391 if (tcp->status.PR_FLAGS & PR_ASLEEP)
1396 /* Stop the process so that we own the stop. */
1397 if (IOCTL(tcp->pfd, PIOCSTOP, (char *)NULL) < 0) {
1398 perror("strace: PIOCSTOP");
1403 /* Set Run-on-Last-Close. */
1405 if (IOCTL(tcp->pfd, PIOCSET, &arg) < 0) {
1406 perror("PIOCSET PR_RLC");
1409 /* Set or Reset Inherit-on-Fork. */
1411 if (IOCTL(tcp->pfd, followfork ? PIOCSET : PIOCRESET, &arg) < 0) {
1412 perror("PIOC{SET,RESET} PR_FORK");
1415 #else /* !PIOCSET */
1417 if (ioctl(tcp->pfd, PIOCSRLC) < 0) {
1421 if (ioctl(tcp->pfd, followfork ? PIOCSFORK : PIOCRFORK) < 0) {
1422 perror("PIOC{S,R}FORK");
1426 /* just unset the PF_LINGER flag for the Run-on-Last-Close. */
1427 if (ioctl(tcp->pfd, PIOCGFL, &arg) < 0) {
1432 if (ioctl(tcp->pfd, PIOCSFL, arg) < 0) {
1436 #endif /* FREEBSD */
1437 #endif /* !PIOCSET */
1439 /* Enable all syscall entries we care about. */
1440 premptyset(&syscalls);
1441 for (i = 1; i < MAX_QUALS; ++i) {
1442 if (i > (sizeof syscalls) * CHAR_BIT) break;
1443 if (qual_flags[i] & QUAL_TRACE) praddset(&syscalls, i);
1445 praddset(&syscalls, SYS_execve);
1447 praddset(&syscalls, SYS_fork);
1449 praddset(&syscalls, SYS_forkall);
1452 praddset(&syscalls, SYS_fork1);
1455 praddset(&syscalls, SYS_rfork1);
1458 praddset(&syscalls, SYS_rforkall);
1461 if (IOCTL(tcp->pfd, PIOCSENTRY, &syscalls) < 0) {
1462 perror("PIOCSENTRY");
1465 /* Enable the syscall exits. */
1466 if (IOCTL(tcp->pfd, PIOCSEXIT, &syscalls) < 0) {
1470 /* Enable signals we care about. */
1471 premptyset(&signals);
1472 for (i = 1; i < MAX_QUALS; ++i) {
1473 if (i > (sizeof signals) * CHAR_BIT) break;
1474 if (qual_flags[i] & QUAL_SIGNAL) praddset(&signals, i);
1476 if (IOCTL(tcp->pfd, PIOCSTRACE, &signals) < 0) {
1477 perror("PIOCSTRACE");
1480 /* Enable faults we care about */
1481 premptyset(&faults);
1482 for (i = 1; i < MAX_QUALS; ++i) {
1483 if (i > (sizeof faults) * CHAR_BIT) break;
1484 if (qual_flags[i] & QUAL_FAULT) praddset(&faults, i);
1486 if (IOCTL(tcp->pfd, PIOCSFAULT, &faults) < 0) {
1487 perror("PIOCSFAULT");
1491 /* set events flags. */
1492 arg = S_SIG | S_SCE | S_SCX;
1493 if (ioctl(tcp->pfd, PIOCBIS, arg) < 0) {
1497 #endif /* FREEBSD */
1501 * The SGI PRSABORT doesn't work for pause() so
1502 * we send it a caught signal to wake it up.
1504 kill(tcp->pid, SIGINT);
1507 /* The child is in a pause(), abort it. */
1509 if (IOCTL(tcp->pfd, PIOCRUN, &arg) < 0) {
1516 /* wake up the child if it received the SIGSTOP */
1517 kill(tcp->pid, SIGCONT);
1520 /* Wait for the child to do something. */
1521 if (IOCTL_WSTOP(tcp) < 0) {
1522 perror("PIOCWSTOP");
1525 if (tcp->status.PR_WHY == PR_SYSENTRY) {
1526 tcp->flags &= ~TCB_INSYSCALL;
1528 if (known_scno(tcp) == SYS_execve)
1531 /* Set it running: maybe execve will be next. */
1534 if (IOCTL(tcp->pfd, PIOCRUN, &arg) < 0) {
1536 if (IOCTL(tcp->pfd, PIOCRUN, 0) < 0) {
1537 #endif /* FREEBSD */
1542 /* handle the case where we "opened" the child before
1543 it did the kill -STOP */
1544 if (tcp->status.PR_WHY == PR_SIGNALLED &&
1545 tcp->status.PR_WHAT == SIGSTOP)
1546 kill(tcp->pid, SIGCONT);
1553 if (attaching < 2) {
1554 /* We are attaching to an already running process.
1555 * Try to figure out the state of the process in syscalls,
1556 * to handle the first event well.
1557 * This is done by having a look at the "wchan" property of the
1558 * process, which tells where it is stopped (if it is). */
1560 char wchan[20]; /* should be enough */
1562 sprintf(proc, "/proc/%d/status", tcp->pid);
1563 status = fopen(proc, "r");
1565 (fscanf(status, "%*s %*d %*d %*d %*d %*d,%*d %*s %*d,%*d"
1566 "%*d,%*d %*d,%*d %19s", wchan) == 1) &&
1567 strcmp(wchan, "nochan") && strcmp(wchan, "spread") &&
1568 strcmp(wchan, "stopevent")) {
1569 /* The process is asleep in the middle of a syscall.
1570 Fake the syscall entry event */
1571 tcp->flags &= ~(TCB_INSYSCALL|TCB_STARTUP);
1572 tcp->status.PR_WHY = PR_SYSENTRY;
1577 } /* otherwise it's a fork being followed */
1579 #endif /* FREEBSD */
1580 #ifndef HAVE_POLLABLE_PROCFS
1581 if (proc_poll_pipe[0] != -1)
1582 proc_poller(tcp->pfd);
1583 else if (nprocs > 1) {
1585 proc_poller(last_pfd);
1586 proc_poller(tcp->pfd);
1588 last_pfd = tcp->pfd;
1589 #endif /* !HAVE_POLLABLE_PROCFS */
1593 #endif /* USE_PROCFS */
1603 for (i = 0; i < tcbtabsize; i++) {
1604 struct tcb *tcp = tcbtab[i];
1605 if (tcp->pid == pid && (tcp->flags & TCB_INUSE))
1615 first_used_tcb(void)
1619 for (i = 0; i < tcbtabsize; i++) {
1621 if (tcp->flags & TCB_INUSE)
1632 for (i = 0; i < tcbtabsize; i++) {
1633 struct tcb *tcp = tcbtab[i];
1634 if (tcp->pfd != pfd)
1636 if (tcp->flags & TCB_INUSE)
1642 #endif /* USE_PROCFS */
1645 droptcb(struct tcb *tcp)
1649 #ifdef TCB_CLONE_THREAD
1650 if (tcp->nclone_threads > 0) {
1651 /* There are other threads left in this process, but this
1652 is the one whose PID represents the whole process.
1653 We need to keep this record around as a zombie until
1654 all the threads die. */
1655 tcp->flags |= TCB_EXITING;
1662 if (tcp->parent != NULL) {
1663 #ifdef TCB_CLONE_THREAD
1664 if (tcp->flags & TCB_CLONE_THREAD)
1665 tcp->parent->nclone_threads--;
1668 /* Update fields like NCLONE_DETACHED, only
1669 for zombie group leader that has already reported
1670 and been short-circuited at the top of this
1671 function. The same condition as at the top of DETACH. */
1672 if ((tcp->flags & TCB_CLONE_THREAD) &&
1673 tcp->parent->nclone_threads == 0 &&
1674 (tcp->parent->flags & TCB_EXITING))
1675 droptcb(tcp->parent);
1681 if (tcp->pfd != -1) {
1685 if (tcp->pfd_reg != -1) {
1686 close(tcp->pfd_reg);
1689 if (tcp->pfd_status != -1) {
1690 close(tcp->pfd_status);
1691 tcp->pfd_status = -1;
1693 #endif /* !FREEBSD */
1695 rebuild_pollv(); /* Note, flags needs to be cleared by now. */
1699 if (outfname && followfork > 1 && tcp->outf)
1705 /* detach traced process; continue with sig
1706 Never call DETACH twice on the same process as both unattached and
1707 attached-unstopped processes give the same ESRCH. For unattached process we
1708 would SIGSTOP it and wait for its SIGSTOP notification forever. */
1711 detach(struct tcb *tcp, int sig)
1715 int status, catch_sigstop;
1716 struct tcb *zombie = NULL;
1718 /* If the group leader is lingering only because of this other
1719 thread now dying, then detach the leader as well. */
1720 if ((tcp->flags & TCB_CLONE_THREAD) &&
1721 tcp->parent->nclone_threads == 1 &&
1722 (tcp->parent->flags & TCB_EXITING))
1723 zombie = tcp->parent;
1726 if (tcp->flags & TCB_BPTSET)
1731 * Linux wrongly insists the child be stopped
1732 * before detaching. Arghh. We go through hoops
1733 * to make a clean break of things.
1736 #undef PTRACE_DETACH
1737 #define PTRACE_DETACH PTRACE_SUNDETACH
1740 * On TCB_STARTUP we did PTRACE_ATTACH but still did not get the
1741 * expected SIGSTOP. We must catch exactly one as otherwise the
1742 * detached process would be left stopped (process state T).
1744 catch_sigstop = (tcp->flags & TCB_STARTUP);
1745 if ((error = ptrace(PTRACE_DETACH, tcp->pid, (char *) 1, sig)) == 0) {
1746 /* On a clear day, you can see forever. */
1748 else if (errno != ESRCH) {
1749 /* Shouldn't happen. */
1750 perror("detach: ptrace(PTRACE_DETACH, ...)");
1752 else if (my_tgkill((tcp->flags & TCB_CLONE_THREAD ? tcp->parent->pid
1756 perror("detach: checking sanity");
1758 else if (!catch_sigstop && my_tgkill((tcp->flags & TCB_CLONE_THREAD
1759 ? tcp->parent->pid : tcp->pid),
1760 tcp->pid, SIGSTOP) < 0) {
1762 perror("detach: stopping child");
1766 if (catch_sigstop) {
1769 if (wait4(tcp->pid, &status, __WALL, NULL) < 0) {
1770 if (errno == ECHILD) /* Already gone. */
1772 if (errno != EINVAL) {
1773 perror("detach: waiting");
1777 /* No __WALL here. */
1778 if (waitpid(tcp->pid, &status, 0) < 0) {
1779 if (errno != ECHILD) {
1780 perror("detach: waiting");
1784 /* If no processes, try clones. */
1785 if (wait4(tcp->pid, &status, __WCLONE,
1787 if (errno != ECHILD)
1788 perror("detach: waiting");
1791 #endif /* __WCLONE */
1796 if (!WIFSTOPPED(status)) {
1797 /* Au revoir, mon ami. */
1800 if (WSTOPSIG(status) == SIGSTOP) {
1801 ptrace_restart(PTRACE_DETACH, tcp, sig);
1804 error = ptrace_restart(PTRACE_CONT, tcp,
1805 WSTOPSIG(status) == syscall_trap_sig ? 0
1806 : WSTOPSIG(status));
1814 /* PTRACE_DETACH won't respect `sig' argument, so we post it here. */
1815 if (sig && kill(tcp->pid, sig) < 0)
1816 perror("detach: kill");
1818 error = ptrace_restart(PTRACE_DETACH, tcp, sig);
1822 fprintf(stderr, "Process %u detached\n", tcp->pid);
1827 if (zombie != NULL) {
1828 /* TCP no longer exists therefore you must not detach() it. */
1838 static void reaper(int sig)
1843 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
1847 #endif /* USE_PROCFS */
1855 for (i = 0; i < tcbtabsize; i++) {
1857 if (!(tcp->flags & TCB_INUSE))
1861 "cleanup: looking at pid %u\n", tcp->pid);
1863 (!outfname || followfork < 2 || tcp_last == tcp)) {
1864 tprintf(" <unfinished ...>");
1867 if (tcp->flags & TCB_ATTACHED)
1870 kill(tcp->pid, SIGCONT);
1871 kill(tcp->pid, SIGTERM);
1884 #ifndef HAVE_STRERROR
1886 #if !HAVE_DECL_SYS_ERRLIST
1887 extern int sys_nerr;
1888 extern char *sys_errlist[];
1889 #endif /* HAVE_DECL_SYS_ERRLIST */
1892 strerror(int err_no)
1894 static char buf[64];
1896 if (err_no < 1 || err_no >= sys_nerr) {
1897 sprintf(buf, "Unknown error %d", err_no);
1900 return sys_errlist[err_no];
1903 #endif /* HAVE_STERRROR */
1905 #ifndef HAVE_STRSIGNAL
1907 #if defined HAVE_SYS_SIGLIST && !defined HAVE_DECL_SYS_SIGLIST
1908 extern char *sys_siglist[];
1910 #if defined HAVE_SYS__SIGLIST && !defined HAVE_DECL__SYS_SIGLIST
1911 extern char *_sys_siglist[];
1917 static char buf[64];
1919 if (sig < 1 || sig >= NSIG) {
1920 sprintf(buf, "Unknown signal %d", sig);
1923 #ifdef HAVE__SYS_SIGLIST
1924 return _sys_siglist[sig];
1926 return sys_siglist[sig];
1930 #endif /* HAVE_STRSIGNAL */
1941 pollv = (struct pollfd *) malloc(nprocs * sizeof pollv[0]);
1942 if (pollv == NULL) {
1943 fprintf(stderr, "%s: out of memory\n", progname);
1947 for (i = j = 0; i < tcbtabsize; i++) {
1948 struct tcb *tcp = tcbtab[i];
1949 if (!(tcp->flags & TCB_INUSE))
1951 pollv[j].fd = tcp->pfd;
1952 pollv[j].events = POLLWANT;
1956 fprintf(stderr, "strace: proc miscount\n");
1961 #ifndef HAVE_POLLABLE_PROCFS
1964 proc_poll_open(void)
1968 if (pipe(proc_poll_pipe) < 0) {
1972 for (i = 0; i < 2; i++) {
1973 if (set_cloexec_flag(proc_poll_pipe[i]) < 0) {
1980 proc_poll(struct pollfd *pollv, int nfds, int timeout)
1984 struct proc_pollfd pollinfo;
1986 if ((n = read(proc_poll_pipe[0], &pollinfo, sizeof(pollinfo))) < 0)
1988 if (n != sizeof(struct proc_pollfd)) {
1989 fprintf(stderr, "panic: short read: %d\n", n);
1992 for (i = 0; i < nprocs; i++) {
1993 if (pollv[i].fd == pollinfo.fd)
1994 pollv[i].revents = pollinfo.revents;
1996 pollv[i].revents = 0;
1998 poller_pid = pollinfo.pid;
2003 wakeup_handler(int sig)
2008 proc_poller(int pfd)
2010 struct proc_pollfd pollinfo;
2011 struct sigaction sa;
2012 sigset_t blocked_set, empty_set;
2017 struct procfs_status pfs;
2018 #endif /* FREEBSD */
2030 sa.sa_handler = interactive ? SIG_DFL : SIG_IGN;
2032 sigemptyset(&sa.sa_mask);
2033 sigaction(SIGHUP, &sa, NULL);
2034 sigaction(SIGINT, &sa, NULL);
2035 sigaction(SIGQUIT, &sa, NULL);
2036 sigaction(SIGPIPE, &sa, NULL);
2037 sigaction(SIGTERM, &sa, NULL);
2038 sa.sa_handler = wakeup_handler;
2039 sigaction(SIGUSR1, &sa, NULL);
2040 sigemptyset(&blocked_set);
2041 sigaddset(&blocked_set, SIGUSR1);
2042 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
2043 sigemptyset(&empty_set);
2045 if (getrlimit(RLIMIT_NOFILE, &rl) < 0) {
2046 perror("getrlimit(RLIMIT_NOFILE, ...)");
2050 for (i = 0; i < n; i++) {
2051 if (i != pfd && i != proc_poll_pipe[1])
2056 pollinfo.pid = getpid();
2059 if (ioctl(pfd, PIOCWSTOP, NULL) < 0)
2061 if (ioctl(pfd, PIOCWSTOP, &pfs) < 0)
2068 pollinfo.revents = POLLERR;
2071 pollinfo.revents = POLLHUP;
2074 perror("proc_poller: PIOCWSTOP");
2076 write(proc_poll_pipe[1], &pollinfo, sizeof(pollinfo));
2079 pollinfo.revents = POLLWANT;
2080 write(proc_poll_pipe[1], &pollinfo, sizeof(pollinfo));
2081 sigsuspend(&empty_set);
2085 #endif /* !HAVE_POLLABLE_PROCFS */
2095 if (followfork < 2 &&
2096 last < nprocs && (pollv[last].revents & POLLWANT)) {
2098 * The previous process is ready to run again. We'll
2099 * let it do so if it is currently in a syscall. This
2100 * heuristic improves the readability of the trace.
2102 tcp = pfd2tcb(pollv[last].fd);
2103 if (tcp && (tcp->flags & TCB_INSYSCALL))
2104 return pollv[last].fd;
2107 for (i = 0; i < nprocs; i++) {
2108 /* Let competing children run round robin. */
2109 j = (i + last + 1) % nprocs;
2110 if (pollv[j].revents & (POLLHUP | POLLERR)) {
2111 tcp = pfd2tcb(pollv[j].fd);
2113 fprintf(stderr, "strace: lost proc\n");
2119 if (pollv[j].revents & POLLWANT) {
2124 fprintf(stderr, "strace: nothing ready\n");
2132 struct tcb *in_syscall = NULL;
2137 int ioctl_result = 0, ioctl_errno = 0;
2142 sigprocmask(SIG_SETMASK, &empty_set, NULL);
2149 #ifndef HAVE_POLLABLE_PROCFS
2150 if (proc_poll_pipe[0] == -1) {
2152 tcp = first_used_tcb();
2159 #ifndef HAVE_POLLABLE_PROCFS
2161 /* fall through ... */
2162 #endif /* !HAVE_POLLABLE_PROCFS */
2164 #ifdef HAVE_POLLABLE_PROCFS
2166 /* On some systems (e.g. UnixWare) we get too much ugly
2167 "unfinished..." stuff when multiple proceses are in
2168 syscalls. Here's a nasty hack */
2175 pv.events = POLLWANT;
2176 if ((what = poll(&pv, 1, 1)) < 0) {
2181 else if (what == 1 && pv.revents & POLLWANT) {
2187 if (poll(pollv, nprocs, INFTIM) < 0) {
2192 #else /* !HAVE_POLLABLE_PROCFS */
2193 if (proc_poll(pollv, nprocs, INFTIM) < 0) {
2198 #endif /* !HAVE_POLLABLE_PROCFS */
2205 /* Look up `pfd' in our table. */
2206 if ((tcp = pfd2tcb(pfd)) == NULL) {
2207 fprintf(stderr, "unknown pfd: %u\n", pfd);
2213 /* Get the status of the process. */
2216 ioctl_result = IOCTL_WSTOP(tcp);
2218 /* Thanks to some scheduling mystery, the first poller
2219 sometimes waits for the already processed end of fork
2220 event. Doing a non blocking poll here solves the problem. */
2221 if (proc_poll_pipe[0] != -1)
2222 ioctl_result = IOCTL_STATUS(tcp);
2224 ioctl_result = IOCTL_WSTOP(tcp);
2225 #endif /* FREEBSD */
2226 ioctl_errno = errno;
2227 #ifndef HAVE_POLLABLE_PROCFS
2228 if (proc_poll_pipe[0] != -1) {
2229 if (ioctl_result < 0)
2230 kill(poller_pid, SIGKILL);
2232 kill(poller_pid, SIGUSR1);
2234 #endif /* !HAVE_POLLABLE_PROCFS */
2240 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
2242 if (ioctl_result < 0) {
2243 /* Find out what happened if it failed. */
2244 switch (ioctl_errno) {
2255 perror("PIOCWSTOP");
2261 if ((tcp->flags & TCB_STARTUP) && (tcp->status.PR_WHY == PR_SYSEXIT)) {
2262 /* discard first event for a syscall we never entered */
2263 IOCTL(tcp->pfd, PIOCRUN, 0);
2268 /* clear the just started flag */
2269 tcp->flags &= ~TCB_STARTUP;
2271 /* set current output file */
2273 curcol = tcp->curcol;
2276 struct timeval stime;
2281 if ((len = pread(tcp->pfd_status, buf, sizeof(buf) - 1, 0)) > 0) {
2284 "%*s %*d %*d %*d %*d %*d,%*d %*s %*d,%*d %*d,%*d %ld,%ld",
2285 &stime.tv_sec, &stime.tv_usec);
2287 stime.tv_sec = stime.tv_usec = 0;
2288 #else /* !FREEBSD */
2289 stime.tv_sec = tcp->status.pr_stime.tv_sec;
2290 stime.tv_usec = tcp->status.pr_stime.tv_nsec/1000;
2291 #endif /* !FREEBSD */
2292 tv_sub(&tcp->dtime, &stime, &tcp->stime);
2295 what = tcp->status.PR_WHAT;
2296 switch (tcp->status.PR_WHY) {
2299 if (tcp->status.PR_FLAGS & PR_ASLEEP) {
2300 tcp->status.PR_WHY = PR_SYSENTRY;
2301 if (trace_syscall(tcp) < 0) {
2302 fprintf(stderr, "syscall trouble\n");
2307 #endif /* !FREEBSD */
2313 if (trace_syscall(tcp) < 0) {
2314 fprintf(stderr, "syscall trouble\n");
2319 if (cflag != CFLAG_ONLY_STATS
2320 && (qual_flags[what] & QUAL_SIGNAL)) {
2322 tprintf("--- %s (%s) ---",
2323 signame(what), strsignal(what));
2326 if (tcp->status.PR_INFO.si_signo == what) {
2328 tprintf(" siginfo=");
2329 printsiginfo(&tcp->status.PR_INFO, 1);
2336 if (cflag != CFLAGS_ONLY_STATS
2337 && (qual_flags[what] & QUAL_FAULT)) {
2339 tprintf("=== FAULT %d ===", what);
2344 case 0: /* handle case we polled for nothing */
2348 fprintf(stderr, "odd stop %d\n", tcp->status.PR_WHY);
2352 /* Remember current print column before continuing. */
2353 tcp->curcol = curcol;
2356 if (IOCTL(tcp->pfd, PIOCRUN, &arg) < 0)
2358 if (IOCTL(tcp->pfd, PIOCRUN, 0) < 0)
2368 #else /* !USE_PROCFS */
2370 #ifdef TCB_GROUP_EXITING
2371 /* Handle an exit detach or death signal that is taking all the
2372 related clone threads with it. This is called in three circumstances:
2373 SIG == -1 TCP has already died (TCB_ATTACHED is clear, strace is parent).
2374 SIG == 0 Continuing TCP will perform an exit_group syscall.
2375 SIG == other Continuing TCP with SIG will kill the process.
2378 handle_group_exit(struct tcb *tcp, int sig)
2380 /* We need to locate our records of all the clone threads
2381 related to TCP, either its children or siblings. */
2382 struct tcb *leader = NULL;
2384 if (tcp->flags & TCB_CLONE_THREAD)
2385 leader = tcp->parent;
2388 if (leader != NULL && leader != tcp
2389 && !(leader->flags & TCB_GROUP_EXITING)
2390 && !(tcp->flags & TCB_STARTUP)
2393 "PANIC: handle_group_exit: %d leader %d\n",
2394 tcp->pid, leader ? leader->pid : -1);
2396 /* TCP no longer exists therefore you must not detach() it. */
2397 droptcb(tcp); /* Already died. */
2400 /* Mark that we are taking the process down. */
2401 tcp->flags |= TCB_EXITING | TCB_GROUP_EXITING;
2402 if (tcp->flags & TCB_ATTACHED) {
2404 if (leader != NULL && leader != tcp)
2405 leader->flags |= TCB_GROUP_EXITING;
2407 if (ptrace_restart(PTRACE_CONT, tcp, sig) < 0) {
2411 if (leader != NULL) {
2412 leader->flags |= TCB_GROUP_EXITING;
2416 /* The leader will report to us as parent now,
2417 and then we'll get to the SIG==-1 case. */
2428 handle_ptrace_event(int status, struct tcb *tcp)
2430 if (status >> 16 == PTRACE_EVENT_VFORK ||
2431 status >> 16 == PTRACE_EVENT_CLONE ||
2432 status >> 16 == PTRACE_EVENT_FORK) {
2435 if (do_ptrace(PTRACE_GETEVENTMSG, tcp, NULL, &childpid) < 0) {
2436 if (errno != ESRCH) {
2438 %s: handle_ptrace_event: ptrace cannot get new child's pid\n",
2445 return handle_new_child(tcp, childpid, 0);
2447 if (status >> 16 == PTRACE_EVENT_EXEC) {
2449 fprintf(stderr, "PTRACE_EVENT_EXEC on pid %d (ignored)\n", tcp->pid);
2452 /* Some PTRACE_EVENT_foo we didn't ask for?! */
2453 error_msg("Unexpected status %x on pid %d", status, tcp->pid);
2468 static int wait4_options = __WALL;
2472 while (nprocs != 0) {
2476 sigprocmask(SIG_SETMASK, &empty_set, NULL);
2479 pid = wait4(-1, &status, wait4_options, cflag ? &ru : NULL);
2480 if (pid < 0 && (wait4_options & __WALL) && errno == EINVAL) {
2481 /* this kernel does not support __WALL */
2482 wait4_options &= ~__WALL;
2484 pid = wait4(-1, &status, wait4_options,
2485 cflag ? &ru : NULL);
2487 if (pid < 0 && !(wait4_options & __WALL) && errno == ECHILD) {
2488 /* most likely a "cloned" process */
2489 pid = wait4(-1, &status, __WCLONE,
2490 cflag ? &ru : NULL);
2492 fprintf(stderr, "strace: clone wait4 "
2493 "failed: %s\n", strerror(errno));
2497 pid = wait4(-1, &status, 0, cflag ? &ru : NULL);
2501 pid = wait(&status);
2505 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
2508 switch (wait_errno) {
2513 * We would like to verify this case
2514 * but sometimes a race in Solbourne's
2515 * version of SunOS sometimes reports
2516 * ECHILD before sending us SIGCHILD.
2521 perror("strace: wait");
2525 if (pid == popen_pid) {
2526 if (WIFEXITED(status) || WIFSIGNALED(status))
2531 fprintf(stderr, " [wait(%#x) = %u]\n", status, pid);
2533 /* Look up `pid' in our table. */
2534 if ((tcp = pid2tcb(pid)) == NULL) {
2537 /* This is needed to go with the CLONE_PTRACE
2538 changes in process.c/util.c: we might see
2539 the child's initial trap before we see the
2540 parent return from the clone syscall.
2541 Leave the child suspended until the parent
2542 returns from its system call. Only then
2543 will we have the association of parent and
2544 child so that we know how to do clearbpt
2546 tcp = alloctcb(pid);
2547 tcp->flags |= TCB_ATTACHED | TCB_SUSPENDED;
2550 Process %d attached (waiting for parent)\n",
2554 /* This can happen if a clone call used
2555 CLONE_PTRACE itself. */
2558 fprintf(stderr, "unknown pid: %u\n", pid);
2559 if (WIFSTOPPED(status))
2560 ptrace(PTRACE_CONT, pid, (char *) 1, 0);
2564 /* set current output file */
2566 curcol = tcp->curcol;
2569 tv_sub(&tcp->dtime, &ru.ru_stime, &tcp->stime);
2570 tcp->stime = ru.ru_stime;
2574 if (tcp->flags & TCB_SUSPENDED) {
2576 * Apparently, doing any ptrace() call on a stopped
2577 * process, provokes the kernel to report the process
2578 * status again on a subsequent wait(), even if the
2579 * process has not been actually restarted.
2580 * Since we have inspected the arguments of suspended
2581 * processes we end up here testing for this case.
2585 if (WIFSIGNALED(status)) {
2586 if (pid == strace_child)
2587 exit_code = 0x100 | WTERMSIG(status);
2588 if (cflag != CFLAG_ONLY_STATS
2589 && (qual_flags[WTERMSIG(status)] & QUAL_SIGNAL)) {
2591 tprintf("+++ killed by %s %s+++",
2592 signame(WTERMSIG(status)),
2594 WCOREDUMP(status) ? "(core dumped) " :
2599 #ifdef TCB_GROUP_EXITING
2600 handle_group_exit(tcp, -1);
2606 if (WIFEXITED(status)) {
2607 if (pid == strace_child)
2608 exit_code = WEXITSTATUS(status);
2610 fprintf(stderr, "pid %u exited with %d\n", pid, WEXITSTATUS(status));
2611 if ((tcp->flags & (TCB_ATTACHED|TCB_STARTUP)) == TCB_ATTACHED
2612 #ifdef TCB_GROUP_EXITING
2613 && !(tcp->parent && (tcp->parent->flags & TCB_GROUP_EXITING))
2614 && !(tcp->flags & TCB_GROUP_EXITING)
2618 "PANIC: attached pid %u exited with %d\n",
2619 pid, WEXITSTATUS(status));
2621 if (tcp == tcp_last) {
2622 if ((tcp->flags & (TCB_INSYSCALL|TCB_REPRINT)) == TCB_INSYSCALL)
2623 tprintf(" <unfinished ... exit status %d>\n",
2624 WEXITSTATUS(status));
2627 #ifdef TCB_GROUP_EXITING
2628 handle_group_exit(tcp, -1);
2634 if (!WIFSTOPPED(status)) {
2635 fprintf(stderr, "PANIC: pid %u not stopped\n", pid);
2640 fprintf(stderr, "pid %u stopped, [%s]\n",
2641 pid, signame(WSTOPSIG(status)));
2644 if (handle_ptrace_event(status, tcp) != 1)
2649 * Interestingly, the process may stop
2650 * with STOPSIG equal to some other signal
2651 * than SIGSTOP if we happend to attach
2652 * just before the process takes a signal.
2653 * A no-MMU vforked child won't send up a signal,
2654 * so skip the first (lost) execve notification.
2656 if ((tcp->flags & TCB_STARTUP) &&
2657 (WSTOPSIG(status) == SIGSTOP || strace_vforked)) {
2659 * This flag is there to keep us in sync.
2660 * Next time this process stops it should
2661 * really be entering a system call.
2663 tcp->flags &= ~TCB_STARTUP;
2664 if (tcp->flags & TCB_BPTSET) {
2666 * One example is a breakpoint inherited from
2667 * parent through fork ().
2669 if (clearbpt(tcp) < 0) /* Pretty fatal */ {
2676 /* If options were not set for this tracee yet */
2677 if (tcp->parent == NULL) {
2678 if (ptrace_setoptions) {
2680 fprintf(stderr, "setting opts %x on pid %d\n", ptrace_setoptions, tcp->pid);
2681 if (ptrace(PTRACE_SETOPTIONS, tcp->pid, NULL, ptrace_setoptions) < 0) {
2682 if (errno != ESRCH) {
2683 /* Should never happen, really */
2684 perror_msg_and_die("PTRACE_SETOPTIONS");
2693 if (WSTOPSIG(status) != syscall_trap_sig) {
2694 if (WSTOPSIG(status) == SIGSTOP &&
2695 (tcp->flags & TCB_SIGTRAPPED)) {
2697 * Trapped attempt to block SIGTRAP
2698 * Hope we are back in control now.
2700 tcp->flags &= ~(TCB_INSYSCALL | TCB_SIGTRAPPED);
2701 if (ptrace_restart(PTRACE_SYSCALL, tcp, 0) < 0) {
2707 if (cflag != CFLAG_ONLY_STATS
2708 && (qual_flags[WSTOPSIG(status)] & QUAL_SIGNAL)) {
2710 #if defined(PT_CR_IPSR) && defined(PT_CR_IIP)
2714 upeek(tcp, PT_CR_IPSR, &psr);
2715 upeek(tcp, PT_CR_IIP, &pc);
2718 pc += (psr >> PSR_RI) & 0x3;
2719 # define PC_FORMAT_STR " @ %lx"
2720 # define PC_FORMAT_ARG pc
2722 # define PC_FORMAT_STR "%s"
2723 # define PC_FORMAT_ARG ""
2726 if (ptrace(PTRACE_GETSIGINFO, pid, 0, &si) == 0) {
2728 printsiginfo(&si, verbose(tcp));
2729 tprintf(" (%s)" PC_FORMAT_STR " ---",
2730 strsignal(WSTOPSIG(status)),
2733 tprintf("--- %s by %s" PC_FORMAT_STR " ---",
2734 strsignal(WSTOPSIG(status)),
2735 signame(WSTOPSIG(status)),
2739 if (((tcp->flags & TCB_ATTACHED) ||
2740 tcp->nclone_threads > 0) &&
2741 !sigishandled(tcp, WSTOPSIG(status))) {
2742 #ifdef TCB_GROUP_EXITING
2743 handle_group_exit(tcp, WSTOPSIG(status));
2745 detach(tcp, WSTOPSIG(status));
2749 if (ptrace_restart(PTRACE_SYSCALL, tcp, WSTOPSIG(status)) < 0) {
2753 tcp->flags &= ~TCB_SUSPENDED;
2756 /* we handled the STATUS, we are permitted to interrupt now. */
2759 if (trace_syscall(tcp) < 0 && !tcp->ptrace_errno) {
2760 /* ptrace() failed in trace_syscall() with ESRCH.
2761 * Likely a result of process disappearing mid-flight.
2762 * Observed case: exit_group() terminating
2763 * all processes in thread group. In this case, threads
2764 * "disappear" in an unpredictable moment without any
2765 * notification to strace via wait().
2767 if (tcp->flags & TCB_ATTACHED) {
2769 /* Do we have dangling line "syscall(param, param"?
2770 * Finish the line then. We cannot
2772 tcp_last->flags |= TCB_REPRINT;
2773 tprintf(" <unfinished ...>");
2779 tcp->pid, (char *) 1, SIGTERM);
2784 if (tcp->flags & TCB_EXITING) {
2785 #ifdef TCB_GROUP_EXITING
2786 if (tcp->flags & TCB_GROUP_EXITING) {
2787 if (handle_group_exit(tcp, 0) < 0)
2792 if (tcp->flags & TCB_ATTACHED)
2794 else if (ptrace_restart(PTRACE_CONT, tcp, 0) < 0) {
2800 if (tcp->flags & TCB_SUSPENDED) {
2802 fprintf(stderr, "Process %u suspended\n", pid);
2806 /* Remember current print column before continuing. */
2807 tcp->curcol = curcol;
2808 if (ptrace_restart(PTRACE_SYSCALL, tcp, 0) < 0) {
2816 #endif /* !USE_PROCFS */
2821 tprintf(const char *fmt, ...)
2825 va_start(args, fmt);
2827 int n = vfprintf(outf, fmt, args);
2830 perror(outfname == NULL
2831 ? "<writing to pipe>" : outfname);
2840 printleader(struct tcb *tcp)
2843 if (tcp_last->ptrace_errno) {
2844 if (tcp_last->flags & TCB_INSYSCALL) {
2845 tprintf(" <unavailable>) ");
2848 tprintf("= ? <unavailable>\n");
2849 tcp_last->ptrace_errno = 0;
2850 } else if (!outfname || followfork < 2 || tcp_last == tcp) {
2851 tcp_last->flags |= TCB_REPRINT;
2852 tprintf(" <unfinished ...>\n");
2856 if ((followfork == 1 || pflag_seen > 1) && outfname)
2857 tprintf("%-5d ", tcp->pid);
2858 else if (nprocs > 1 && !outfname)
2859 tprintf("[pid %5u] ", tcp->pid);
2861 char str[sizeof("HH:MM:SS")];
2862 struct timeval tv, dtv;
2863 static struct timeval otv;
2865 gettimeofday(&tv, NULL);
2867 if (otv.tv_sec == 0)
2869 tv_sub(&dtv, &tv, &otv);
2870 tprintf("%6ld.%06ld ",
2871 (long) dtv.tv_sec, (long) dtv.tv_usec);
2874 else if (tflag > 2) {
2875 tprintf("%ld.%06ld ",
2876 (long) tv.tv_sec, (long) tv.tv_usec);
2879 time_t local = tv.tv_sec;
2880 strftime(str, sizeof(str), "%T", localtime(&local));
2882 tprintf("%s.%06ld ", str, (long) tv.tv_usec);
2884 tprintf("%s ", str);
2895 tprintf("%*s", col - curcol, "");
2905 #ifdef HAVE_MP_PROCFS
2908 mp_ioctl(int fd, int cmd, void *arg, int size)
2910 struct iovec iov[2];
2913 iov[0].iov_base = &cmd;
2914 iov[0].iov_len = sizeof cmd;
2917 iov[1].iov_base = arg;
2918 iov[1].iov_len = size;
2921 return writev(fd, iov, n);