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_followfork = 0;
88 unsigned int ptrace_setoptions_for_all = 0;
89 /* Which WSTOPSIG(status) value marks syscall traps? */
90 static unsigned int syscall_trap_sig = SIGTRAP;
91 int dtime = 0, xflag = 0, qflag = 0;
92 cflag_t cflag = CFLAG_NONE;
93 static int iflag = 0, interactive = 0, pflag_seen = 0, rflag = 0, tflag = 0;
95 * daemonized_tracer supports -D option.
96 * With this option, strace forks twice.
97 * Unlike normal case, with -D *grandparent* process exec's,
98 * becoming a traced process. Child exits (this prevents traced process
99 * from having children it doesn't expect to have), and grandchild
100 * attaches to grandparent similarly to strace -p PID.
101 * This allows for more transparent interaction in cases
102 * when process and its parent are communicating via signals,
103 * wait() etc. Without -D, strace process gets lodged in between,
104 * disrupting parent<->child link.
106 static bool daemonized_tracer = 0;
108 /* Sometimes we want to print only succeeding syscalls. */
109 int not_failing_only = 0;
111 /* Show path associated with fd arguments */
112 int show_fd_path = 0;
114 /* are we filtering traces based on paths? */
115 int tracing_paths = 0;
117 static int exit_code = 0;
118 static int strace_child = 0;
119 static int strace_tracer_pid = 0;
121 static char *username = NULL;
125 int acolumn = DEFAULT_ACOLUMN;
126 int max_strlen = DEFAULT_STRLEN;
127 static char *outfname = NULL;
131 unsigned int nprocs, tcbtabsize;
132 const char *progname;
133 extern char **environ;
135 static int detach(struct tcb *tcp, int sig);
136 static int trace(void);
137 static void cleanup(void);
138 static void interrupt(int sig);
139 static sigset_t empty_set, blocked_set;
141 #ifdef HAVE_SIG_ATOMIC_T
142 static volatile sig_atomic_t interrupted;
143 #else /* !HAVE_SIG_ATOMIC_T */
144 static volatile int interrupted;
145 #endif /* !HAVE_SIG_ATOMIC_T */
149 static struct tcb *pfd2tcb(int pfd);
150 static void reaper(int sig);
151 static void rebuild_pollv(void);
152 static struct pollfd *pollv;
154 #ifndef HAVE_POLLABLE_PROCFS
156 static void proc_poll_open(void);
157 static void proc_poller(int pfd);
165 static int poller_pid;
166 static int proc_poll_pipe[2] = { -1, -1 };
168 #endif /* !HAVE_POLLABLE_PROCFS */
170 #ifdef HAVE_MP_PROCFS
171 #define POLLWANT POLLWRNORM
173 #define POLLWANT POLLPRI
175 #endif /* USE_PROCFS */
183 usage: strace [-CdDffhiqrtttTvVxxy] [-a column] [-e expr] ... [-o file]\n\
184 [-p pid] ... [-s strsize] [-u username] [-E var=val] ...\n\
185 [-P path] [command [arg ...]]\n\
186 or: strace -c [-D] [-e expr] ... [-O overhead] [-S sortby] [-E var=val] ...\n\
187 [command [arg ...]]\n\
188 -c -- count time, calls, and errors for each syscall and report summary\n\
189 -C -- like -c but also print regular output while processes are running\n\
190 -f -- follow forks, -ff -- with output into separate files\n\
191 -F -- attempt to follow vforks, -h -- print help message\n\
192 -i -- print instruction pointer at time of syscall\n\
193 -q -- suppress messages about attaching, detaching, etc.\n\
194 -r -- print relative timestamp, -t -- absolute timestamp, -tt -- with usecs\n\
195 -T -- print time spent in each syscall, -V -- print version\n\
196 -v -- verbose mode: print unabbreviated argv, stat, termio[s], etc. args\n\
197 -x -- print non-ascii strings in hex, -xx -- print all strings in hex\n\
198 -y -- print paths associated with file descriptor arguments\n\
199 -a column -- alignment COLUMN for printing syscall results (default %d)\n\
200 -e expr -- a qualifying expression: option=[!]all or option=[!]val1[,val2]...\n\
201 options: trace, abbrev, verbose, raw, signal, read, or write\n\
202 -o file -- send trace output to FILE instead of stderr\n\
203 -O overhead -- set overhead for tracing syscalls to OVERHEAD usecs\n\
204 -p pid -- trace process with process id PID, may be repeated\n\
205 -D -- run tracer process as a detached grandchild, not as parent\n\
206 -s strsize -- limit length of print strings to STRSIZE chars (default %d)\n\
207 -S sortby -- sort syscall counts by: time, calls, name, nothing (default %s)\n\
208 -u username -- run command as username handling setuid and/or setgid\n\
209 -E var=val -- put var=val in the environment for command\n\
210 -E var -- remove var from the environment for command\n\
211 -P path -- trace accesses to path\n\
212 " /* this is broken, so don't document it
213 -z -- print only succeeding syscalls\n\
215 , DEFAULT_ACOLUMN, DEFAULT_STRLEN, DEFAULT_SORTBY);
219 static void die(void) __attribute__ ((noreturn));
220 static void die(void)
222 if (strace_tracer_pid == getpid()) {
229 static void verror_msg(int err_no, const char *fmt, va_list p)
234 vasprintf(&msg, fmt, p);
238 fprintf(stderr, "%s: %s: %s\n", progname, msg, strerror(err_no));
240 fprintf(stderr, "%s: %s\n", progname, msg);
245 void error_msg(const char *fmt, ...)
249 verror_msg(0, fmt, p);
253 void error_msg_and_die(const char *fmt, ...)
257 verror_msg(0, fmt, p);
261 void perror_msg(const char *fmt, ...)
265 verror_msg(errno, fmt, p);
269 void perror_msg_and_die(const char *fmt, ...)
273 verror_msg(errno, fmt, p);
286 /* Glue for systems without a MMU that cannot provide fork() */
288 # define strace_vforked 0
290 # define strace_vforked 1
291 # define fork() vfork()
295 set_cloexec_flag(int fd)
299 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
301 fprintf(stderr, "%s: fcntl F_GETFD: %s\n",
302 progname, strerror(errno));
306 newflags = flags | FD_CLOEXEC;
307 if (flags == newflags)
310 if (fcntl(fd, F_SETFD, newflags) < 0)
312 fprintf(stderr, "%s: fcntl F_SETFD: %s\n",
313 progname, strerror(errno));
321 * When strace is setuid executable, we have to swap uids
322 * before and after filesystem and process management operations.
328 int euid = geteuid(), uid = getuid();
330 if (euid != uid && setreuid(euid, uid) < 0)
332 fprintf(stderr, "%s: setreuid: %s\n",
333 progname, strerror(errno));
340 # define fopen_for_output fopen64
342 # define fopen_for_output fopen
346 strace_fopen(const char *path, const char *mode)
351 if ((fp = fopen_for_output(path, mode)) == NULL)
352 fprintf(stderr, "%s: can't fopen '%s': %s\n",
353 progname, path, strerror(errno));
355 if (fp && set_cloexec_flag(fileno(fp)) < 0)
363 static int popen_pid = -1;
366 # define _PATH_BSHELL "/bin/sh"
370 * We cannot use standard popen(3) here because we have to distinguish
371 * popen child process from other processes we trace, and standard popen(3)
372 * does not export its child's pid.
375 strace_popen(const char *command)
382 fprintf(stderr, "%s: pipe: %s\n",
383 progname, strerror(errno));
388 if (set_cloexec_flag(fds[1]) < 0)
396 if ((popen_pid = fork()) == -1)
398 fprintf(stderr, "%s: fork: %s\n",
399 progname, strerror(errno));
411 return fdopen(fds[1], "w");
416 if (fds[0] && (dup2(fds[0], 0) || close(fds[0])))
418 fprintf(stderr, "%s: dup2: %s\n",
419 progname, strerror(errno));
422 execl(_PATH_BSHELL, "sh", "-c", command, NULL);
423 fprintf(stderr, "%s: execl: %s: %s\n",
424 progname, _PATH_BSHELL, strerror(errno));
430 newoutf(struct tcb *tcp)
432 if (outfname && followfork > 1) {
433 char name[520 + sizeof(int) * 3];
436 sprintf(name, "%.512s.%u", outfname, tcp->pid);
437 if ((fp = strace_fopen(name, "w")) == NULL)
451 * Block user interruptions as we would leave the traced
452 * process stopped (process state T) if we would terminate in
453 * between PTRACE_ATTACH and wait4 () on SIGSTOP.
454 * We rely on cleanup() from this point on.
457 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
459 if (daemonized_tracer) {
464 if (pid) { /* parent */
466 * Wait for grandchild to attach to straced process
467 * (grandparent). Grandchild SIGKILLs us after it attached.
468 * Grandparent's wait() is unblocked by our death,
469 * it proceeds to exec the straced program.
472 _exit(0); /* paranoia */
475 /* We will be the tracer process. Remember our new pid: */
476 strace_tracer_pid = getpid();
479 for (tcbi = 0; tcbi < tcbtabsize; tcbi++) {
481 if (!(tcp->flags & TCB_INUSE) || !(tcp->flags & TCB_ATTACHED))
484 if (tcp->flags & TCB_CLONE_THREAD)
487 /* Reinitialize the output since it may have changed. */
489 if (newoutf(tcp) < 0)
493 if (proc_open(tcp, 1) < 0) {
494 fprintf(stderr, "trouble opening proc file\n");
498 #else /* !USE_PROCFS */
500 if (followfork && !daemonized_tracer) {
501 char procdir[sizeof("/proc/%d/task") + sizeof(int) * 3];
504 sprintf(procdir, "/proc/%d/task", tcp->pid);
505 dir = opendir(procdir);
507 unsigned int ntid = 0, nerr = 0;
510 while ((de = readdir(dir)) != NULL) {
511 if (de->d_fileno == 0)
513 tid = atoi(de->d_name);
517 if (ptrace(PTRACE_ATTACH, tid, (char *) 1, 0) < 0)
519 else if (tid != tcbtab[tcbi]->pid) {
521 tcp->flags |= TCB_ATTACHED|TCB_CLONE_THREAD|TCB_FOLLOWFORK;
522 tcbtab[tcbi]->nchildren++;
523 tcbtab[tcbi]->nclone_threads++;
524 tcp->parent = tcbtab[tcbi];
527 sigprocmask(SIG_SETMASK, &empty_set, NULL);
530 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
536 perror("attach: ptrace(PTRACE_ATTACH, ...)");
541 fprintf(stderr, ntid > 1
542 ? "Process %u attached with %u threads - interrupt to quit\n"
543 : "Process %u attached - interrupt to quit\n",
544 tcbtab[tcbi]->pid, ntid);
547 } /* if (opendir worked) */
550 if (ptrace(PTRACE_ATTACH, tcp->pid, (char *) 1, 0) < 0) {
551 perror("attach: ptrace(PTRACE_ATTACH, ...)");
555 /* INTERRUPTED is going to be checked at the top of TRACE. */
557 if (daemonized_tracer) {
559 * It is our grandparent we trace, not a -p PID.
560 * Don't want to just detach on exit, so...
562 tcp->flags &= ~TCB_ATTACHED;
564 * Make parent go away.
565 * Also makes grandparent's wait() unblock.
567 kill(getppid(), SIGKILL);
570 #endif /* !USE_PROCFS */
573 "Process %u attached - interrupt to quit\n",
578 sigprocmask(SIG_SETMASK, &empty_set, NULL);
582 startup_child(char **argv)
585 const char *filename;
586 char pathname[MAXPATHLEN];
591 if (strchr(filename, '/')) {
592 if (strlen(filename) > sizeof pathname - 1) {
593 errno = ENAMETOOLONG;
594 perror("strace: exec");
597 strcpy(pathname, filename);
599 #ifdef USE_DEBUGGING_EXEC
601 * Debuggers customarily check the current directory
602 * first regardless of the path but doing that gives
603 * security geeks a panic attack.
605 else if (stat(filename, &statbuf) == 0)
606 strcpy(pathname, filename);
607 #endif /* USE_DEBUGGING_EXEC */
612 for (path = getenv("PATH"); path && *path; path += m) {
613 if (strchr(path, ':')) {
614 n = strchr(path, ':') - path;
618 m = n = strlen(path);
620 if (!getcwd(pathname, MAXPATHLEN))
622 len = strlen(pathname);
624 else if (n > sizeof pathname - 1)
627 strncpy(pathname, path, n);
630 if (len && pathname[len - 1] != '/')
631 pathname[len++] = '/';
632 strcpy(pathname + len, filename);
633 if (stat(pathname, &statbuf) == 0 &&
634 /* Accept only regular files
635 with some execute bits set.
636 XXX not perfect, might still fail */
637 S_ISREG(statbuf.st_mode) &&
638 (statbuf.st_mode & 0111))
642 if (stat(pathname, &statbuf) < 0) {
643 fprintf(stderr, "%s: %s: command not found\n",
647 strace_child = pid = fork();
649 perror("strace: fork");
653 if ((pid != 0 && daemonized_tracer) /* -D: parent to become a traced process */
654 || (pid == 0 && !daemonized_tracer) /* not -D: child to become a traced process */
658 if (outf != stderr) close(fileno(outf));
660 /* Kludge for SGI, see proc_open for details. */
661 sa.sa_handler = foobar;
663 sigemptyset(&sa.sa_mask);
664 sigaction(SIGINT, &sa, NULL);
669 kill(pid, SIGSTOP); /* stop HERE */
671 #else /* !USE_PROCFS */
675 if (!daemonized_tracer) {
676 if (ptrace(PTRACE_TRACEME, 0, (char *) 1, 0) < 0) {
677 perror("strace: ptrace(PTRACE_TRACEME, ...)");
684 if (username != NULL || geteuid() == 0) {
685 uid_t run_euid = run_uid;
686 gid_t run_egid = run_gid;
688 if (statbuf.st_mode & S_ISUID)
689 run_euid = statbuf.st_uid;
690 if (statbuf.st_mode & S_ISGID)
691 run_egid = statbuf.st_gid;
694 * It is important to set groups before we
695 * lose privileges on setuid.
697 if (username != NULL) {
698 if (initgroups(username, run_gid) < 0) {
699 perror("initgroups");
702 if (setregid(run_gid, run_egid) < 0) {
706 if (setreuid(run_uid, run_euid) < 0) {
713 setreuid(run_uid, run_uid);
715 if (!daemonized_tracer) {
717 * Induce an immediate stop so that the parent
718 * will resume us with PTRACE_SYSCALL and display
719 * this execve call normally.
720 * Unless of course we're on a no-MMU system where
721 * we vfork()-ed, so we cannot stop the child.
724 kill(getpid(), SIGSTOP);
726 struct sigaction sv_sigchld;
727 sigaction(SIGCHLD, NULL, &sv_sigchld);
729 * Make sure it is not SIG_IGN, otherwise wait
732 signal(SIGCHLD, SIG_DFL);
734 * Wait for grandchild to attach to us.
735 * It kills child after that, and wait() unblocks.
740 sigaction(SIGCHLD, &sv_sigchld, NULL);
742 #endif /* !USE_PROCFS */
744 execv(pathname, argv);
745 perror("strace: exec");
749 /* We are the tracer. */
750 /* With -D, we are *child* here, IOW: different pid. Fetch it. */
751 strace_tracer_pid = getpid();
753 tcp = alloctcb(daemonized_tracer ? getppid() : pid);
754 if (daemonized_tracer) {
755 /* We want subsequent startup_attach() to attach to it. */
756 tcp->flags |= TCB_ATTACHED;
759 if (proc_open(tcp, 0) < 0) {
760 fprintf(stderr, "trouble opening proc file\n");
764 #endif /* USE_PROCFS */
769 * Test whether the kernel support PTRACE_O_TRACECLONE et al options.
770 * First fork a new child, call ptrace with PTRACE_SETOPTIONS on it,
771 * and then see which options are supported by the kernel.
774 test_ptrace_setoptions_followfork(void)
776 int pid, expected_grandchild = 0, found_grandchild = 0;
777 const unsigned int test_options = PTRACE_O_TRACECLONE |
781 if ((pid = fork()) < 0)
784 if (ptrace(PTRACE_TRACEME, 0, (char *)1, 0) < 0)
786 kill(getpid(), SIGSTOP);
791 int status, tracee_pid;
793 tracee_pid = wait(&status);
794 if (tracee_pid == -1) {
797 else if (errno == ECHILD)
799 perror("test_ptrace_setoptions_followfork");
802 if (tracee_pid != pid) {
803 found_grandchild = tracee_pid;
804 if (ptrace(PTRACE_CONT, tracee_pid, 0, 0) < 0 &&
806 kill(tracee_pid, SIGKILL);
808 else if (WIFSTOPPED(status)) {
809 switch (WSTOPSIG(status)) {
811 if (ptrace(PTRACE_SETOPTIONS, pid,
812 NULL, test_options) < 0) {
818 if (status >> 16 == PTRACE_EVENT_FORK) {
821 if (ptrace(PTRACE_GETEVENTMSG, pid,
822 NULL, (long) &msg) == 0)
823 expected_grandchild = msg;
827 if (ptrace(PTRACE_SYSCALL, pid, 0, 0) < 0 &&
832 if (expected_grandchild && expected_grandchild == found_grandchild)
833 ptrace_setoptions_followfork |= test_options;
838 * Test whether the kernel support PTRACE_O_TRACESYSGOOD.
839 * First fork a new child, call ptrace(PTRACE_SETOPTIONS) on it,
840 * and then see whether it will stop with (SIGTRAP | 0x80).
842 * Use of this option enables correct handling of user-generated SIGTRAPs,
843 * and SIGTRAPs generated by special instructions such as int3 on x86:
844 * _start: .globl _start
849 * (compile with: "gcc -nostartfiles -nostdlib -o int3 int3.S")
852 test_ptrace_setoptions_for_all(void)
854 const unsigned int test_options = PTRACE_O_TRACESYSGOOD | PTRACE_O_TRACEEXEC;
860 perror_msg_and_die("fork");
864 if (ptrace(PTRACE_TRACEME, 0L, 0L, 0L) < 0)
865 /* Note: exits with exitcode 1 */
866 perror_msg_and_die("%s: PTRACE_TRACEME doesn't work", __func__);
868 _exit(0); /* parent should see entry into this syscall */
872 int status, tracee_pid;
875 tracee_pid = wait(&status);
876 if (tracee_pid <= 0) {
880 perror_msg_and_die("%s: unexpected wait result %d", __func__, tracee_pid);
882 if (WIFEXITED(status)) {
883 if (WEXITSTATUS(status) == 0)
885 /* PTRACE_TRACEME failed in child. This is fatal. */
888 if (!WIFSTOPPED(status)) {
890 error_msg_and_die("%s: unexpected wait status %x", __func__, status);
892 if (WSTOPSIG(status) == SIGSTOP) {
894 * We don't check "options aren't accepted" error.
895 * If it happens, we'll never get (SIGTRAP | 0x80),
896 * and thus will decide to not use the option.
897 * IOW: the outcome of the test will be correct.
899 if (ptrace(PTRACE_SETOPTIONS, pid, 0L, test_options) < 0)
901 perror_msg("PTRACE_SETOPTIONS");
903 if (WSTOPSIG(status) == (SIGTRAP | 0x80)) {
906 if (ptrace(PTRACE_SYSCALL, pid, 0L, 0L) < 0) {
908 perror_msg_and_die("PTRACE_SYSCALL doesn't work");
913 syscall_trap_sig = (SIGTRAP | 0x80);
914 ptrace_setoptions_for_all = test_options;
916 fprintf(stderr, "ptrace_setoptions_for_all = %#x\n",
917 ptrace_setoptions_for_all);
922 "Test for PTRACE_O_TRACESYSGOOD failed, giving up using this feature.\n");
927 main(int argc, char *argv[])
934 static char buf[BUFSIZ];
936 progname = argv[0] ? argv[0] : "strace";
938 strace_tracer_pid = getpid();
940 /* Allocate the initial tcbtab. */
941 tcbtabsize = argc; /* Surely enough for all -p args. */
942 if ((tcbtab = calloc(tcbtabsize, sizeof tcbtab[0])) == NULL) {
943 fprintf(stderr, "%s: out of memory\n", progname);
946 if ((tcbtab[0] = calloc(tcbtabsize, sizeof tcbtab[0][0])) == NULL) {
947 fprintf(stderr, "%s: out of memory\n", progname);
950 for (tcp = tcbtab[0]; tcp < &tcbtab[0][tcbtabsize]; ++tcp)
951 tcbtab[tcp - tcbtab[0]] = &tcbtab[0][tcp - tcbtab[0]];
955 set_sortby(DEFAULT_SORTBY);
956 set_personality(DEFAULT_PERSONALITY);
957 qualify("trace=all");
958 qualify("abbrev=all");
959 qualify("verbose=all");
960 qualify("signal=all");
961 while ((c = getopt(argc, argv,
966 "a:e:o:O:p:s:S:u:E:P:")) != EOF) {
969 if (cflag == CFLAG_BOTH) {
970 fprintf(stderr, "%s: -c and -C are mutually exclusive options\n",
974 cflag = CFLAG_ONLY_STATS;
977 if (cflag == CFLAG_ONLY_STATS) {
978 fprintf(stderr, "%s: -c and -C are mutually exclusive options\n",
989 daemonized_tracer = 1;
1024 qualify("abbrev=none");
1027 printf("%s -- version %s\n", PACKAGE_NAME, VERSION);
1031 not_failing_only = 1;
1034 acolumn = atoi(optarg);
1040 outfname = strdup(optarg);
1043 set_overhead(atoi(optarg));
1046 if ((pid = atoi(optarg)) <= 0) {
1047 fprintf(stderr, "%s: Invalid process id: %s\n",
1051 if (pid == strace_tracer_pid) {
1052 fprintf(stderr, "%s: I'm sorry, I can't let you do that, Dave.\n", progname);
1055 tcp = alloc_tcb(pid, 0);
1056 tcp->flags |= TCB_ATTACHED;
1061 if (pathtrace_select(optarg)) {
1062 fprintf(stderr, "%s : failed to select path '%s'\n", progname, optarg);
1067 max_strlen = atoi(optarg);
1068 if (max_strlen < 0) {
1070 "%s: invalid -s argument: %s\n",
1079 username = strdup(optarg);
1082 if (putenv(optarg) < 0) {
1083 fprintf(stderr, "%s: out of memory\n",
1094 if ((optind == argc) == !pflag_seen)
1097 if (pflag_seen && daemonized_tracer) {
1099 "%s: -D and -p are mutually exclusive options\n",
1107 if (followfork > 1 && cflag) {
1109 "%s: (-c or -C) and -ff are mutually exclusive options\n",
1114 /* See if they want to run as another user. */
1115 if (username != NULL) {
1116 struct passwd *pent;
1118 if (getuid() != 0 || geteuid() != 0) {
1120 "%s: you must be root to use the -u option\n",
1124 if ((pent = getpwnam(username)) == NULL) {
1125 fprintf(stderr, "%s: cannot find user `%s'\n",
1126 progname, username);
1129 run_uid = pent->pw_uid;
1130 run_gid = pent->pw_gid;
1139 if (test_ptrace_setoptions_followfork() < 0) {
1141 "Test for options supported by PTRACE_SETOPTIONS "
1142 "failed, giving up using this feature.\n");
1143 ptrace_setoptions_followfork = 0;
1146 fprintf(stderr, "ptrace_setoptions_followfork = %#x\n",
1147 ptrace_setoptions_followfork);
1149 test_ptrace_setoptions_for_all();
1152 /* Check if they want to redirect the output. */
1154 /* See if they want to pipe the output. */
1155 if (outfname[0] == '|' || outfname[0] == '!') {
1157 * We can't do the <outfname>.PID funny business
1158 * when using popen, so prohibit it.
1160 if (followfork > 1) {
1162 %s: piping the output and -ff are mutually exclusive options\n",
1167 if ((outf = strace_popen(outfname + 1)) == NULL)
1170 else if (followfork <= 1 &&
1171 (outf = strace_fopen(outfname, "w")) == NULL)
1175 if (!outfname || outfname[0] == '|' || outfname[0] == '!')
1176 setvbuf(outf, buf, _IOLBF, BUFSIZ);
1177 if (outfname && optind < argc) {
1182 /* Valid states here:
1183 optind < argc pflag_seen outfname interactive
1190 /* STARTUP_CHILD must be called before the signal handlers get
1191 installed below as they are inherited into the spawned process.
1192 Also we do not need to be protected by them as during interruption
1193 in the STARTUP_CHILD mode we kill the spawned process anyway. */
1195 startup_child(&argv[optind]);
1197 sigemptyset(&empty_set);
1198 sigemptyset(&blocked_set);
1199 sa.sa_handler = SIG_IGN;
1200 sigemptyset(&sa.sa_mask);
1202 sigaction(SIGTTOU, &sa, NULL);
1203 sigaction(SIGTTIN, &sa, NULL);
1205 sigaddset(&blocked_set, SIGHUP);
1206 sigaddset(&blocked_set, SIGINT);
1207 sigaddset(&blocked_set, SIGQUIT);
1208 sigaddset(&blocked_set, SIGPIPE);
1209 sigaddset(&blocked_set, SIGTERM);
1210 sa.sa_handler = interrupt;
1212 /* POSIX signals on sunos4.1 are a little broken. */
1213 sa.sa_flags = SA_INTERRUPT;
1216 sigaction(SIGHUP, &sa, NULL);
1217 sigaction(SIGINT, &sa, NULL);
1218 sigaction(SIGQUIT, &sa, NULL);
1219 sigaction(SIGPIPE, &sa, NULL);
1220 sigaction(SIGTERM, &sa, NULL);
1222 sa.sa_handler = reaper;
1223 sigaction(SIGCHLD, &sa, NULL);
1225 /* Make sure SIGCHLD has the default action so that waitpid
1226 definitely works without losing track of children. The user
1227 should not have given us a bogus state to inherit, but he might
1228 have. Arguably we should detect SIG_IGN here and pass it on
1229 to children, but probably noone really needs that. */
1230 sa.sa_handler = SIG_DFL;
1231 sigaction(SIGCHLD, &sa, NULL);
1232 #endif /* USE_PROCFS */
1234 if (pflag_seen || daemonized_tracer)
1241 if (exit_code > 0xff) {
1242 /* Child was killed by a signal, mimic that. */
1244 signal(exit_code, SIG_DFL);
1246 /* Paranoia - what if this signal is not fatal?
1247 Exit with 128 + signo then. */
1256 /* Allocate some more TCBs and expand the table.
1257 We don't want to relocate the TCBs because our
1258 callers have pointers and it would be a pain.
1259 So tcbtab is a table of pointers. Since we never
1260 free the TCBs, we allocate a single chunk of many. */
1261 struct tcb **newtab = (struct tcb **)
1262 realloc(tcbtab, 2 * tcbtabsize * sizeof tcbtab[0]);
1263 struct tcb *newtcbs = (struct tcb *) calloc(tcbtabsize,
1266 if (newtab == NULL || newtcbs == NULL) {
1267 fprintf(stderr, "%s: expand_tcbtab: out of memory\n",
1272 for (i = tcbtabsize; i < 2 * tcbtabsize; ++i)
1273 newtab[i] = &newtcbs[i - tcbtabsize];
1279 alloc_tcb(int pid, int command_options_parsed)
1284 if (nprocs == tcbtabsize)
1287 for (i = 0; i < tcbtabsize; i++) {
1289 if ((tcp->flags & TCB_INUSE) == 0) {
1294 #ifdef TCB_CLONE_THREAD
1295 tcp->nclone_threads = 0;
1296 tcp->nclone_waiting = 0;
1298 tcp->flags = TCB_INUSE | TCB_STARTUP;
1299 tcp->outf = outf; /* Initialise to current out file */
1301 tcp->stime.tv_sec = 0;
1302 tcp->stime.tv_usec = 0;
1305 if (command_options_parsed)
1310 fprintf(stderr, "%s: bug in alloc_tcb\n", progname);
1317 proc_open(struct tcb *tcp, int attaching)
1327 #ifndef HAVE_POLLABLE_PROCFS
1328 static int last_pfd;
1331 #ifdef HAVE_MP_PROCFS
1332 /* Open the process pseudo-files in /proc. */
1333 sprintf(proc, "/proc/%d/ctl", tcp->pid);
1334 if ((tcp->pfd = open(proc, O_WRONLY|O_EXCL)) < 0) {
1335 perror("strace: open(\"/proc/...\", ...)");
1338 if (set_cloexec_flag(tcp->pfd) < 0) {
1341 sprintf(proc, "/proc/%d/status", tcp->pid);
1342 if ((tcp->pfd_stat = open(proc, O_RDONLY|O_EXCL)) < 0) {
1343 perror("strace: open(\"/proc/...\", ...)");
1346 if (set_cloexec_flag(tcp->pfd_stat) < 0) {
1349 sprintf(proc, "/proc/%d/as", tcp->pid);
1350 if ((tcp->pfd_as = open(proc, O_RDONLY|O_EXCL)) < 0) {
1351 perror("strace: open(\"/proc/...\", ...)");
1354 if (set_cloexec_flag(tcp->pfd_as) < 0) {
1358 /* Open the process pseudo-file in /proc. */
1360 sprintf(proc, "/proc/%d", tcp->pid);
1361 tcp->pfd = open(proc, O_RDWR|O_EXCL);
1363 sprintf(proc, "/proc/%d/mem", tcp->pid);
1364 tcp->pfd = open(proc, O_RDWR);
1365 #endif /* FREEBSD */
1367 perror("strace: open(\"/proc/...\", ...)");
1370 if (set_cloexec_flag(tcp->pfd) < 0) {
1375 sprintf(proc, "/proc/%d/regs", tcp->pid);
1376 if ((tcp->pfd_reg = open(proc, O_RDONLY)) < 0) {
1377 perror("strace: open(\"/proc/.../regs\", ...)");
1381 sprintf(proc, "/proc/%d/status", tcp->pid);
1382 if ((tcp->pfd_status = open(proc, O_RDONLY)) < 0) {
1383 perror("strace: open(\"/proc/.../status\", ...)");
1387 tcp->pfd_status = -1;
1388 #endif /* FREEBSD */
1392 * Wait for the child to pause. Because of a race
1393 * condition we have to poll for the event.
1396 if (IOCTL_STATUS(tcp) < 0) {
1397 perror("strace: PIOCSTATUS");
1400 if (tcp->status.PR_FLAGS & PR_ASLEEP)
1405 /* Stop the process so that we own the stop. */
1406 if (IOCTL(tcp->pfd, PIOCSTOP, (char *)NULL) < 0) {
1407 perror("strace: PIOCSTOP");
1412 /* Set Run-on-Last-Close. */
1414 if (IOCTL(tcp->pfd, PIOCSET, &arg) < 0) {
1415 perror("PIOCSET PR_RLC");
1418 /* Set or Reset Inherit-on-Fork. */
1420 if (IOCTL(tcp->pfd, followfork ? PIOCSET : PIOCRESET, &arg) < 0) {
1421 perror("PIOC{SET,RESET} PR_FORK");
1424 #else /* !PIOCSET */
1426 if (ioctl(tcp->pfd, PIOCSRLC) < 0) {
1430 if (ioctl(tcp->pfd, followfork ? PIOCSFORK : PIOCRFORK) < 0) {
1431 perror("PIOC{S,R}FORK");
1435 /* just unset the PF_LINGER flag for the Run-on-Last-Close. */
1436 if (ioctl(tcp->pfd, PIOCGFL, &arg) < 0) {
1441 if (ioctl(tcp->pfd, PIOCSFL, arg) < 0) {
1445 #endif /* FREEBSD */
1446 #endif /* !PIOCSET */
1448 /* Enable all syscall entries we care about. */
1449 premptyset(&syscalls);
1450 for (i = 1; i < MAX_QUALS; ++i) {
1451 if (i > (sizeof syscalls) * CHAR_BIT) break;
1452 if (qual_flags[i] & QUAL_TRACE) praddset(&syscalls, i);
1454 praddset(&syscalls, SYS_execve);
1456 praddset(&syscalls, SYS_fork);
1458 praddset(&syscalls, SYS_forkall);
1461 praddset(&syscalls, SYS_fork1);
1464 praddset(&syscalls, SYS_rfork1);
1467 praddset(&syscalls, SYS_rforkall);
1470 if (IOCTL(tcp->pfd, PIOCSENTRY, &syscalls) < 0) {
1471 perror("PIOCSENTRY");
1474 /* Enable the syscall exits. */
1475 if (IOCTL(tcp->pfd, PIOCSEXIT, &syscalls) < 0) {
1479 /* Enable signals we care about. */
1480 premptyset(&signals);
1481 for (i = 1; i < MAX_QUALS; ++i) {
1482 if (i > (sizeof signals) * CHAR_BIT) break;
1483 if (qual_flags[i] & QUAL_SIGNAL) praddset(&signals, i);
1485 if (IOCTL(tcp->pfd, PIOCSTRACE, &signals) < 0) {
1486 perror("PIOCSTRACE");
1489 /* Enable faults we care about */
1490 premptyset(&faults);
1491 for (i = 1; i < MAX_QUALS; ++i) {
1492 if (i > (sizeof faults) * CHAR_BIT) break;
1493 if (qual_flags[i] & QUAL_FAULT) praddset(&faults, i);
1495 if (IOCTL(tcp->pfd, PIOCSFAULT, &faults) < 0) {
1496 perror("PIOCSFAULT");
1500 /* set events flags. */
1501 arg = S_SIG | S_SCE | S_SCX;
1502 if (ioctl(tcp->pfd, PIOCBIS, arg) < 0) {
1506 #endif /* FREEBSD */
1510 * The SGI PRSABORT doesn't work for pause() so
1511 * we send it a caught signal to wake it up.
1513 kill(tcp->pid, SIGINT);
1516 /* The child is in a pause(), abort it. */
1518 if (IOCTL(tcp->pfd, PIOCRUN, &arg) < 0) {
1525 /* wake up the child if it received the SIGSTOP */
1526 kill(tcp->pid, SIGCONT);
1529 /* Wait for the child to do something. */
1530 if (IOCTL_WSTOP(tcp) < 0) {
1531 perror("PIOCWSTOP");
1534 if (tcp->status.PR_WHY == PR_SYSENTRY) {
1535 tcp->flags &= ~TCB_INSYSCALL;
1537 if (known_scno(tcp) == SYS_execve)
1540 /* Set it running: maybe execve will be next. */
1543 if (IOCTL(tcp->pfd, PIOCRUN, &arg) < 0) {
1545 if (IOCTL(tcp->pfd, PIOCRUN, 0) < 0) {
1546 #endif /* FREEBSD */
1551 /* handle the case where we "opened" the child before
1552 it did the kill -STOP */
1553 if (tcp->status.PR_WHY == PR_SIGNALLED &&
1554 tcp->status.PR_WHAT == SIGSTOP)
1555 kill(tcp->pid, SIGCONT);
1562 if (attaching < 2) {
1563 /* We are attaching to an already running process.
1564 * Try to figure out the state of the process in syscalls,
1565 * to handle the first event well.
1566 * This is done by having a look at the "wchan" property of the
1567 * process, which tells where it is stopped (if it is). */
1569 char wchan[20]; /* should be enough */
1571 sprintf(proc, "/proc/%d/status", tcp->pid);
1572 status = fopen(proc, "r");
1574 (fscanf(status, "%*s %*d %*d %*d %*d %*d,%*d %*s %*d,%*d"
1575 "%*d,%*d %*d,%*d %19s", wchan) == 1) &&
1576 strcmp(wchan, "nochan") && strcmp(wchan, "spread") &&
1577 strcmp(wchan, "stopevent")) {
1578 /* The process is asleep in the middle of a syscall.
1579 Fake the syscall entry event */
1580 tcp->flags &= ~(TCB_INSYSCALL|TCB_STARTUP);
1581 tcp->status.PR_WHY = PR_SYSENTRY;
1586 } /* otherwise it's a fork being followed */
1588 #endif /* FREEBSD */
1589 #ifndef HAVE_POLLABLE_PROCFS
1590 if (proc_poll_pipe[0] != -1)
1591 proc_poller(tcp->pfd);
1592 else if (nprocs > 1) {
1594 proc_poller(last_pfd);
1595 proc_poller(tcp->pfd);
1597 last_pfd = tcp->pfd;
1598 #endif /* !HAVE_POLLABLE_PROCFS */
1602 #endif /* USE_PROCFS */
1612 for (i = 0; i < tcbtabsize; i++) {
1613 struct tcb *tcp = tcbtab[i];
1614 if (tcp->pid == pid && (tcp->flags & TCB_INUSE))
1624 first_used_tcb(void)
1628 for (i = 0; i < tcbtabsize; i++) {
1630 if (tcp->flags & TCB_INUSE)
1641 for (i = 0; i < tcbtabsize; i++) {
1642 struct tcb *tcp = tcbtab[i];
1643 if (tcp->pfd != pfd)
1645 if (tcp->flags & TCB_INUSE)
1651 #endif /* USE_PROCFS */
1654 droptcb(struct tcb *tcp)
1658 #ifdef TCB_CLONE_THREAD
1659 if (tcp->nclone_threads > 0) {
1660 /* There are other threads left in this process, but this
1661 is the one whose PID represents the whole process.
1662 We need to keep this record around as a zombie until
1663 all the threads die. */
1664 tcp->flags |= TCB_EXITING;
1671 if (tcp->parent != NULL) {
1672 tcp->parent->nchildren--;
1673 #ifdef TCB_CLONE_THREAD
1674 if (tcp->flags & TCB_CLONE_THREAD)
1675 tcp->parent->nclone_threads--;
1677 tcp->parent->nzombies++;
1679 /* Update `tcp->parent->parent->nchildren' and the other fields
1680 like NCLONE_DETACHED, only for zombie group leader that has
1681 already reported and been short-circuited at the top of this
1682 function. The same condition as at the top of DETACH. */
1683 if ((tcp->flags & TCB_CLONE_THREAD) &&
1684 tcp->parent->nclone_threads == 0 &&
1685 (tcp->parent->flags & TCB_EXITING))
1686 droptcb(tcp->parent);
1692 if (tcp->pfd != -1) {
1696 if (tcp->pfd_reg != -1) {
1697 close(tcp->pfd_reg);
1700 if (tcp->pfd_status != -1) {
1701 close(tcp->pfd_status);
1702 tcp->pfd_status = -1;
1704 #endif /* !FREEBSD */
1706 rebuild_pollv(); /* Note, flags needs to be cleared by now. */
1710 if (outfname && followfork > 1 && tcp->outf)
1719 resume(struct tcb *tcp)
1724 if (!(tcp->flags & TCB_SUSPENDED)) {
1725 fprintf(stderr, "PANIC: pid %u not suspended\n", tcp->pid);
1728 tcp->flags &= ~TCB_SUSPENDED;
1729 #ifdef TCB_CLONE_THREAD
1730 if (tcp->flags & TCB_CLONE_THREAD)
1731 tcp->parent->nclone_waiting--;
1734 if (ptrace_restart(PTRACE_SYSCALL, tcp, 0) < 0)
1738 fprintf(stderr, "Process %u resumed\n", tcp->pid);
1743 resume_from_tcp(struct tcb *tcp)
1748 /* XXX This won't always be quite right (but it never was).
1749 A waiter with argument 0 or < -1 is waiting for any pid in
1750 a particular pgrp, which this child might or might not be
1751 in. The waiter will only wake up if it's argument is -1
1752 or if it's waiting for tcp->pid's pgrp. It makes a
1753 difference to wake up a waiter when there might be more
1754 traced children, because it could get a false ECHILD
1755 error. OTOH, if this was the last child in the pgrp, then
1756 it ought to wake up and get ECHILD. We would have to
1757 search the system for all pid's in the pgrp to be sure.
1759 && (t->waitpid == -1 ||
1760 (t->waitpid == 0 && getpgid (tcp->pid) == getpgid (t->pid))
1761 || (t->waitpid < 0 && t->waitpid == -getpid (t->pid)))
1765 (tcp->parent->flags & TCB_SUSPENDED) &&
1766 (tcp->parent->waitpid <= 0 || tcp->parent->waitpid == tcp->pid)) {
1767 error = resume(tcp->parent);
1770 #ifdef TCB_CLONE_THREAD
1771 if (tcp->parent && tcp->parent->nclone_waiting > 0) {
1772 /* Some other threads of our parent are waiting too. */
1775 /* Resume all the threads that were waiting for this PID. */
1776 for (i = 0; i < tcbtabsize; i++) {
1777 struct tcb *t = tcbtab[i];
1778 if (t->parent == tcp->parent && t != tcp
1779 && ((t->flags & (TCB_CLONE_THREAD|TCB_SUSPENDED))
1780 == (TCB_CLONE_THREAD|TCB_SUSPENDED))
1781 && t->waitpid == tcp->pid) {
1787 /* Noone was waiting for this PID in particular,
1788 so now we might need to resume some wildcarders. */
1789 for (i = 0; i < tcbtabsize; i++) {
1790 struct tcb *t = tcbtab[i];
1791 if (t->parent == tcp->parent && t != tcp
1793 & (TCB_CLONE_THREAD|TCB_SUSPENDED))
1794 == (TCB_CLONE_THREAD|TCB_SUSPENDED))
1807 #endif /* !USE_PROCFS */
1809 /* detach traced process; continue with sig
1810 Never call DETACH twice on the same process as both unattached and
1811 attached-unstopped processes give the same ESRCH. For unattached process we
1812 would SIGSTOP it and wait for its SIGSTOP notification forever. */
1815 detach(struct tcb *tcp, int sig)
1819 int status, catch_sigstop;
1820 struct tcb *zombie = NULL;
1822 /* If the group leader is lingering only because of this other
1823 thread now dying, then detach the leader as well. */
1824 if ((tcp->flags & TCB_CLONE_THREAD) &&
1825 tcp->parent->nclone_threads == 1 &&
1826 (tcp->parent->flags & TCB_EXITING))
1827 zombie = tcp->parent;
1830 if (tcp->flags & TCB_BPTSET)
1835 * Linux wrongly insists the child be stopped
1836 * before detaching. Arghh. We go through hoops
1837 * to make a clean break of things.
1840 #undef PTRACE_DETACH
1841 #define PTRACE_DETACH PTRACE_SUNDETACH
1844 * On TCB_STARTUP we did PTRACE_ATTACH but still did not get the
1845 * expected SIGSTOP. We must catch exactly one as otherwise the
1846 * detached process would be left stopped (process state T).
1848 catch_sigstop = (tcp->flags & TCB_STARTUP);
1849 if ((error = ptrace(PTRACE_DETACH, tcp->pid, (char *) 1, sig)) == 0) {
1850 /* On a clear day, you can see forever. */
1852 else if (errno != ESRCH) {
1853 /* Shouldn't happen. */
1854 perror("detach: ptrace(PTRACE_DETACH, ...)");
1856 else if (my_tgkill((tcp->flags & TCB_CLONE_THREAD ? tcp->parent->pid
1860 perror("detach: checking sanity");
1862 else if (!catch_sigstop && my_tgkill((tcp->flags & TCB_CLONE_THREAD
1863 ? tcp->parent->pid : tcp->pid),
1864 tcp->pid, SIGSTOP) < 0) {
1866 perror("detach: stopping child");
1870 if (catch_sigstop) {
1873 if (wait4(tcp->pid, &status, __WALL, NULL) < 0) {
1874 if (errno == ECHILD) /* Already gone. */
1876 if (errno != EINVAL) {
1877 perror("detach: waiting");
1881 /* No __WALL here. */
1882 if (waitpid(tcp->pid, &status, 0) < 0) {
1883 if (errno != ECHILD) {
1884 perror("detach: waiting");
1888 /* If no processes, try clones. */
1889 if (wait4(tcp->pid, &status, __WCLONE,
1891 if (errno != ECHILD)
1892 perror("detach: waiting");
1895 #endif /* __WCLONE */
1900 if (!WIFSTOPPED(status)) {
1901 /* Au revoir, mon ami. */
1904 if (WSTOPSIG(status) == SIGSTOP) {
1905 ptrace_restart(PTRACE_DETACH, tcp, sig);
1908 error = ptrace_restart(PTRACE_CONT, tcp,
1909 WSTOPSIG(status) == syscall_trap_sig ? 0
1910 : WSTOPSIG(status));
1918 /* PTRACE_DETACH won't respect `sig' argument, so we post it here. */
1919 if (sig && kill(tcp->pid, sig) < 0)
1920 perror("detach: kill");
1922 error = ptrace_restart(PTRACE_DETACH, tcp, sig);
1926 error |= resume_from_tcp(tcp);
1930 fprintf(stderr, "Process %u detached\n", tcp->pid);
1935 if (zombie != NULL) {
1936 /* TCP no longer exists therefore you must not detach() it. */
1946 static void reaper(int sig)
1951 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
1955 #endif /* USE_PROCFS */
1963 for (i = 0; i < tcbtabsize; i++) {
1965 if (!(tcp->flags & TCB_INUSE))
1969 "cleanup: looking at pid %u\n", tcp->pid);
1971 (!outfname || followfork < 2 || tcp_last == tcp)) {
1972 tprintf(" <unfinished ...>");
1975 if (tcp->flags & TCB_ATTACHED)
1978 kill(tcp->pid, SIGCONT);
1979 kill(tcp->pid, SIGTERM);
1992 #ifndef HAVE_STRERROR
1994 #if !HAVE_DECL_SYS_ERRLIST
1995 extern int sys_nerr;
1996 extern char *sys_errlist[];
1997 #endif /* HAVE_DECL_SYS_ERRLIST */
2000 strerror(int err_no)
2002 static char buf[64];
2004 if (err_no < 1 || err_no >= sys_nerr) {
2005 sprintf(buf, "Unknown error %d", err_no);
2008 return sys_errlist[err_no];
2011 #endif /* HAVE_STERRROR */
2013 #ifndef HAVE_STRSIGNAL
2015 #if defined HAVE_SYS_SIGLIST && !defined HAVE_DECL_SYS_SIGLIST
2016 extern char *sys_siglist[];
2018 #if defined HAVE_SYS__SIGLIST && !defined HAVE_DECL__SYS_SIGLIST
2019 extern char *_sys_siglist[];
2025 static char buf[64];
2027 if (sig < 1 || sig >= NSIG) {
2028 sprintf(buf, "Unknown signal %d", sig);
2031 #ifdef HAVE__SYS_SIGLIST
2032 return _sys_siglist[sig];
2034 return sys_siglist[sig];
2038 #endif /* HAVE_STRSIGNAL */
2049 pollv = (struct pollfd *) malloc(nprocs * sizeof pollv[0]);
2050 if (pollv == NULL) {
2051 fprintf(stderr, "%s: out of memory\n", progname);
2055 for (i = j = 0; i < tcbtabsize; i++) {
2056 struct tcb *tcp = tcbtab[i];
2057 if (!(tcp->flags & TCB_INUSE))
2059 pollv[j].fd = tcp->pfd;
2060 pollv[j].events = POLLWANT;
2064 fprintf(stderr, "strace: proc miscount\n");
2069 #ifndef HAVE_POLLABLE_PROCFS
2072 proc_poll_open(void)
2076 if (pipe(proc_poll_pipe) < 0) {
2080 for (i = 0; i < 2; i++) {
2081 if (set_cloexec_flag(proc_poll_pipe[i]) < 0) {
2088 proc_poll(struct pollfd *pollv, int nfds, int timeout)
2092 struct proc_pollfd pollinfo;
2094 if ((n = read(proc_poll_pipe[0], &pollinfo, sizeof(pollinfo))) < 0)
2096 if (n != sizeof(struct proc_pollfd)) {
2097 fprintf(stderr, "panic: short read: %d\n", n);
2100 for (i = 0; i < nprocs; i++) {
2101 if (pollv[i].fd == pollinfo.fd)
2102 pollv[i].revents = pollinfo.revents;
2104 pollv[i].revents = 0;
2106 poller_pid = pollinfo.pid;
2111 wakeup_handler(int sig)
2116 proc_poller(int pfd)
2118 struct proc_pollfd pollinfo;
2119 struct sigaction sa;
2120 sigset_t blocked_set, empty_set;
2125 struct procfs_status pfs;
2126 #endif /* FREEBSD */
2138 sa.sa_handler = interactive ? SIG_DFL : SIG_IGN;
2140 sigemptyset(&sa.sa_mask);
2141 sigaction(SIGHUP, &sa, NULL);
2142 sigaction(SIGINT, &sa, NULL);
2143 sigaction(SIGQUIT, &sa, NULL);
2144 sigaction(SIGPIPE, &sa, NULL);
2145 sigaction(SIGTERM, &sa, NULL);
2146 sa.sa_handler = wakeup_handler;
2147 sigaction(SIGUSR1, &sa, NULL);
2148 sigemptyset(&blocked_set);
2149 sigaddset(&blocked_set, SIGUSR1);
2150 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
2151 sigemptyset(&empty_set);
2153 if (getrlimit(RLIMIT_NOFILE, &rl) < 0) {
2154 perror("getrlimit(RLIMIT_NOFILE, ...)");
2158 for (i = 0; i < n; i++) {
2159 if (i != pfd && i != proc_poll_pipe[1])
2164 pollinfo.pid = getpid();
2167 if (ioctl(pfd, PIOCWSTOP, NULL) < 0)
2169 if (ioctl(pfd, PIOCWSTOP, &pfs) < 0)
2176 pollinfo.revents = POLLERR;
2179 pollinfo.revents = POLLHUP;
2182 perror("proc_poller: PIOCWSTOP");
2184 write(proc_poll_pipe[1], &pollinfo, sizeof(pollinfo));
2187 pollinfo.revents = POLLWANT;
2188 write(proc_poll_pipe[1], &pollinfo, sizeof(pollinfo));
2189 sigsuspend(&empty_set);
2193 #endif /* !HAVE_POLLABLE_PROCFS */
2203 if (followfork < 2 &&
2204 last < nprocs && (pollv[last].revents & POLLWANT)) {
2206 * The previous process is ready to run again. We'll
2207 * let it do so if it is currently in a syscall. This
2208 * heuristic improves the readability of the trace.
2210 tcp = pfd2tcb(pollv[last].fd);
2211 if (tcp && (tcp->flags & TCB_INSYSCALL))
2212 return pollv[last].fd;
2215 for (i = 0; i < nprocs; i++) {
2216 /* Let competing children run round robin. */
2217 j = (i + last + 1) % nprocs;
2218 if (pollv[j].revents & (POLLHUP | POLLERR)) {
2219 tcp = pfd2tcb(pollv[j].fd);
2221 fprintf(stderr, "strace: lost proc\n");
2227 if (pollv[j].revents & POLLWANT) {
2232 fprintf(stderr, "strace: nothing ready\n");
2240 struct tcb *in_syscall = NULL;
2245 int ioctl_result = 0, ioctl_errno = 0;
2250 sigprocmask(SIG_SETMASK, &empty_set, NULL);
2257 #ifndef HAVE_POLLABLE_PROCFS
2258 if (proc_poll_pipe[0] == -1) {
2260 tcp = first_used_tcb();
2267 #ifndef HAVE_POLLABLE_PROCFS
2269 /* fall through ... */
2270 #endif /* !HAVE_POLLABLE_PROCFS */
2272 #ifdef HAVE_POLLABLE_PROCFS
2274 /* On some systems (e.g. UnixWare) we get too much ugly
2275 "unfinished..." stuff when multiple proceses are in
2276 syscalls. Here's a nasty hack */
2283 pv.events = POLLWANT;
2284 if ((what = poll(&pv, 1, 1)) < 0) {
2289 else if (what == 1 && pv.revents & POLLWANT) {
2295 if (poll(pollv, nprocs, INFTIM) < 0) {
2300 #else /* !HAVE_POLLABLE_PROCFS */
2301 if (proc_poll(pollv, nprocs, INFTIM) < 0) {
2306 #endif /* !HAVE_POLLABLE_PROCFS */
2313 /* Look up `pfd' in our table. */
2314 if ((tcp = pfd2tcb(pfd)) == NULL) {
2315 fprintf(stderr, "unknown pfd: %u\n", pfd);
2321 /* Get the status of the process. */
2324 ioctl_result = IOCTL_WSTOP(tcp);
2326 /* Thanks to some scheduling mystery, the first poller
2327 sometimes waits for the already processed end of fork
2328 event. Doing a non blocking poll here solves the problem. */
2329 if (proc_poll_pipe[0] != -1)
2330 ioctl_result = IOCTL_STATUS(tcp);
2332 ioctl_result = IOCTL_WSTOP(tcp);
2333 #endif /* FREEBSD */
2334 ioctl_errno = errno;
2335 #ifndef HAVE_POLLABLE_PROCFS
2336 if (proc_poll_pipe[0] != -1) {
2337 if (ioctl_result < 0)
2338 kill(poller_pid, SIGKILL);
2340 kill(poller_pid, SIGUSR1);
2342 #endif /* !HAVE_POLLABLE_PROCFS */
2348 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
2350 if (ioctl_result < 0) {
2351 /* Find out what happened if it failed. */
2352 switch (ioctl_errno) {
2363 perror("PIOCWSTOP");
2369 if ((tcp->flags & TCB_STARTUP) && (tcp->status.PR_WHY == PR_SYSEXIT)) {
2370 /* discard first event for a syscall we never entered */
2371 IOCTL(tcp->pfd, PIOCRUN, 0);
2376 /* clear the just started flag */
2377 tcp->flags &= ~TCB_STARTUP;
2379 /* set current output file */
2381 curcol = tcp->curcol;
2384 struct timeval stime;
2389 if ((len = pread(tcp->pfd_status, buf, sizeof(buf) - 1, 0)) > 0) {
2392 "%*s %*d %*d %*d %*d %*d,%*d %*s %*d,%*d %*d,%*d %ld,%ld",
2393 &stime.tv_sec, &stime.tv_usec);
2395 stime.tv_sec = stime.tv_usec = 0;
2396 #else /* !FREEBSD */
2397 stime.tv_sec = tcp->status.pr_stime.tv_sec;
2398 stime.tv_usec = tcp->status.pr_stime.tv_nsec/1000;
2399 #endif /* !FREEBSD */
2400 tv_sub(&tcp->dtime, &stime, &tcp->stime);
2403 what = tcp->status.PR_WHAT;
2404 switch (tcp->status.PR_WHY) {
2407 if (tcp->status.PR_FLAGS & PR_ASLEEP) {
2408 tcp->status.PR_WHY = PR_SYSENTRY;
2409 if (trace_syscall(tcp) < 0) {
2410 fprintf(stderr, "syscall trouble\n");
2415 #endif /* !FREEBSD */
2421 if (trace_syscall(tcp) < 0) {
2422 fprintf(stderr, "syscall trouble\n");
2427 if (cflag != CFLAG_ONLY_STATS
2428 && (qual_flags[what] & QUAL_SIGNAL)) {
2430 tprintf("--- %s (%s) ---",
2431 signame(what), strsignal(what));
2434 if (tcp->status.PR_INFO.si_signo == what) {
2436 tprintf(" siginfo=");
2437 printsiginfo(&tcp->status.PR_INFO, 1);
2444 if (cflag != CFLAGS_ONLY_STATS
2445 && (qual_flags[what] & QUAL_FAULT)) {
2447 tprintf("=== FAULT %d ===", what);
2452 case 0: /* handle case we polled for nothing */
2456 fprintf(stderr, "odd stop %d\n", tcp->status.PR_WHY);
2460 /* Remember current print column before continuing. */
2461 tcp->curcol = curcol;
2464 if (IOCTL(tcp->pfd, PIOCRUN, &arg) < 0)
2466 if (IOCTL(tcp->pfd, PIOCRUN, 0) < 0)
2476 #else /* !USE_PROCFS */
2478 #ifdef TCB_GROUP_EXITING
2479 /* Handle an exit detach or death signal that is taking all the
2480 related clone threads with it. This is called in three circumstances:
2481 SIG == -1 TCP has already died (TCB_ATTACHED is clear, strace is parent).
2482 SIG == 0 Continuing TCP will perform an exit_group syscall.
2483 SIG == other Continuing TCP with SIG will kill the process.
2486 handle_group_exit(struct tcb *tcp, int sig)
2488 /* We need to locate our records of all the clone threads
2489 related to TCP, either its children or siblings. */
2490 struct tcb *leader = NULL;
2492 if (tcp->flags & TCB_CLONE_THREAD)
2493 leader = tcp->parent;
2496 if (leader != NULL && leader != tcp
2497 && !(leader->flags & TCB_GROUP_EXITING)
2498 && !(tcp->flags & TCB_STARTUP)
2501 "PANIC: handle_group_exit: %d leader %d\n",
2502 tcp->pid, leader ? leader->pid : -1);
2504 /* TCP no longer exists therefore you must not detach() it. */
2506 resume_from_tcp(tcp);
2508 droptcb(tcp); /* Already died. */
2511 /* Mark that we are taking the process down. */
2512 tcp->flags |= TCB_EXITING | TCB_GROUP_EXITING;
2513 if (tcp->flags & TCB_ATTACHED) {
2515 if (leader != NULL && leader != tcp)
2516 leader->flags |= TCB_GROUP_EXITING;
2518 if (ptrace_restart(PTRACE_CONT, tcp, sig) < 0) {
2522 if (leader != NULL) {
2523 leader->flags |= TCB_GROUP_EXITING;
2527 /* The leader will report to us as parent now,
2528 and then we'll get to the SIG==-1 case. */
2539 handle_ptrace_event(int status, struct tcb *tcp)
2541 if (status >> 16 == PTRACE_EVENT_VFORK ||
2542 status >> 16 == PTRACE_EVENT_CLONE ||
2543 status >> 16 == PTRACE_EVENT_FORK) {
2546 if (do_ptrace(PTRACE_GETEVENTMSG, tcp, NULL, &childpid) < 0) {
2547 if (errno != ESRCH) {
2549 %s: handle_ptrace_event: ptrace cannot get new child's pid\n",
2556 return handle_new_child(tcp, childpid, 0);
2558 if (status >> 16 == PTRACE_EVENT_EXEC) {
2560 fprintf(stderr, "PTRACE_EVENT_EXEC on pid %d (ignored)\n", tcp->pid);
2563 /* Some PTRACE_EVENT_foo we didn't ask for?! */
2564 error_msg("Unexpected status %x on pid %d", status, tcp->pid);
2579 static int wait4_options = __WALL;
2583 while (nprocs != 0) {
2587 sigprocmask(SIG_SETMASK, &empty_set, NULL);
2590 pid = wait4(-1, &status, wait4_options, cflag ? &ru : NULL);
2591 if (pid < 0 && (wait4_options & __WALL) && errno == EINVAL) {
2592 /* this kernel does not support __WALL */
2593 wait4_options &= ~__WALL;
2595 pid = wait4(-1, &status, wait4_options,
2596 cflag ? &ru : NULL);
2598 if (pid < 0 && !(wait4_options & __WALL) && errno == ECHILD) {
2599 /* most likely a "cloned" process */
2600 pid = wait4(-1, &status, __WCLONE,
2601 cflag ? &ru : NULL);
2603 fprintf(stderr, "strace: clone wait4 "
2604 "failed: %s\n", strerror(errno));
2608 pid = wait4(-1, &status, 0, cflag ? &ru : NULL);
2612 pid = wait(&status);
2616 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
2619 switch (wait_errno) {
2624 * We would like to verify this case
2625 * but sometimes a race in Solbourne's
2626 * version of SunOS sometimes reports
2627 * ECHILD before sending us SIGCHILD.
2632 perror("strace: wait");
2636 if (pid == popen_pid) {
2637 if (WIFEXITED(status) || WIFSIGNALED(status))
2642 fprintf(stderr, " [wait(%#x) = %u]\n", status, pid);
2644 /* Look up `pid' in our table. */
2645 if ((tcp = pid2tcb(pid)) == NULL) {
2648 /* This is needed to go with the CLONE_PTRACE
2649 changes in process.c/util.c: we might see
2650 the child's initial trap before we see the
2651 parent return from the clone syscall.
2652 Leave the child suspended until the parent
2653 returns from its system call. Only then
2654 will we have the association of parent and
2655 child so that we know how to do clearbpt
2657 tcp = alloctcb(pid);
2658 tcp->flags |= TCB_ATTACHED | TCB_SUSPENDED;
2661 Process %d attached (waiting for parent)\n",
2665 /* This can happen if a clone call used
2666 CLONE_PTRACE itself. */
2669 fprintf(stderr, "unknown pid: %u\n", pid);
2670 if (WIFSTOPPED(status))
2671 ptrace(PTRACE_CONT, pid, (char *) 1, 0);
2675 /* set current output file */
2677 curcol = tcp->curcol;
2680 tv_sub(&tcp->dtime, &ru.ru_stime, &tcp->stime);
2681 tcp->stime = ru.ru_stime;
2685 if (tcp->flags & TCB_SUSPENDED) {
2687 * Apparently, doing any ptrace() call on a stopped
2688 * process, provokes the kernel to report the process
2689 * status again on a subsequent wait(), even if the
2690 * process has not been actually restarted.
2691 * Since we have inspected the arguments of suspended
2692 * processes we end up here testing for this case.
2696 if (WIFSIGNALED(status)) {
2697 if (pid == strace_child)
2698 exit_code = 0x100 | WTERMSIG(status);
2699 if (cflag != CFLAG_ONLY_STATS
2700 && (qual_flags[WTERMSIG(status)] & QUAL_SIGNAL)) {
2702 tprintf("+++ killed by %s %s+++",
2703 signame(WTERMSIG(status)),
2705 WCOREDUMP(status) ? "(core dumped) " :
2710 #ifdef TCB_GROUP_EXITING
2711 handle_group_exit(tcp, -1);
2717 if (WIFEXITED(status)) {
2718 if (pid == strace_child)
2719 exit_code = WEXITSTATUS(status);
2721 fprintf(stderr, "pid %u exited with %d\n", pid, WEXITSTATUS(status));
2722 if ((tcp->flags & (TCB_ATTACHED|TCB_STARTUP)) == TCB_ATTACHED
2723 #ifdef TCB_GROUP_EXITING
2724 && !(tcp->parent && (tcp->parent->flags & TCB_GROUP_EXITING))
2725 && !(tcp->flags & TCB_GROUP_EXITING)
2729 "PANIC: attached pid %u exited with %d\n",
2730 pid, WEXITSTATUS(status));
2732 if (tcp == tcp_last) {
2733 if ((tcp->flags & (TCB_INSYSCALL|TCB_REPRINT)) == TCB_INSYSCALL)
2734 tprintf(" <unfinished ... exit status %d>\n",
2735 WEXITSTATUS(status));
2738 #ifdef TCB_GROUP_EXITING
2739 handle_group_exit(tcp, -1);
2745 if (!WIFSTOPPED(status)) {
2746 fprintf(stderr, "PANIC: pid %u not stopped\n", pid);
2751 fprintf(stderr, "pid %u stopped, [%s]\n",
2752 pid, signame(WSTOPSIG(status)));
2755 if (handle_ptrace_event(status, tcp) != 1)
2760 * Interestingly, the process may stop
2761 * with STOPSIG equal to some other signal
2762 * than SIGSTOP if we happend to attach
2763 * just before the process takes a signal.
2764 * A no-MMU vforked child won't send up a signal,
2765 * so skip the first (lost) execve notification.
2767 if ((tcp->flags & TCB_STARTUP) &&
2768 (WSTOPSIG(status) == SIGSTOP || strace_vforked)) {
2770 * This flag is there to keep us in sync.
2771 * Next time this process stops it should
2772 * really be entering a system call.
2774 tcp->flags &= ~TCB_STARTUP;
2775 if (tcp->flags & TCB_BPTSET) {
2777 * One example is a breakpoint inherited from
2778 * parent through fork ().
2780 if (clearbpt(tcp) < 0) /* Pretty fatal */ {
2787 int options = ptrace_setoptions_for_all;
2788 if (followfork && (tcp->parent == NULL))
2789 options |= ptrace_setoptions_followfork;
2792 fprintf(stderr, "setting opts %x on pid %d\n", options, tcp->pid);
2793 if (ptrace(PTRACE_SETOPTIONS, tcp->pid, NULL, options) < 0) {
2794 if (errno != ESRCH) {
2795 /* Should never happen, really */
2796 perror_msg_and_die("PTRACE_SETOPTIONS");
2804 if (WSTOPSIG(status) != syscall_trap_sig) {
2805 if (WSTOPSIG(status) == SIGSTOP &&
2806 (tcp->flags & TCB_SIGTRAPPED)) {
2808 * Trapped attempt to block SIGTRAP
2809 * Hope we are back in control now.
2811 tcp->flags &= ~(TCB_INSYSCALL | TCB_SIGTRAPPED);
2812 if (ptrace_restart(PTRACE_SYSCALL, tcp, 0) < 0) {
2818 if (cflag != CFLAG_ONLY_STATS
2819 && (qual_flags[WSTOPSIG(status)] & QUAL_SIGNAL)) {
2821 #if defined(PT_CR_IPSR) && defined(PT_CR_IIP)
2825 upeek(tcp, PT_CR_IPSR, &psr);
2826 upeek(tcp, PT_CR_IIP, &pc);
2829 pc += (psr >> PSR_RI) & 0x3;
2830 # define PC_FORMAT_STR " @ %lx"
2831 # define PC_FORMAT_ARG pc
2833 # define PC_FORMAT_STR "%s"
2834 # define PC_FORMAT_ARG ""
2837 if (ptrace(PTRACE_GETSIGINFO, pid, 0, &si) == 0) {
2839 printsiginfo(&si, verbose(tcp));
2840 tprintf(" (%s)" PC_FORMAT_STR " ---",
2841 strsignal(WSTOPSIG(status)),
2844 tprintf("--- %s by %s" PC_FORMAT_STR " ---",
2845 strsignal(WSTOPSIG(status)),
2846 signame(WSTOPSIG(status)),
2850 if (((tcp->flags & TCB_ATTACHED) ||
2851 tcp->nclone_threads > 0) &&
2852 !sigishandled(tcp, WSTOPSIG(status))) {
2853 #ifdef TCB_GROUP_EXITING
2854 handle_group_exit(tcp, WSTOPSIG(status));
2856 detach(tcp, WSTOPSIG(status));
2860 if (ptrace_restart(PTRACE_SYSCALL, tcp, WSTOPSIG(status)) < 0) {
2864 tcp->flags &= ~TCB_SUSPENDED;
2867 /* we handled the STATUS, we are permitted to interrupt now. */
2870 if (trace_syscall(tcp) < 0 && !tcp->ptrace_errno) {
2871 /* ptrace() failed in trace_syscall() with ESRCH.
2872 * Likely a result of process disappearing mid-flight.
2873 * Observed case: exit_group() terminating
2874 * all processes in thread group. In this case, threads
2875 * "disappear" in an unpredictable moment without any
2876 * notification to strace via wait().
2878 if (tcp->flags & TCB_ATTACHED) {
2880 /* Do we have dangling line "syscall(param, param"?
2881 * Finish the line then. We cannot
2883 tcp_last->flags |= TCB_REPRINT;
2884 tprintf(" <unfinished ...>");
2890 tcp->pid, (char *) 1, SIGTERM);
2895 if (tcp->flags & TCB_EXITING) {
2896 #ifdef TCB_GROUP_EXITING
2897 if (tcp->flags & TCB_GROUP_EXITING) {
2898 if (handle_group_exit(tcp, 0) < 0)
2903 if (tcp->flags & TCB_ATTACHED)
2905 else if (ptrace_restart(PTRACE_CONT, tcp, 0) < 0) {
2911 if (tcp->flags & TCB_SUSPENDED) {
2913 fprintf(stderr, "Process %u suspended\n", pid);
2917 /* Remember current print column before continuing. */
2918 tcp->curcol = curcol;
2919 if (ptrace_restart(PTRACE_SYSCALL, tcp, 0) < 0) {
2927 #endif /* !USE_PROCFS */
2932 tprintf(const char *fmt, ...)
2936 va_start(args, fmt);
2938 int n = vfprintf(outf, fmt, args);
2941 perror(outfname == NULL
2942 ? "<writing to pipe>" : outfname);
2951 printleader(struct tcb *tcp)
2954 if (tcp_last->ptrace_errno) {
2955 if (tcp_last->flags & TCB_INSYSCALL) {
2956 tprintf(" <unavailable>)");
2959 tprintf("= ? <unavailable>\n");
2960 tcp_last->ptrace_errno = 0;
2961 } else if (!outfname || followfork < 2 || tcp_last == tcp) {
2962 tcp_last->flags |= TCB_REPRINT;
2963 tprintf(" <unfinished ...>\n");
2967 if ((followfork == 1 || pflag_seen > 1) && outfname)
2968 tprintf("%-5d ", tcp->pid);
2969 else if (nprocs > 1 && !outfname)
2970 tprintf("[pid %5u] ", tcp->pid);
2972 char str[sizeof("HH:MM:SS")];
2973 struct timeval tv, dtv;
2974 static struct timeval otv;
2976 gettimeofday(&tv, NULL);
2978 if (otv.tv_sec == 0)
2980 tv_sub(&dtv, &tv, &otv);
2981 tprintf("%6ld.%06ld ",
2982 (long) dtv.tv_sec, (long) dtv.tv_usec);
2985 else if (tflag > 2) {
2986 tprintf("%ld.%06ld ",
2987 (long) tv.tv_sec, (long) tv.tv_usec);
2990 time_t local = tv.tv_sec;
2991 strftime(str, sizeof(str), "%T", localtime(&local));
2993 tprintf("%s.%06ld ", str, (long) tv.tv_usec);
2995 tprintf("%s ", str);
3006 tprintf("%*s", col - curcol, "");
3016 #ifdef HAVE_MP_PROCFS
3019 mp_ioctl(int fd, int cmd, void *arg, int size)
3021 struct iovec iov[2];
3024 iov[0].iov_base = &cmd;
3025 iov[0].iov_len = sizeof cmd;
3028 iov[1].iov_base = arg;
3029 iov[1].iov_len = size;
3032 return writev(fd, iov, n);