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_tkill
53 # define my_tkill(tid, sig) syscall(__NR_tkill, (tid), (sig))
55 /* kill() may choose arbitrarily the target task of the process group
56 while we later wait on a that specific TID. PID process waits become
57 TID task specific waits for a process under ptrace(2). */
58 # warning "Neither tkill(2) nor tgkill(2) available, risk of strace hangs!"
59 # define my_tkill(tid, sig) kill((tid), (sig))
63 #if defined(IA64) && defined(LINUX)
64 # include <asm/ptrace_offsets.h>
72 #include <sys/stropts.h>
79 extern char **environ;
84 int debug = 0, followfork = 0;
85 unsigned int ptrace_setoptions = 0;
86 /* Which WSTOPSIG(status) value marks syscall traps? */
87 static unsigned int syscall_trap_sig = SIGTRAP;
88 int dtime = 0, xflag = 0, qflag = 0;
89 cflag_t cflag = CFLAG_NONE;
90 static int iflag = 0, interactive = 0, pflag_seen = 0, rflag = 0, tflag = 0;
92 * daemonized_tracer supports -D option.
93 * With this option, strace forks twice.
94 * Unlike normal case, with -D *grandparent* process exec's,
95 * becoming a traced process. Child exits (this prevents traced process
96 * from having children it doesn't expect to have), and grandchild
97 * attaches to grandparent similarly to strace -p PID.
98 * This allows for more transparent interaction in cases
99 * when process and its parent are communicating via signals,
100 * wait() etc. Without -D, strace process gets lodged in between,
101 * disrupting parent<->child link.
103 static bool daemonized_tracer = 0;
105 /* Sometimes we want to print only succeeding syscalls. */
106 int not_failing_only = 0;
108 /* Show path associated with fd arguments */
109 int show_fd_path = 0;
111 /* are we filtering traces based on paths? */
112 int tracing_paths = 0;
114 static int exit_code = 0;
115 static int strace_child = 0;
116 static int strace_tracer_pid = 0;
118 static char *username = NULL;
119 static uid_t run_uid;
120 static gid_t run_gid;
122 int acolumn = DEFAULT_ACOLUMN;
123 int max_strlen = DEFAULT_STRLEN;
124 static char *outfname = NULL;
127 static struct tcb **tcbtab;
128 static unsigned int nprocs, tcbtabsize;
129 static const char *progname;
131 static int detach(struct tcb *tcp, int sig);
132 static int trace(void);
133 static void cleanup(void);
134 static void interrupt(int sig);
135 static sigset_t empty_set, blocked_set;
137 #ifdef HAVE_SIG_ATOMIC_T
138 static volatile sig_atomic_t interrupted;
139 #else /* !HAVE_SIG_ATOMIC_T */
140 static volatile int interrupted;
141 #endif /* !HAVE_SIG_ATOMIC_T */
145 static struct tcb *pfd2tcb(int pfd);
146 static void reaper(int sig);
147 static void rebuild_pollv(void);
148 static struct pollfd *pollv;
150 #ifndef HAVE_POLLABLE_PROCFS
152 static void proc_poll_open(void);
153 static void proc_poller(int pfd);
161 static int poller_pid;
162 static int proc_poll_pipe[2] = { -1, -1 };
164 #endif /* !HAVE_POLLABLE_PROCFS */
166 #ifdef HAVE_MP_PROCFS
167 #define POLLWANT POLLWRNORM
169 #define POLLWANT POLLPRI
171 #endif /* USE_PROCFS */
174 usage(FILE *ofp, int exitval)
177 usage: strace [-CdDffhiqrtttTvVxxy] [-a column] [-e expr] ... [-o file]\n\
178 [-p pid] ... [-s strsize] [-u username] [-E var=val] ...\n\
179 [-P path] [command [arg ...]]\n\
180 or: strace -c [-D] [-e expr] ... [-O overhead] [-S sortby] [-E var=val] ...\n\
181 [command [arg ...]]\n\
182 -c -- count time, calls, and errors for each syscall and report summary\n\
183 -C -- like -c but also print regular output while processes are running\n\
184 -f -- follow forks, -ff -- with output into separate files\n\
185 -F -- attempt to follow vforks, -h -- print help message\n\
186 -i -- print instruction pointer at time of syscall\n\
187 -q -- suppress messages about attaching, detaching, etc.\n\
188 -r -- print relative timestamp, -t -- absolute timestamp, -tt -- with usecs\n\
189 -T -- print time spent in each syscall, -V -- print version\n\
190 -v -- verbose mode: print unabbreviated argv, stat, termio[s], etc. args\n\
191 -x -- print non-ascii strings in hex, -xx -- print all strings in hex\n\
192 -y -- print paths associated with file descriptor arguments\n\
193 -a column -- alignment COLUMN for printing syscall results (default %d)\n\
194 -e expr -- a qualifying expression: option=[!]all or option=[!]val1[,val2]...\n\
195 options: trace, abbrev, verbose, raw, signal, read, or write\n\
196 -o file -- send trace output to FILE instead of stderr\n\
197 -O overhead -- set overhead for tracing syscalls to OVERHEAD usecs\n\
198 -p pid -- trace process with process id PID, may be repeated\n\
199 -D -- run tracer process as a detached grandchild, not as parent\n\
200 -s strsize -- limit length of print strings to STRSIZE chars (default %d)\n\
201 -S sortby -- sort syscall counts by: time, calls, name, nothing (default %s)\n\
202 -u username -- run command as username handling setuid and/or setgid\n\
203 -E var=val -- put var=val in the environment for command\n\
204 -E var -- remove var from the environment for command\n\
205 -P path -- trace accesses to path\n\
206 " /* this is broken, so don't document it
207 -z -- print only succeeding syscalls\n\
209 , DEFAULT_ACOLUMN, DEFAULT_STRLEN, DEFAULT_SORTBY);
213 static void die(void) __attribute__ ((noreturn));
214 static void die(void)
216 if (strace_tracer_pid == getpid()) {
223 static void verror_msg(int err_no, const char *fmt, va_list p)
226 fprintf(stderr, "%s: ", progname);
227 vfprintf(stderr, fmt, p);
229 fprintf(stderr, ": %s\n", strerror(err_no));
235 void error_msg(const char *fmt, ...)
239 verror_msg(0, fmt, p);
243 void error_msg_and_die(const char *fmt, ...)
247 verror_msg(0, fmt, p);
251 void perror_msg(const char *fmt, ...)
255 verror_msg(errno, fmt, p);
259 void perror_msg_and_die(const char *fmt, ...)
263 verror_msg(errno, fmt, p);
276 /* Glue for systems without a MMU that cannot provide fork() */
278 # define strace_vforked 0
280 # define strace_vforked 1
281 # define fork() vfork()
285 set_cloexec_flag(int fd)
289 flags = fcntl(fd, F_GETFD);
291 /* Can happen only if fd is bad.
292 * Should never happen: if it does, we have a bug
293 * in the caller. Therefore we just abort
294 * instead of propagating the error.
296 perror_msg_and_die("fcntl(%d, F_GETFD)", fd);
299 newflags = flags | FD_CLOEXEC;
300 if (flags == newflags)
303 fcntl(fd, F_SETFD, newflags); /* never fails */
307 * When strace is setuid executable, we have to swap uids
308 * before and after filesystem and process management operations.
314 int euid = geteuid(), uid = getuid();
316 if (euid != uid && setreuid(euid, uid) < 0) {
317 perror_msg_and_die("setreuid");
323 # define fopen_for_output fopen64
325 # define fopen_for_output fopen
329 strace_fopen(const char *path)
334 fp = fopen_for_output(path, "w");
336 perror_msg_and_die("Can't fopen '%s'", path);
338 set_cloexec_flag(fileno(fp));
342 static int popen_pid = 0;
345 # define _PATH_BSHELL "/bin/sh"
349 * We cannot use standard popen(3) here because we have to distinguish
350 * popen child process from other processes we trace, and standard popen(3)
351 * does not export its child's pid.
354 strace_popen(const char *command)
361 perror_msg_and_die("pipe");
363 set_cloexec_flag(fds[1]); /* never fails */
367 perror_msg_and_die("vfork");
369 if (popen_pid == 0) {
374 perror_msg_and_die("dup2");
377 execl(_PATH_BSHELL, "sh", "-c", command, NULL);
378 perror_msg_and_die("Can't execute '%s'", _PATH_BSHELL);
384 fp = fdopen(fds[1], "w");
386 error_msg_and_die("Out of memory");
391 newoutf(struct tcb *tcp)
393 if (outfname && followfork > 1) {
394 char name[520 + sizeof(int) * 3];
395 sprintf(name, "%.512s.%u", outfname, tcp->pid);
396 tcp->outf = strace_fopen(name);
407 * Block user interruptions as we would leave the traced
408 * process stopped (process state T) if we would terminate in
409 * between PTRACE_ATTACH and wait4 () on SIGSTOP.
410 * We rely on cleanup() from this point on.
413 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
415 if (daemonized_tracer) {
420 if (pid) { /* parent */
422 * Wait for grandchild to attach to straced process
423 * (grandparent). Grandchild SIGKILLs us after it attached.
424 * Grandparent's wait() is unblocked by our death,
425 * it proceeds to exec the straced program.
428 _exit(0); /* paranoia */
431 /* We will be the tracer process. Remember our new pid: */
432 strace_tracer_pid = getpid();
435 for (tcbi = 0; tcbi < tcbtabsize; tcbi++) {
438 if (!(tcp->flags & TCB_INUSE) || !(tcp->flags & TCB_ATTACHED))
441 if (tcp->flags & TCB_ATTACH_DONE)
444 /* Reinitialize the output since it may have changed. */
449 if (proc_open(tcp, 1) < 0) {
450 fprintf(stderr, "trouble opening proc file\n");
454 #else /* !USE_PROCFS */
456 if (followfork && !daemonized_tracer) {
457 char procdir[sizeof("/proc/%d/task") + sizeof(int) * 3];
460 sprintf(procdir, "/proc/%d/task", tcp->pid);
461 dir = opendir(procdir);
463 unsigned int ntid = 0, nerr = 0;
466 while ((de = readdir(dir)) != NULL) {
467 if (de->d_fileno == 0)
469 tid = atoi(de->d_name);
473 if (ptrace(PTRACE_ATTACH, tid, (char *) 1, 0) < 0) {
476 fprintf(stderr, "attach to pid %d failed\n", tid);
480 fprintf(stderr, "attach to pid %d succeeded\n", tid);
481 if (tid != tcp->pid) {
482 struct tcb *new_tcp = alloctcb(tid);
483 new_tcp->flags |= TCB_ATTACHED|TCB_ATTACH_DONE;
487 sigprocmask(SIG_SETMASK, &empty_set, NULL);
490 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
496 perror("attach: ptrace(PTRACE_ATTACH, ...)");
501 fprintf(stderr, ntid > 1
502 ? "Process %u attached with %u threads - interrupt to quit\n"
503 : "Process %u attached - interrupt to quit\n",
507 } /* if (opendir worked) */
510 if (ptrace(PTRACE_ATTACH, tcp->pid, (char *) 1, 0) < 0) {
511 perror("attach: ptrace(PTRACE_ATTACH, ...)");
516 fprintf(stderr, "attach to pid %d (main) succeeded\n", tcp->pid);
518 if (daemonized_tracer) {
520 * It is our grandparent we trace, not a -p PID.
521 * Don't want to just detach on exit, so...
523 tcp->flags &= ~TCB_ATTACHED;
525 * Make parent go away.
526 * Also makes grandparent's wait() unblock.
528 kill(getppid(), SIGKILL);
531 #endif /* !USE_PROCFS */
534 "Process %u attached - interrupt to quit\n",
536 } /* for each tcbtab[] */
540 /* TCB_ATTACH_DONE flag is used only in this function */
541 for (tcbi = 0; tcbi < tcbtabsize; tcbi++) {
543 tcp->flags &= ~TCB_ATTACH_DONE;
548 sigprocmask(SIG_SETMASK, &empty_set, NULL);
552 startup_child(char **argv)
555 const char *filename;
556 char pathname[MAXPATHLEN];
561 if (strchr(filename, '/')) {
562 if (strlen(filename) > sizeof pathname - 1) {
563 errno = ENAMETOOLONG;
564 perror_msg_and_die("exec");
566 strcpy(pathname, filename);
568 #ifdef USE_DEBUGGING_EXEC
570 * Debuggers customarily check the current directory
571 * first regardless of the path but doing that gives
572 * security geeks a panic attack.
574 else if (stat(filename, &statbuf) == 0)
575 strcpy(pathname, filename);
576 #endif /* USE_DEBUGGING_EXEC */
581 for (path = getenv("PATH"); path && *path; path += m) {
582 if (strchr(path, ':')) {
583 n = strchr(path, ':') - path;
587 m = n = strlen(path);
589 if (!getcwd(pathname, MAXPATHLEN))
591 len = strlen(pathname);
593 else if (n > sizeof pathname - 1)
596 strncpy(pathname, path, n);
599 if (len && pathname[len - 1] != '/')
600 pathname[len++] = '/';
601 strcpy(pathname + len, filename);
602 if (stat(pathname, &statbuf) == 0 &&
603 /* Accept only regular files
604 with some execute bits set.
605 XXX not perfect, might still fail */
606 S_ISREG(statbuf.st_mode) &&
607 (statbuf.st_mode & 0111))
611 if (stat(pathname, &statbuf) < 0) {
612 perror_msg_and_die("Can't stat '%s'", filename);
614 strace_child = pid = fork();
616 perror_msg_and_die("fork");
618 if ((pid != 0 && daemonized_tracer) /* -D: parent to become a traced process */
619 || (pid == 0 && !daemonized_tracer) /* not -D: child to become a traced process */
623 if (outf != stderr) close(fileno(outf));
625 /* Kludge for SGI, see proc_open for details. */
626 sa.sa_handler = foobar;
628 sigemptyset(&sa.sa_mask);
629 sigaction(SIGINT, &sa, NULL);
634 kill(pid, SIGSTOP); /* stop HERE */
636 #else /* !USE_PROCFS */
640 if (!daemonized_tracer) {
641 if (ptrace(PTRACE_TRACEME, 0, (char *) 1, 0) < 0) {
642 perror_msg_and_die("ptrace(PTRACE_TRACEME, ...)");
648 if (username != NULL || geteuid() == 0) {
649 uid_t run_euid = run_uid;
650 gid_t run_egid = run_gid;
652 if (statbuf.st_mode & S_ISUID)
653 run_euid = statbuf.st_uid;
654 if (statbuf.st_mode & S_ISGID)
655 run_egid = statbuf.st_gid;
658 * It is important to set groups before we
659 * lose privileges on setuid.
661 if (username != NULL) {
662 if (initgroups(username, run_gid) < 0) {
663 perror_msg_and_die("initgroups");
665 if (setregid(run_gid, run_egid) < 0) {
666 perror_msg_and_die("setregid");
668 if (setreuid(run_uid, run_euid) < 0) {
669 perror_msg_and_die("setreuid");
674 setreuid(run_uid, run_uid);
676 if (!daemonized_tracer) {
678 * Induce an immediate stop so that the parent
679 * will resume us with PTRACE_SYSCALL and display
680 * this execve call normally.
681 * Unless of course we're on a no-MMU system where
682 * we vfork()-ed, so we cannot stop the child.
685 kill(getpid(), SIGSTOP);
687 struct sigaction sv_sigchld;
688 sigaction(SIGCHLD, NULL, &sv_sigchld);
690 * Make sure it is not SIG_IGN, otherwise wait
693 signal(SIGCHLD, SIG_DFL);
695 * Wait for grandchild to attach to us.
696 * It kills child after that, and wait() unblocks.
701 sigaction(SIGCHLD, &sv_sigchld, NULL);
703 #endif /* !USE_PROCFS */
705 execv(pathname, argv);
706 perror_msg_and_die("exec");
709 /* We are the tracer. */
710 /* With -D, we are *child* here, IOW: different pid. Fetch it. */
711 strace_tracer_pid = getpid();
713 tcp = alloctcb(daemonized_tracer ? getppid() : pid);
714 if (daemonized_tracer) {
715 /* We want subsequent startup_attach() to attach to it. */
716 tcp->flags |= TCB_ATTACHED;
719 if (proc_open(tcp, 0) < 0) {
720 perror_msg_and_die("trouble opening proc file");
722 #endif /* USE_PROCFS */
726 static void kill_save_errno(pid_t pid, int sig)
728 int saved_errno = errno;
730 (void) kill(pid, sig);
735 * Test whether the kernel support PTRACE_O_TRACECLONE et al options.
736 * First fork a new child, call ptrace with PTRACE_SETOPTIONS on it,
737 * and then see which options are supported by the kernel.
740 test_ptrace_setoptions_followfork(void)
742 int pid, expected_grandchild = 0, found_grandchild = 0;
743 const unsigned int test_options = PTRACE_O_TRACECLONE |
747 if ((pid = fork()) < 0)
748 perror_msg_and_die("fork");
751 if (ptrace(PTRACE_TRACEME, 0, 0, 0) < 0)
752 perror_msg_and_die("%s: PTRACE_TRACEME doesn't work",
756 perror_msg_and_die("fork");
761 int status, tracee_pid;
764 tracee_pid = wait(&status);
765 if (tracee_pid <= 0) {
768 else if (errno == ECHILD)
770 kill_save_errno(pid, SIGKILL);
771 perror_msg_and_die("%s: unexpected wait result %d",
772 __func__, tracee_pid);
774 if (WIFEXITED(status)) {
775 if (WEXITSTATUS(status)) {
776 if (tracee_pid != pid)
777 kill_save_errno(pid, SIGKILL);
778 error_msg_and_die("%s: unexpected exit status %u",
779 __func__, WEXITSTATUS(status));
783 if (WIFSIGNALED(status)) {
784 if (tracee_pid != pid)
785 kill_save_errno(pid, SIGKILL);
786 error_msg_and_die("%s: unexpected signal %u",
787 __func__, WTERMSIG(status));
789 if (!WIFSTOPPED(status)) {
790 if (tracee_pid != pid)
791 kill_save_errno(tracee_pid, SIGKILL);
793 error_msg_and_die("%s: unexpected wait status %x",
796 if (tracee_pid != pid) {
797 found_grandchild = tracee_pid;
798 if (ptrace(PTRACE_CONT, tracee_pid, 0, 0) < 0) {
799 kill_save_errno(tracee_pid, SIGKILL);
800 kill_save_errno(pid, SIGKILL);
801 perror_msg_and_die("PTRACE_CONT doesn't work");
805 switch (WSTOPSIG(status)) {
807 if (ptrace(PTRACE_SETOPTIONS, pid, 0, test_options) < 0
808 && errno != EINVAL && errno != EIO)
809 perror_msg("PTRACE_SETOPTIONS");
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) {
822 kill_save_errno(pid, SIGKILL);
823 perror_msg_and_die("PTRACE_SYSCALL doesn't work");
826 if (expected_grandchild && expected_grandchild == found_grandchild) {
827 ptrace_setoptions |= test_options;
829 fprintf(stderr, "ptrace_setoptions = %#x\n",
833 error_msg("Test for PTRACE_O_TRACECLONE failed, "
834 "giving up using this feature.");
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 |
861 perror_msg_and_die("fork");
865 if (ptrace(PTRACE_TRACEME, 0L, 0L, 0L) < 0)
866 /* Note: exits with exitcode 1 */
867 perror_msg_and_die("%s: PTRACE_TRACEME doesn't work",
870 _exit(0); /* parent should see entry into this syscall */
874 int status, tracee_pid;
877 tracee_pid = wait(&status);
878 if (tracee_pid <= 0) {
881 kill_save_errno(pid, SIGKILL);
882 perror_msg_and_die("%s: unexpected wait result %d",
883 __func__, tracee_pid);
885 if (WIFEXITED(status)) {
886 if (WEXITSTATUS(status) == 0)
888 error_msg_and_die("%s: unexpected exit status %u",
889 __func__, WEXITSTATUS(status));
891 if (WIFSIGNALED(status)) {
892 error_msg_and_die("%s: unexpected signal %u",
893 __func__, WTERMSIG(status));
895 if (!WIFSTOPPED(status)) {
897 error_msg_and_die("%s: unexpected wait status %x",
900 if (WSTOPSIG(status) == SIGSTOP) {
902 * We don't check "options aren't accepted" error.
903 * If it happens, we'll never get (SIGTRAP | 0x80),
904 * and thus will decide to not use the option.
905 * IOW: the outcome of the test will be correct.
907 if (ptrace(PTRACE_SETOPTIONS, pid, 0L, test_options) < 0
908 && errno != EINVAL && errno != EIO)
909 perror_msg("PTRACE_SETOPTIONS");
911 if (WSTOPSIG(status) == (SIGTRAP | 0x80)) {
914 if (ptrace(PTRACE_SYSCALL, pid, 0L, 0L) < 0) {
915 kill_save_errno(pid, SIGKILL);
916 perror_msg_and_die("PTRACE_SYSCALL doesn't work");
921 syscall_trap_sig = (SIGTRAP | 0x80);
922 ptrace_setoptions |= test_options;
924 fprintf(stderr, "ptrace_setoptions = %#x\n",
929 error_msg("Test for PTRACE_O_TRACESYSGOOD failed, "
930 "giving up using this feature.");
935 main(int argc, char *argv[])
942 progname = argv[0] ? argv[0] : "strace";
944 strace_tracer_pid = getpid();
946 /* Allocate the initial tcbtab. */
947 tcbtabsize = argc; /* Surely enough for all -p args. */
948 tcbtab = calloc(tcbtabsize, sizeof(tcbtab[0]));
950 error_msg_and_die("Out of memory");
951 tcp = calloc(tcbtabsize, sizeof(*tcp));
953 error_msg_and_die("Out of memory");
954 for (c = 0; c < tcbtabsize; c++)
959 set_sortby(DEFAULT_SORTBY);
960 set_personality(DEFAULT_PERSONALITY);
961 qualify("trace=all");
962 qualify("abbrev=all");
963 qualify("verbose=all");
964 qualify("signal=all");
965 while ((c = getopt(argc, argv,
970 "a:e:o:O:p:s:S:u:E:P:")) != EOF) {
973 if (cflag == CFLAG_BOTH) {
974 error_msg_and_die("-c and -C are mutually exclusive options");
976 cflag = CFLAG_ONLY_STATS;
979 if (cflag == CFLAG_ONLY_STATS) {
980 error_msg_and_die("-c and -C are mutually exclusive options");
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 error_msg("Invalid process id: '%s'", optarg);
1050 if (pid == strace_tracer_pid) {
1051 error_msg("I'm sorry, I can't let you do that, Dave.");
1054 tcp = alloc_tcb(pid, 0);
1055 tcp->flags |= TCB_ATTACHED;
1060 if (pathtrace_select(optarg)) {
1061 error_msg_and_die("Failed to select path '%s'", optarg);
1065 max_strlen = atoi(optarg);
1066 if (max_strlen < 0) {
1067 error_msg_and_die("Invalid -s argument: '%s'", optarg);
1074 username = strdup(optarg);
1077 if (putenv(optarg) < 0) {
1078 error_msg_and_die("Out of memory");
1087 if ((optind == argc) == !pflag_seen)
1090 if (pflag_seen && daemonized_tracer) {
1091 error_msg_and_die("-D and -p are mutually exclusive options");
1097 if (followfork > 1 && cflag) {
1098 error_msg_and_die("(-c or -C) and -ff are mutually exclusive options");
1101 /* See if they want to run as another user. */
1102 if (username != NULL) {
1103 struct passwd *pent;
1105 if (getuid() != 0 || geteuid() != 0) {
1106 error_msg_and_die("You must be root to use the -u option");
1108 if ((pent = getpwnam(username)) == NULL) {
1109 error_msg_and_die("Cannot find user '%s'", username);
1111 run_uid = pent->pw_uid;
1112 run_gid = pent->pw_gid;
1121 test_ptrace_setoptions_followfork();
1122 test_ptrace_setoptions_for_all();
1125 /* Check if they want to redirect the output. */
1127 /* See if they want to pipe the output. */
1128 if (outfname[0] == '|' || outfname[0] == '!') {
1130 * We can't do the <outfname>.PID funny business
1131 * when using popen, so prohibit it.
1134 error_msg_and_die("Piping the output and -ff are mutually exclusive");
1135 outf = strace_popen(outfname + 1);
1137 else if (followfork <= 1)
1138 outf = strace_fopen(outfname);
1141 if (!outfname || outfname[0] == '|' || outfname[0] == '!') {
1142 static char buf[BUFSIZ];
1143 setvbuf(outf, buf, _IOLBF, BUFSIZ);
1145 if (outfname && optind < argc) {
1150 /* Valid states here:
1151 optind < argc pflag_seen outfname interactive
1158 /* STARTUP_CHILD must be called before the signal handlers get
1159 installed below as they are inherited into the spawned process.
1160 Also we do not need to be protected by them as during interruption
1161 in the STARTUP_CHILD mode we kill the spawned process anyway. */
1163 startup_child(&argv[optind]);
1165 sigemptyset(&empty_set);
1166 sigemptyset(&blocked_set);
1167 sa.sa_handler = SIG_IGN;
1168 sigemptyset(&sa.sa_mask);
1170 sigaction(SIGTTOU, &sa, NULL);
1171 sigaction(SIGTTIN, &sa, NULL);
1173 sigaddset(&blocked_set, SIGHUP);
1174 sigaddset(&blocked_set, SIGINT);
1175 sigaddset(&blocked_set, SIGQUIT);
1176 sigaddset(&blocked_set, SIGPIPE);
1177 sigaddset(&blocked_set, SIGTERM);
1178 sa.sa_handler = interrupt;
1180 /* POSIX signals on sunos4.1 are a little broken. */
1181 sa.sa_flags = SA_INTERRUPT;
1184 sigaction(SIGHUP, &sa, NULL);
1185 sigaction(SIGINT, &sa, NULL);
1186 sigaction(SIGQUIT, &sa, NULL);
1187 sigaction(SIGPIPE, &sa, NULL);
1188 sigaction(SIGTERM, &sa, NULL);
1190 sa.sa_handler = reaper;
1191 sigaction(SIGCHLD, &sa, NULL);
1193 /* Make sure SIGCHLD has the default action so that waitpid
1194 definitely works without losing track of children. The user
1195 should not have given us a bogus state to inherit, but he might
1196 have. Arguably we should detect SIG_IGN here and pass it on
1197 to children, but probably noone really needs that. */
1198 sa.sa_handler = SIG_DFL;
1199 sigaction(SIGCHLD, &sa, NULL);
1200 #endif /* USE_PROCFS */
1202 if (pflag_seen || daemonized_tracer)
1209 if (exit_code > 0xff) {
1210 /* Child was killed by a signal, mimic that. */
1212 signal(exit_code, SIG_DFL);
1214 /* Paranoia - what if this signal is not fatal?
1215 Exit with 128 + signo then. */
1224 /* Allocate some more TCBs and expand the table.
1225 We don't want to relocate the TCBs because our
1226 callers have pointers and it would be a pain.
1227 So tcbtab is a table of pointers. Since we never
1228 free the TCBs, we allocate a single chunk of many. */
1230 struct tcb *newtcbs = calloc(tcbtabsize, sizeof(newtcbs[0]));
1231 struct tcb **newtab = realloc(tcbtab, tcbtabsize * 2 * sizeof(tcbtab[0]));
1232 if (newtab == NULL || newtcbs == NULL)
1233 error_msg_and_die("expand_tcbtab: out of memory");
1236 while (i < tcbtabsize)
1237 tcbtab[i++] = newtcbs++;
1241 alloc_tcb(int pid, int command_options_parsed)
1246 if (nprocs == tcbtabsize)
1249 for (i = 0; i < tcbtabsize; i++) {
1251 if ((tcp->flags & TCB_INUSE) == 0) {
1252 memset(tcp, 0, sizeof(*tcp));
1254 tcp->flags = TCB_INUSE | TCB_STARTUP;
1255 tcp->outf = outf; /* Initialise to current out file */
1259 fprintf(stderr, "new tcb for pid %d, active tcbs:%d\n", tcp->pid, nprocs);
1260 if (command_options_parsed)
1265 error_msg_and_die("bug in alloc_tcb");
1270 proc_open(struct tcb *tcp, int attaching)
1280 #ifndef HAVE_POLLABLE_PROCFS
1281 static int last_pfd;
1284 #ifdef HAVE_MP_PROCFS
1285 /* Open the process pseudo-files in /proc. */
1286 sprintf(proc, "/proc/%d/ctl", tcp->pid);
1287 if ((tcp->pfd = open(proc, O_WRONLY|O_EXCL)) < 0) {
1288 perror("strace: open(\"/proc/...\", ...)");
1291 set_cloexec_flag(tcp->pfd);
1292 sprintf(proc, "/proc/%d/status", tcp->pid);
1293 if ((tcp->pfd_stat = open(proc, O_RDONLY|O_EXCL)) < 0) {
1294 perror("strace: open(\"/proc/...\", ...)");
1297 set_cloexec_flag(tcp->pfd_stat);
1298 sprintf(proc, "/proc/%d/as", tcp->pid);
1299 if ((tcp->pfd_as = open(proc, O_RDONLY|O_EXCL)) < 0) {
1300 perror("strace: open(\"/proc/...\", ...)");
1303 set_cloexec_flag(tcp->pfd_as);
1305 /* Open the process pseudo-file in /proc. */
1307 sprintf(proc, "/proc/%d", tcp->pid);
1308 tcp->pfd = open(proc, O_RDWR|O_EXCL);
1310 sprintf(proc, "/proc/%d/mem", tcp->pid);
1311 tcp->pfd = open(proc, O_RDWR);
1312 #endif /* FREEBSD */
1314 perror("strace: open(\"/proc/...\", ...)");
1317 set_cloexec_flag(tcp->pfd);
1320 sprintf(proc, "/proc/%d/regs", tcp->pid);
1321 if ((tcp->pfd_reg = open(proc, O_RDONLY)) < 0) {
1322 perror("strace: open(\"/proc/.../regs\", ...)");
1326 sprintf(proc, "/proc/%d/status", tcp->pid);
1327 if ((tcp->pfd_status = open(proc, O_RDONLY)) < 0) {
1328 perror("strace: open(\"/proc/.../status\", ...)");
1332 tcp->pfd_status = -1;
1333 #endif /* FREEBSD */
1337 * Wait for the child to pause. Because of a race
1338 * condition we have to poll for the event.
1341 if (IOCTL_STATUS(tcp) < 0) {
1342 perror("strace: PIOCSTATUS");
1345 if (tcp->status.PR_FLAGS & PR_ASLEEP)
1350 /* Stop the process so that we own the stop. */
1351 if (IOCTL(tcp->pfd, PIOCSTOP, (char *)NULL) < 0) {
1352 perror("strace: PIOCSTOP");
1357 /* Set Run-on-Last-Close. */
1359 if (IOCTL(tcp->pfd, PIOCSET, &arg) < 0) {
1360 perror("PIOCSET PR_RLC");
1363 /* Set or Reset Inherit-on-Fork. */
1365 if (IOCTL(tcp->pfd, followfork ? PIOCSET : PIOCRESET, &arg) < 0) {
1366 perror("PIOC{SET,RESET} PR_FORK");
1369 #else /* !PIOCSET */
1371 if (ioctl(tcp->pfd, PIOCSRLC) < 0) {
1375 if (ioctl(tcp->pfd, followfork ? PIOCSFORK : PIOCRFORK) < 0) {
1376 perror("PIOC{S,R}FORK");
1380 /* just unset the PF_LINGER flag for the Run-on-Last-Close. */
1381 if (ioctl(tcp->pfd, PIOCGFL, &arg) < 0) {
1386 if (ioctl(tcp->pfd, PIOCSFL, arg) < 0) {
1390 #endif /* FREEBSD */
1391 #endif /* !PIOCSET */
1393 /* Enable all syscall entries we care about. */
1394 premptyset(&syscalls);
1395 for (i = 1; i < MAX_QUALS; ++i) {
1396 if (i > (sizeof syscalls) * CHAR_BIT) break;
1397 if (qual_flags[i] & QUAL_TRACE) praddset(&syscalls, i);
1399 praddset(&syscalls, SYS_execve);
1401 praddset(&syscalls, SYS_fork);
1403 praddset(&syscalls, SYS_forkall);
1406 praddset(&syscalls, SYS_fork1);
1409 praddset(&syscalls, SYS_rfork1);
1412 praddset(&syscalls, SYS_rforkall);
1415 if (IOCTL(tcp->pfd, PIOCSENTRY, &syscalls) < 0) {
1416 perror("PIOCSENTRY");
1419 /* Enable the syscall exits. */
1420 if (IOCTL(tcp->pfd, PIOCSEXIT, &syscalls) < 0) {
1424 /* Enable signals we care about. */
1425 premptyset(&signals);
1426 for (i = 1; i < MAX_QUALS; ++i) {
1427 if (i > (sizeof signals) * CHAR_BIT) break;
1428 if (qual_flags[i] & QUAL_SIGNAL) praddset(&signals, i);
1430 if (IOCTL(tcp->pfd, PIOCSTRACE, &signals) < 0) {
1431 perror("PIOCSTRACE");
1434 /* Enable faults we care about */
1435 premptyset(&faults);
1436 for (i = 1; i < MAX_QUALS; ++i) {
1437 if (i > (sizeof faults) * CHAR_BIT) break;
1438 if (qual_flags[i] & QUAL_FAULT) praddset(&faults, i);
1440 if (IOCTL(tcp->pfd, PIOCSFAULT, &faults) < 0) {
1441 perror("PIOCSFAULT");
1445 /* set events flags. */
1446 arg = S_SIG | S_SCE | S_SCX;
1447 if (ioctl(tcp->pfd, PIOCBIS, arg) < 0) {
1451 #endif /* FREEBSD */
1455 * The SGI PRSABORT doesn't work for pause() so
1456 * we send it a caught signal to wake it up.
1458 kill(tcp->pid, SIGINT);
1461 /* The child is in a pause(), abort it. */
1463 if (IOCTL(tcp->pfd, PIOCRUN, &arg) < 0) {
1470 /* wake up the child if it received the SIGSTOP */
1471 kill(tcp->pid, SIGCONT);
1474 /* Wait for the child to do something. */
1475 if (IOCTL_WSTOP(tcp) < 0) {
1476 perror("PIOCWSTOP");
1479 if (tcp->status.PR_WHY == PR_SYSENTRY) {
1480 tcp->flags &= ~TCB_INSYSCALL;
1482 if (known_scno(tcp) == SYS_execve)
1485 /* Set it running: maybe execve will be next. */
1488 if (IOCTL(tcp->pfd, PIOCRUN, &arg) < 0) {
1490 if (IOCTL(tcp->pfd, PIOCRUN, 0) < 0) {
1491 #endif /* FREEBSD */
1496 /* handle the case where we "opened" the child before
1497 it did the kill -STOP */
1498 if (tcp->status.PR_WHY == PR_SIGNALLED &&
1499 tcp->status.PR_WHAT == SIGSTOP)
1500 kill(tcp->pid, SIGCONT);
1507 if (attaching < 2) {
1508 /* We are attaching to an already running process.
1509 * Try to figure out the state of the process in syscalls,
1510 * to handle the first event well.
1511 * This is done by having a look at the "wchan" property of the
1512 * process, which tells where it is stopped (if it is). */
1514 char wchan[20]; /* should be enough */
1516 sprintf(proc, "/proc/%d/status", tcp->pid);
1517 status = fopen(proc, "r");
1519 (fscanf(status, "%*s %*d %*d %*d %*d %*d,%*d %*s %*d,%*d"
1520 "%*d,%*d %*d,%*d %19s", wchan) == 1) &&
1521 strcmp(wchan, "nochan") && strcmp(wchan, "spread") &&
1522 strcmp(wchan, "stopevent")) {
1523 /* The process is asleep in the middle of a syscall.
1524 Fake the syscall entry event */
1525 tcp->flags &= ~(TCB_INSYSCALL|TCB_STARTUP);
1526 tcp->status.PR_WHY = PR_SYSENTRY;
1531 } /* otherwise it's a fork being followed */
1533 #endif /* FREEBSD */
1534 #ifndef HAVE_POLLABLE_PROCFS
1535 if (proc_poll_pipe[0] != -1)
1536 proc_poller(tcp->pfd);
1537 else if (nprocs > 1) {
1539 proc_poller(last_pfd);
1540 proc_poller(tcp->pfd);
1542 last_pfd = tcp->pfd;
1543 #endif /* !HAVE_POLLABLE_PROCFS */
1547 #endif /* USE_PROCFS */
1557 for (i = 0; i < tcbtabsize; i++) {
1558 struct tcb *tcp = tcbtab[i];
1559 if (tcp->pid == pid && (tcp->flags & TCB_INUSE))
1569 first_used_tcb(void)
1573 for (i = 0; i < tcbtabsize; i++) {
1575 if (tcp->flags & TCB_INUSE)
1586 for (i = 0; i < tcbtabsize; i++) {
1587 struct tcb *tcp = tcbtab[i];
1588 if (tcp->pfd != pfd)
1590 if (tcp->flags & TCB_INUSE)
1596 #endif /* USE_PROCFS */
1599 droptcb(struct tcb *tcp)
1606 fprintf(stderr, "dropped tcb for pid %d, %d remain\n", tcp->pid, nprocs);
1608 if (tcp->pfd != -1) {
1612 if (tcp->pfd_reg != -1) {
1613 close(tcp->pfd_reg);
1616 if (tcp->pfd_status != -1) {
1617 close(tcp->pfd_status);
1618 tcp->pfd_status = -1;
1620 #endif /* !FREEBSD */
1622 tcp->flags = 0; /* rebuild_pollv needs it */
1627 if (outfname && followfork > 1 && tcp->outf)
1630 memset(tcp, 0, sizeof(*tcp));
1633 /* detach traced process; continue with sig
1634 Never call DETACH twice on the same process as both unattached and
1635 attached-unstopped processes give the same ESRCH. For unattached process we
1636 would SIGSTOP it and wait for its SIGSTOP notification forever. */
1639 detach(struct tcb *tcp, int sig)
1643 int status, catch_sigstop;
1646 if (tcp->flags & TCB_BPTSET)
1651 * Linux wrongly insists the child be stopped
1652 * before detaching. Arghh. We go through hoops
1653 * to make a clean break of things.
1656 #undef PTRACE_DETACH
1657 #define PTRACE_DETACH PTRACE_SUNDETACH
1660 * On TCB_STARTUP we did PTRACE_ATTACH but still did not get the
1661 * expected SIGSTOP. We must catch exactly one as otherwise the
1662 * detached process would be left stopped (process state T).
1664 catch_sigstop = (tcp->flags & TCB_STARTUP);
1665 if ((error = ptrace(PTRACE_DETACH, tcp->pid, (char *) 1, sig)) == 0) {
1666 /* On a clear day, you can see forever. */
1668 else if (errno != ESRCH) {
1669 /* Shouldn't happen. */
1670 perror("detach: ptrace(PTRACE_DETACH, ...)");
1672 else if (my_tkill(tcp->pid, 0) < 0) {
1674 perror("detach: checking sanity");
1676 else if (!catch_sigstop && my_tkill(tcp->pid, SIGSTOP) < 0) {
1678 perror("detach: stopping child");
1682 if (catch_sigstop) {
1685 if (wait4(tcp->pid, &status, __WALL, NULL) < 0) {
1686 if (errno == ECHILD) /* Already gone. */
1688 if (errno != EINVAL) {
1689 perror("detach: waiting");
1693 /* No __WALL here. */
1694 if (waitpid(tcp->pid, &status, 0) < 0) {
1695 if (errno != ECHILD) {
1696 perror("detach: waiting");
1700 /* If no processes, try clones. */
1701 if (wait4(tcp->pid, &status, __WCLONE,
1703 if (errno != ECHILD)
1704 perror("detach: waiting");
1707 #endif /* __WCLONE */
1712 if (!WIFSTOPPED(status)) {
1713 /* Au revoir, mon ami. */
1716 if (WSTOPSIG(status) == SIGSTOP) {
1717 ptrace_restart(PTRACE_DETACH, tcp, sig);
1720 error = ptrace_restart(PTRACE_CONT, tcp,
1721 WSTOPSIG(status) == syscall_trap_sig ? 0
1722 : WSTOPSIG(status));
1730 /* PTRACE_DETACH won't respect `sig' argument, so we post it here. */
1731 if (sig && kill(tcp->pid, sig) < 0)
1732 perror("detach: kill");
1734 error = ptrace_restart(PTRACE_DETACH, tcp, sig);
1738 fprintf(stderr, "Process %u detached\n", tcp->pid);
1747 static void reaper(int sig)
1752 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
1756 #endif /* USE_PROCFS */
1764 for (i = 0; i < tcbtabsize; i++) {
1766 if (!(tcp->flags & TCB_INUSE))
1770 "cleanup: looking at pid %u\n", tcp->pid);
1772 (!outfname || followfork < 2 || tcp_last == tcp)) {
1773 tprintf(" <unfinished ...>");
1776 if (tcp->flags & TCB_ATTACHED)
1779 kill(tcp->pid, SIGCONT);
1780 kill(tcp->pid, SIGTERM);
1793 #ifndef HAVE_STRERROR
1795 #if !HAVE_DECL_SYS_ERRLIST
1796 extern int sys_nerr;
1797 extern char *sys_errlist[];
1798 #endif /* HAVE_DECL_SYS_ERRLIST */
1801 strerror(int err_no)
1803 static char buf[64];
1805 if (err_no < 1 || err_no >= sys_nerr) {
1806 sprintf(buf, "Unknown error %d", err_no);
1809 return sys_errlist[err_no];
1812 #endif /* HAVE_STERRROR */
1814 #ifndef HAVE_STRSIGNAL
1816 #if defined HAVE_SYS_SIGLIST && !defined HAVE_DECL_SYS_SIGLIST
1817 extern char *sys_siglist[];
1819 #if defined HAVE_SYS__SIGLIST && !defined HAVE_DECL__SYS_SIGLIST
1820 extern char *_sys_siglist[];
1826 static char buf[64];
1828 if (sig < 1 || sig >= NSIG) {
1829 sprintf(buf, "Unknown signal %d", sig);
1832 #ifdef HAVE__SYS_SIGLIST
1833 return _sys_siglist[sig];
1835 return sys_siglist[sig];
1839 #endif /* HAVE_STRSIGNAL */
1850 pollv = (struct pollfd *) malloc(nprocs * sizeof pollv[0]);
1851 if (pollv == NULL) {
1852 error_msg_and_die("Out of memory");
1855 for (i = j = 0; i < tcbtabsize; i++) {
1856 struct tcb *tcp = tcbtab[i];
1857 if (!(tcp->flags & TCB_INUSE))
1859 pollv[j].fd = tcp->pfd;
1860 pollv[j].events = POLLWANT;
1864 error_msg_and_die("proc miscount");
1868 #ifndef HAVE_POLLABLE_PROCFS
1871 proc_poll_open(void)
1875 if (pipe(proc_poll_pipe) < 0) {
1876 perror_msg_and_die("pipe");
1878 for (i = 0; i < 2; i++) {
1879 set_cloexec_flag(proc_poll_pipe[i]);
1884 proc_poll(struct pollfd *pollv, int nfds, int timeout)
1888 struct proc_pollfd pollinfo;
1890 if ((n = read(proc_poll_pipe[0], &pollinfo, sizeof(pollinfo))) < 0)
1892 if (n != sizeof(struct proc_pollfd)) {
1893 error_msg_and_die("panic: short read: %d", n);
1895 for (i = 0; i < nprocs; i++) {
1896 if (pollv[i].fd == pollinfo.fd)
1897 pollv[i].revents = pollinfo.revents;
1899 pollv[i].revents = 0;
1901 poller_pid = pollinfo.pid;
1906 wakeup_handler(int sig)
1911 proc_poller(int pfd)
1913 struct proc_pollfd pollinfo;
1914 struct sigaction sa;
1915 sigset_t blocked_set, empty_set;
1920 struct procfs_status pfs;
1921 #endif /* FREEBSD */
1925 perror_msg_and_die("fork");
1932 sa.sa_handler = interactive ? SIG_DFL : SIG_IGN;
1934 sigemptyset(&sa.sa_mask);
1935 sigaction(SIGHUP, &sa, NULL);
1936 sigaction(SIGINT, &sa, NULL);
1937 sigaction(SIGQUIT, &sa, NULL);
1938 sigaction(SIGPIPE, &sa, NULL);
1939 sigaction(SIGTERM, &sa, NULL);
1940 sa.sa_handler = wakeup_handler;
1941 sigaction(SIGUSR1, &sa, NULL);
1942 sigemptyset(&blocked_set);
1943 sigaddset(&blocked_set, SIGUSR1);
1944 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
1945 sigemptyset(&empty_set);
1947 if (getrlimit(RLIMIT_NOFILE, &rl) < 0) {
1948 perror_msg_and_die("getrlimit(RLIMIT_NOFILE, ...)");
1951 for (i = 0; i < n; i++) {
1952 if (i != pfd && i != proc_poll_pipe[1])
1957 pollinfo.pid = getpid();
1960 if (ioctl(pfd, PIOCWSTOP, NULL) < 0)
1962 if (ioctl(pfd, PIOCWSTOP, &pfs) < 0)
1969 pollinfo.revents = POLLERR;
1972 pollinfo.revents = POLLHUP;
1975 perror("proc_poller: PIOCWSTOP");
1977 write(proc_poll_pipe[1], &pollinfo, sizeof(pollinfo));
1980 pollinfo.revents = POLLWANT;
1981 write(proc_poll_pipe[1], &pollinfo, sizeof(pollinfo));
1982 sigsuspend(&empty_set);
1986 #endif /* !HAVE_POLLABLE_PROCFS */
1996 if (followfork < 2 &&
1997 last < nprocs && (pollv[last].revents & POLLWANT)) {
1999 * The previous process is ready to run again. We'll
2000 * let it do so if it is currently in a syscall. This
2001 * heuristic improves the readability of the trace.
2003 tcp = pfd2tcb(pollv[last].fd);
2004 if (tcp && (tcp->flags & TCB_INSYSCALL))
2005 return pollv[last].fd;
2008 for (i = 0; i < nprocs; i++) {
2009 /* Let competing children run round robin. */
2010 j = (i + last + 1) % nprocs;
2011 if (pollv[j].revents & (POLLHUP | POLLERR)) {
2012 tcp = pfd2tcb(pollv[j].fd);
2014 error_msg_and_die("lost proc");
2019 if (pollv[j].revents & POLLWANT) {
2024 error_msg_and_die("nothing ready");
2031 struct tcb *in_syscall = NULL;
2036 int ioctl_result = 0, ioctl_errno = 0;
2041 sigprocmask(SIG_SETMASK, &empty_set, NULL);
2048 #ifndef HAVE_POLLABLE_PROCFS
2049 if (proc_poll_pipe[0] == -1) {
2051 tcp = first_used_tcb();
2058 #ifndef HAVE_POLLABLE_PROCFS
2060 /* fall through ... */
2061 #endif /* !HAVE_POLLABLE_PROCFS */
2063 #ifdef HAVE_POLLABLE_PROCFS
2065 /* On some systems (e.g. UnixWare) we get too much ugly
2066 "unfinished..." stuff when multiple proceses are in
2067 syscalls. Here's a nasty hack */
2074 pv.events = POLLWANT;
2075 if ((what = poll(&pv, 1, 1)) < 0) {
2080 else if (what == 1 && pv.revents & POLLWANT) {
2086 if (poll(pollv, nprocs, INFTIM) < 0) {
2091 #else /* !HAVE_POLLABLE_PROCFS */
2092 if (proc_poll(pollv, nprocs, INFTIM) < 0) {
2097 #endif /* !HAVE_POLLABLE_PROCFS */
2104 /* Look up `pfd' in our table. */
2105 if ((tcp = pfd2tcb(pfd)) == NULL) {
2106 error_msg_and_die("unknown pfd: %u", pfd);
2111 /* Get the status of the process. */
2114 ioctl_result = IOCTL_WSTOP(tcp);
2116 /* Thanks to some scheduling mystery, the first poller
2117 sometimes waits for the already processed end of fork
2118 event. Doing a non blocking poll here solves the problem. */
2119 if (proc_poll_pipe[0] != -1)
2120 ioctl_result = IOCTL_STATUS(tcp);
2122 ioctl_result = IOCTL_WSTOP(tcp);
2123 #endif /* FREEBSD */
2124 ioctl_errno = errno;
2125 #ifndef HAVE_POLLABLE_PROCFS
2126 if (proc_poll_pipe[0] != -1) {
2127 if (ioctl_result < 0)
2128 kill(poller_pid, SIGKILL);
2130 kill(poller_pid, SIGUSR1);
2132 #endif /* !HAVE_POLLABLE_PROCFS */
2138 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
2140 if (ioctl_result < 0) {
2141 /* Find out what happened if it failed. */
2142 switch (ioctl_errno) {
2153 perror_msg_and_die("PIOCWSTOP");
2158 if ((tcp->flags & TCB_STARTUP) && (tcp->status.PR_WHY == PR_SYSEXIT)) {
2159 /* discard first event for a syscall we never entered */
2160 IOCTL(tcp->pfd, PIOCRUN, 0);
2165 /* clear the just started flag */
2166 tcp->flags &= ~TCB_STARTUP;
2168 /* set current output file */
2170 curcol = tcp->curcol;
2173 struct timeval stime;
2178 if ((len = pread(tcp->pfd_status, buf, sizeof(buf) - 1, 0)) > 0) {
2181 "%*s %*d %*d %*d %*d %*d,%*d %*s %*d,%*d %*d,%*d %ld,%ld",
2182 &stime.tv_sec, &stime.tv_usec);
2184 stime.tv_sec = stime.tv_usec = 0;
2185 #else /* !FREEBSD */
2186 stime.tv_sec = tcp->status.pr_stime.tv_sec;
2187 stime.tv_usec = tcp->status.pr_stime.tv_nsec/1000;
2188 #endif /* !FREEBSD */
2189 tv_sub(&tcp->dtime, &stime, &tcp->stime);
2192 what = tcp->status.PR_WHAT;
2193 switch (tcp->status.PR_WHY) {
2196 if (tcp->status.PR_FLAGS & PR_ASLEEP) {
2197 tcp->status.PR_WHY = PR_SYSENTRY;
2198 if (trace_syscall(tcp) < 0) {
2199 error_msg_and_die("syscall trouble");
2203 #endif /* !FREEBSD */
2209 if (trace_syscall(tcp) < 0) {
2210 error_msg_and_die("syscall trouble");
2214 if (cflag != CFLAG_ONLY_STATS
2215 && (qual_flags[what] & QUAL_SIGNAL)) {
2217 tprintf("--- %s (%s) ---",
2218 signame(what), strsignal(what));
2221 if (tcp->status.PR_INFO.si_signo == what) {
2223 tprintf(" siginfo=");
2224 printsiginfo(&tcp->status.PR_INFO, 1);
2231 if (cflag != CFLAGS_ONLY_STATS
2232 && (qual_flags[what] & QUAL_FAULT)) {
2234 tprintf("=== FAULT %d ===", what);
2239 case 0: /* handle case we polled for nothing */
2243 error_msg_and_die("odd stop %d", tcp->status.PR_WHY);
2246 /* Remember current print column before continuing. */
2247 tcp->curcol = curcol;
2250 if (IOCTL(tcp->pfd, PIOCRUN, &arg) < 0)
2252 if (IOCTL(tcp->pfd, PIOCRUN, 0) < 0)
2255 perror_msg_and_die("PIOCRUN");
2261 #else /* !USE_PROCFS */
2272 struct rusage *rup = cflag ? &ru : NULL;
2274 static int wait4_options = __WALL;
2278 while (nprocs != 0) {
2282 sigprocmask(SIG_SETMASK, &empty_set, NULL);
2285 pid = wait4(-1, &status, wait4_options, rup);
2286 if (pid < 0 && (wait4_options & __WALL) && errno == EINVAL) {
2287 /* this kernel does not support __WALL */
2288 wait4_options &= ~__WALL;
2289 pid = wait4(-1, &status, wait4_options, rup);
2291 if (pid < 0 && !(wait4_options & __WALL) && errno == ECHILD) {
2292 /* most likely a "cloned" process */
2293 pid = wait4(-1, &status, __WCLONE, rup);
2295 perror_msg("wait4(__WCLONE) failed");
2299 pid = wait4(-1, &status, 0, rup);
2300 # endif /* __WALL */
2303 pid = wait(&status);
2307 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
2310 switch (wait_errno) {
2315 * We would like to verify this case
2316 * but sometimes a race in Solbourne's
2317 * version of SunOS sometimes reports
2318 * ECHILD before sending us SIGCHILD.
2323 perror("strace: wait");
2327 if (pid == popen_pid) {
2328 if (WIFEXITED(status) || WIFSIGNALED(status))
2333 char buf[sizeof("WIFEXITED,exitcode=%u") + sizeof(int)*3 /*paranoia:*/ + 16];
2335 unsigned ev = (unsigned)status >> 16;
2337 static const char *const event_names[] = {
2338 [PTRACE_EVENT_CLONE] = "CLONE",
2339 [PTRACE_EVENT_FORK] = "FORK",
2340 [PTRACE_EVENT_VFORK] = "VFORK",
2341 [PTRACE_EVENT_VFORK_DONE] = "VFORK_DONE",
2342 [PTRACE_EVENT_EXEC] = "EXEC",
2343 [PTRACE_EVENT_EXIT] = "EXIT",
2346 if (ev < ARRAY_SIZE(event_names))
2347 e = event_names[ev];
2349 sprintf(buf, "?? (%u)", ev);
2352 fprintf(stderr, " PTRACE_EVENT_%s", e);
2356 if (WIFSIGNALED(status))
2358 sprintf(buf, "WIFSIGNALED,%ssig=%s",
2359 WCOREDUMP(status) ? "core," : "",
2360 signame(WTERMSIG(status)));
2362 sprintf(buf, "WIFSIGNALED,sig=%s",
2363 signame(WTERMSIG(status)));
2365 if (WIFEXITED(status))
2366 sprintf(buf, "WIFEXITED,exitcode=%u", WEXITSTATUS(status));
2367 if (WIFSTOPPED(status))
2368 sprintf(buf, "WIFSTOPPED,sig=%s", signame(WSTOPSIG(status)));
2370 if (WIFCONTINUED(status))
2371 strcpy(buf, "WIFCONTINUED");
2373 fprintf(stderr, " [wait(0x%04x) = %u] %s\n", status, pid, buf);
2376 /* Look up `pid' in our table. */
2377 if ((tcp = pid2tcb(pid)) == NULL) {
2380 /* This is needed to go with the CLONE_PTRACE
2381 changes in process.c/util.c: we might see
2382 the child's initial trap before we see the
2383 parent return from the clone syscall.
2384 Leave the child suspended until the parent
2385 returns from its system call. Only then
2386 will we have the association of parent and
2387 child so that we know how to do clearbpt
2389 tcp = alloctcb(pid);
2390 tcp->flags |= TCB_ATTACHED;
2392 fprintf(stderr, "Process %d attached\n",
2396 /* This can happen if a clone call used
2397 CLONE_PTRACE itself. */
2400 if (WIFSTOPPED(status))
2401 ptrace(PTRACE_CONT, pid, (char *) 1, 0);
2402 error_msg_and_die("Unknown pid: %u", pid);
2405 /* set current output file */
2407 curcol = tcp->curcol;
2410 tv_sub(&tcp->dtime, &ru.ru_stime, &tcp->stime);
2411 tcp->stime = ru.ru_stime;
2415 if (WIFSIGNALED(status)) {
2416 if (pid == strace_child)
2417 exit_code = 0x100 | WTERMSIG(status);
2418 if (cflag != CFLAG_ONLY_STATS
2419 && (qual_flags[WTERMSIG(status)] & QUAL_SIGNAL)) {
2422 tprintf("+++ killed by %s %s+++",
2423 signame(WTERMSIG(status)),
2424 WCOREDUMP(status) ? "(core dumped) " : "");
2426 tprintf("+++ killed by %s +++",
2427 signame(WTERMSIG(status)));
2434 if (WIFEXITED(status)) {
2435 if (pid == strace_child)
2436 exit_code = WEXITSTATUS(status);
2437 if (tcp == tcp_last) {
2438 if ((tcp->flags & (TCB_INSYSCALL|TCB_REPRINT)) == TCB_INSYSCALL)
2439 tprintf(" <unfinished ... exit status %d>\n",
2440 WEXITSTATUS(status));
2443 if (!cflag /* && (qual_flags[WTERMSIG(status)] & QUAL_SIGNAL) */ ) {
2445 tprintf("+++ exited with %d +++", WEXITSTATUS(status));
2451 if (!WIFSTOPPED(status)) {
2452 fprintf(stderr, "PANIC: pid %u not stopped\n", pid);
2458 /* Ptrace event (we ignore all of them for now) */
2463 * Interestingly, the process may stop
2464 * with STOPSIG equal to some other signal
2465 * than SIGSTOP if we happend to attach
2466 * just before the process takes a signal.
2467 * A no-MMU vforked child won't send up a signal,
2468 * so skip the first (lost) execve notification.
2470 if ((tcp->flags & TCB_STARTUP) &&
2471 (WSTOPSIG(status) == SIGSTOP || strace_vforked)) {
2473 * This flag is there to keep us in sync.
2474 * Next time this process stops it should
2475 * really be entering a system call.
2477 tcp->flags &= ~TCB_STARTUP;
2478 if (tcp->flags & TCB_BPTSET) {
2480 * One example is a breakpoint inherited from
2481 * parent through fork ().
2483 if (clearbpt(tcp) < 0) /* Pretty fatal */ {
2490 if (ptrace_setoptions) {
2492 fprintf(stderr, "setting opts %x on pid %d\n", ptrace_setoptions, tcp->pid);
2493 if (ptrace(PTRACE_SETOPTIONS, tcp->pid, NULL, ptrace_setoptions) < 0) {
2494 if (errno != ESRCH) {
2495 /* Should never happen, really */
2496 perror_msg_and_die("PTRACE_SETOPTIONS");
2504 if (WSTOPSIG(status) != syscall_trap_sig) {
2505 if (WSTOPSIG(status) == SIGSTOP &&
2506 (tcp->flags & TCB_SIGTRAPPED)) {
2508 * Trapped attempt to block SIGTRAP
2509 * Hope we are back in control now.
2511 tcp->flags &= ~(TCB_INSYSCALL | TCB_SIGTRAPPED);
2512 if (ptrace_restart(PTRACE_SYSCALL, tcp, 0) < 0) {
2518 if (cflag != CFLAG_ONLY_STATS
2519 && (qual_flags[WSTOPSIG(status)] & QUAL_SIGNAL)) {
2521 #if defined(PT_CR_IPSR) && defined(PT_CR_IIP)
2525 upeek(tcp, PT_CR_IPSR, &psr);
2526 upeek(tcp, PT_CR_IIP, &pc);
2529 pc += (psr >> PSR_RI) & 0x3;
2530 # define PC_FORMAT_STR " @ %lx"
2531 # define PC_FORMAT_ARG pc
2533 # define PC_FORMAT_STR "%s"
2534 # define PC_FORMAT_ARG ""
2537 if (ptrace(PTRACE_GETSIGINFO, pid, 0, &si) == 0) {
2539 printsiginfo(&si, verbose(tcp));
2540 tprintf(" (%s)" PC_FORMAT_STR " ---",
2541 strsignal(WSTOPSIG(status)),
2544 tprintf("--- %s by %s" PC_FORMAT_STR " ---",
2545 strsignal(WSTOPSIG(status)),
2546 signame(WSTOPSIG(status)),
2550 if (ptrace_restart(PTRACE_SYSCALL, tcp, WSTOPSIG(status)) < 0) {
2556 /* we handled the STATUS, we are permitted to interrupt now. */
2559 if (trace_syscall(tcp) < 0 && !tcp->ptrace_errno) {
2560 /* ptrace() failed in trace_syscall() with ESRCH.
2561 * Likely a result of process disappearing mid-flight.
2562 * Observed case: exit_group() terminating
2563 * all processes in thread group. In this case, threads
2564 * "disappear" in an unpredictable moment without any
2565 * notification to strace via wait().
2567 if (tcp->flags & TCB_ATTACHED) {
2569 /* Do we have dangling line "syscall(param, param"?
2570 * Finish the line then.
2572 tcp_last->flags |= TCB_REPRINT;
2573 tprintf(" <unfinished ...>");
2579 tcp->pid, (char *) 1, SIGTERM);
2585 /* Remember current print column before continuing. */
2586 tcp->curcol = curcol;
2587 if (ptrace_restart(PTRACE_SYSCALL, tcp, 0) < 0) {
2595 #endif /* !USE_PROCFS */
2598 tprintf(const char *fmt, ...)
2602 va_start(args, fmt);
2604 int n = vfprintf(outf, fmt, args);
2607 perror(outfname == NULL
2608 ? "<writing to pipe>" : outfname);
2617 printleader(struct tcb *tcp)
2620 if (tcp_last->ptrace_errno) {
2621 if (tcp_last->flags & TCB_INSYSCALL) {
2622 tprintf(" <unavailable>) ");
2625 tprintf("= ? <unavailable>\n");
2626 tcp_last->ptrace_errno = 0;
2627 } else if (!outfname || followfork < 2 || tcp_last == tcp) {
2628 tcp_last->flags |= TCB_REPRINT;
2629 tprintf(" <unfinished ...>\n");
2633 if ((followfork == 1 || pflag_seen > 1) && outfname)
2634 tprintf("%-5d ", tcp->pid);
2635 else if (nprocs > 1 && !outfname)
2636 tprintf("[pid %5u] ", tcp->pid);
2638 char str[sizeof("HH:MM:SS")];
2639 struct timeval tv, dtv;
2640 static struct timeval otv;
2642 gettimeofday(&tv, NULL);
2644 if (otv.tv_sec == 0)
2646 tv_sub(&dtv, &tv, &otv);
2647 tprintf("%6ld.%06ld ",
2648 (long) dtv.tv_sec, (long) dtv.tv_usec);
2651 else if (tflag > 2) {
2652 tprintf("%ld.%06ld ",
2653 (long) tv.tv_sec, (long) tv.tv_usec);
2656 time_t local = tv.tv_sec;
2657 strftime(str, sizeof(str), "%T", localtime(&local));
2659 tprintf("%s.%06ld ", str, (long) tv.tv_usec);
2661 tprintf("%s ", str);
2672 tprintf("%*s", col - curcol, "");
2682 #ifdef HAVE_MP_PROCFS
2685 mp_ioctl(int fd, int cmd, void *arg, int size)
2687 struct iovec iov[2];
2690 iov[0].iov_base = &cmd;
2691 iov[0].iov_len = sizeof cmd;
2694 iov[1].iov_base = arg;
2695 iov[1].iov_len = size;
2698 return writev(fd, iov, n);