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>
50 # include <asm/unistd.h>
51 # if defined __NR_tkill
52 # define my_tkill(tid, sig) syscall(__NR_tkill, (tid), (sig))
54 /* kill() may choose arbitrarily the target task of the process group
55 while we later wait on a that specific TID. PID process waits become
56 TID task specific waits for a process under ptrace(2). */
57 # warning "Neither tkill(2) nor tgkill(2) available, risk of strace hangs!"
58 # define my_tkill(tid, sig) kill((tid), (sig))
62 #if defined(IA64) && defined(LINUX)
63 # include <asm/ptrace_offsets.h>
71 #include <sys/stropts.h>
78 extern char **environ;
83 int debug = 0, followfork = 0;
84 unsigned int ptrace_setoptions = 0;
85 /* Which WSTOPSIG(status) value marks syscall traps? */
86 static unsigned int syscall_trap_sig = SIGTRAP;
87 int dtime = 0, xflag = 0, qflag = 0;
88 cflag_t cflag = CFLAG_NONE;
89 static int iflag = 0, pflag_seen = 0, rflag = 0, tflag = 0;
90 static int interactive = 1;
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 max_strlen = DEFAULT_STRLEN;
123 static int acolumn = DEFAULT_ACOLUMN;
124 static char *acolumn_spaces;
125 static char *outfname = NULL;
128 static struct tcb **tcbtab;
129 static unsigned int nprocs, tcbtabsize;
130 static const char *progname;
132 static int detach(struct tcb *tcp);
133 static int trace(void);
134 static void cleanup(void);
135 static void interrupt(int sig);
136 static sigset_t empty_set, blocked_set;
138 #ifdef HAVE_SIG_ATOMIC_T
139 static volatile sig_atomic_t interrupted;
140 #else /* !HAVE_SIG_ATOMIC_T */
141 static volatile int interrupted;
142 #endif /* !HAVE_SIG_ATOMIC_T */
146 static struct tcb *pfd2tcb(int pfd);
147 static void reaper(int sig);
148 static void rebuild_pollv(void);
149 static struct pollfd *pollv;
151 #ifndef HAVE_POLLABLE_PROCFS
153 static void proc_poll_open(void);
154 static void proc_poller(int pfd);
162 static int poller_pid;
163 static int proc_poll_pipe[2] = { -1, -1 };
165 #endif /* !HAVE_POLLABLE_PROCFS */
167 #ifdef HAVE_MP_PROCFS
168 #define POLLWANT POLLWRNORM
170 #define POLLWANT POLLPRI
172 #endif /* USE_PROCFS */
175 usage(FILE *ofp, int exitval)
178 usage: strace [-CdDffhiqrtttTvVxxy] [-a column] [-e expr] ... [-o file]\n\
179 [-p pid] ... [-s strsize] [-u username] [-E var=val] ...\n\
180 [-P path] [command [arg ...]]\n\
181 or: strace -c [-D] [-e expr] ... [-O overhead] [-S sortby] [-E var=val] ...\n\
182 [command [arg ...]]\n\
183 -c -- count time, calls, and errors for each syscall and report summary\n\
184 -C -- like -c but also print regular output while processes are running\n\
185 -f -- follow forks, -ff -- with output into separate files\n\
186 -F -- attempt to follow vforks, -h -- print help message\n\
187 -i -- print instruction pointer at time of syscall\n\
188 -q -- suppress messages about attaching, detaching, etc.\n\
189 -r -- print relative timestamp, -t -- absolute timestamp, -tt -- with usecs\n\
190 -T -- print time spent in each syscall, -V -- print version\n\
191 -v -- verbose mode: print unabbreviated argv, stat, termio[s], etc. args\n\
192 -x -- print non-ascii strings in hex, -xx -- print all strings in hex\n\
193 -y -- print paths associated with file descriptor arguments\n\
194 -a column -- alignment COLUMN for printing syscall results (default %d)\n\
195 -e expr -- a qualifying expression: option=[!]all or option=[!]val1[,val2]...\n\
196 options: trace, abbrev, verbose, raw, signal, read, or write\n\
197 -o file -- send trace output to FILE instead of stderr\n\
198 -O overhead -- set overhead for tracing syscalls to OVERHEAD usecs\n\
199 -p pid -- trace process with process id PID, may be repeated\n\
200 -D -- run tracer process as a detached grandchild, not as parent\n\
201 -s strsize -- limit length of print strings to STRSIZE chars (default %d)\n\
202 -S sortby -- sort syscall counts by: time, calls, name, nothing (default %s)\n\
203 -u username -- run command as username handling setuid and/or setgid\n\
204 -E var=val -- put var=val in the environment for command\n\
205 -E var -- remove var from the environment for command\n\
206 -P path -- trace accesses to path\n\
207 " /* this is broken, so don't document it
208 -z -- print only succeeding syscalls\n\
210 , DEFAULT_ACOLUMN, DEFAULT_STRLEN, DEFAULT_SORTBY);
214 static void die(void) __attribute__ ((noreturn));
215 static void die(void)
217 if (strace_tracer_pid == getpid()) {
224 static void verror_msg(int err_no, const char *fmt, va_list p)
230 /* We want to print entire message with single fprintf to ensure
231 * message integrity if stderr is shared with other programs.
232 * Thus we use vasprintf + single fprintf.
235 vasprintf(&msg, fmt, p);
238 fprintf(stderr, "%s: %s: %s\n", progname, msg, strerror(err_no));
240 fprintf(stderr, "%s: %s\n", progname, msg);
243 /* malloc in vasprintf failed, try it without malloc */
244 fprintf(stderr, "%s: ", progname);
245 vfprintf(stderr, fmt, p);
247 fprintf(stderr, ": %s\n", strerror(err_no));
251 /* We don't switch stderr to buffered, thus fprintf(stderr)
252 * always flushes its output and this is not necessary: */
253 /* fflush(stderr); */
256 void error_msg(const char *fmt, ...)
260 verror_msg(0, fmt, p);
264 void error_msg_and_die(const char *fmt, ...)
268 verror_msg(0, fmt, p);
272 void perror_msg(const char *fmt, ...)
276 verror_msg(errno, fmt, p);
280 void perror_msg_and_die(const char *fmt, ...)
284 verror_msg(errno, fmt, p);
288 void die_out_of_memory(void)
290 static bool recursed = 0;
294 error_msg_and_die("Out of memory");
306 /* Glue for systems without a MMU that cannot provide fork() */
308 # define strace_vforked 0
310 # define strace_vforked 1
311 # define fork() vfork()
315 set_cloexec_flag(int fd)
319 flags = fcntl(fd, F_GETFD);
321 /* Can happen only if fd is bad.
322 * Should never happen: if it does, we have a bug
323 * in the caller. Therefore we just abort
324 * instead of propagating the error.
326 perror_msg_and_die("fcntl(%d, F_GETFD)", fd);
329 newflags = flags | FD_CLOEXEC;
330 if (flags == newflags)
333 fcntl(fd, F_SETFD, newflags); /* never fails */
337 * When strace is setuid executable, we have to swap uids
338 * before and after filesystem and process management operations.
344 int euid = geteuid(), uid = getuid();
346 if (euid != uid && setreuid(euid, uid) < 0) {
347 perror_msg_and_die("setreuid");
353 # define fopen_for_output fopen64
355 # define fopen_for_output fopen
359 strace_fopen(const char *path)
364 fp = fopen_for_output(path, "w");
366 perror_msg_and_die("Can't fopen '%s'", path);
368 set_cloexec_flag(fileno(fp));
372 static int popen_pid = 0;
375 # define _PATH_BSHELL "/bin/sh"
379 * We cannot use standard popen(3) here because we have to distinguish
380 * popen child process from other processes we trace, and standard popen(3)
381 * does not export its child's pid.
384 strace_popen(const char *command)
391 perror_msg_and_die("pipe");
393 set_cloexec_flag(fds[1]); /* never fails */
397 perror_msg_and_die("vfork");
399 if (popen_pid == 0) {
404 perror_msg_and_die("dup2");
407 execl(_PATH_BSHELL, "sh", "-c", command, NULL);
408 perror_msg_and_die("Can't execute '%s'", _PATH_BSHELL);
414 fp = fdopen(fds[1], "w");
421 newoutf(struct tcb *tcp)
423 if (outfname && followfork > 1) {
424 char name[520 + sizeof(int) * 3];
425 sprintf(name, "%.512s.%u", outfname, tcp->pid);
426 tcp->outf = strace_fopen(name);
437 * Block user interruptions as we would leave the traced
438 * process stopped (process state T) if we would terminate in
439 * between PTRACE_ATTACH and wait4() on SIGSTOP.
440 * We rely on cleanup() from this point on.
443 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
445 if (daemonized_tracer) {
448 perror_msg_and_die("fork");
450 if (pid) { /* parent */
452 * Wait for grandchild to attach to straced process
453 * (grandparent). Grandchild SIGKILLs us after it attached.
454 * Grandparent's wait() is unblocked by our death,
455 * it proceeds to exec the straced program.
458 _exit(0); /* paranoia */
461 /* We will be the tracer process. Remember our new pid: */
462 strace_tracer_pid = getpid();
465 for (tcbi = 0; tcbi < tcbtabsize; tcbi++) {
468 /* Is this a process we should attach to, but not yet attached? */
469 if ((tcp->flags & (TCB_ATTACHED | TCB_STARTUP)) != TCB_ATTACHED)
472 /* Reinitialize the output since it may have changed */
477 if (proc_open(tcp, 1) < 0) {
478 fprintf(stderr, "trouble opening proc file\n");
482 #else /* !USE_PROCFS */
484 if (followfork && !daemonized_tracer) {
485 char procdir[sizeof("/proc/%d/task") + sizeof(int) * 3];
488 sprintf(procdir, "/proc/%d/task", tcp->pid);
489 dir = opendir(procdir);
491 unsigned int ntid = 0, nerr = 0;
494 while ((de = readdir(dir)) != NULL) {
498 if (de->d_fileno == 0)
500 tid = atoi(de->d_name);
504 if (ptrace(PTRACE_ATTACH, tid, (char *) 1, 0) < 0) {
507 fprintf(stderr, "attach to pid %d failed\n", tid);
511 fprintf(stderr, "attach to pid %d succeeded\n", tid);
514 cur_tcp = alloctcb(tid);
515 cur_tcp->flags |= TCB_ATTACHED | TCB_STARTUP | TCB_IGNORE_ONE_SIGSTOP;
519 sigprocmask(SIG_SETMASK, &empty_set, NULL);
522 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
526 perror("attach: ptrace(PTRACE_ATTACH, ...)");
531 fprintf(stderr, ntid > 1
532 ? "Process %u attached with %u threads - interrupt to quit\n"
533 : "Process %u attached - interrupt to quit\n",
536 if (!(tcp->flags & TCB_STARTUP)) {
537 /* -p PID, we failed to attach to PID itself
538 * but did attach to some of its sibling threads.
544 } /* if (opendir worked) */
547 if (ptrace(PTRACE_ATTACH, tcp->pid, (char *) 1, 0) < 0) {
548 perror("attach: ptrace(PTRACE_ATTACH, ...)");
552 tcp->flags |= TCB_STARTUP | TCB_IGNORE_ONE_SIGSTOP;
554 fprintf(stderr, "attach to pid %d (main) succeeded\n", tcp->pid);
556 if (daemonized_tracer) {
558 * It is our grandparent we trace, not a -p PID.
559 * Don't want to just detach on exit, so...
561 tcp->flags &= ~TCB_ATTACHED;
563 * Make parent go away.
564 * Also makes grandparent's wait() unblock.
566 kill(getppid(), SIGKILL);
569 #endif /* !USE_PROCFS */
572 "Process %u attached - interrupt to quit\n",
574 } /* for each tcbtab[] */
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_msg_and_die("exec");
596 strcpy(pathname, filename);
598 #ifdef USE_DEBUGGING_EXEC
600 * Debuggers customarily check the current directory
601 * first regardless of the path but doing that gives
602 * security geeks a panic attack.
604 else if (stat(filename, &statbuf) == 0)
605 strcpy(pathname, filename);
606 #endif /* USE_DEBUGGING_EXEC */
611 for (path = getenv("PATH"); path && *path; path += m) {
612 if (strchr(path, ':')) {
613 n = strchr(path, ':') - path;
617 m = n = strlen(path);
619 if (!getcwd(pathname, MAXPATHLEN))
621 len = strlen(pathname);
623 else if (n > sizeof pathname - 1)
626 strncpy(pathname, path, n);
629 if (len && pathname[len - 1] != '/')
630 pathname[len++] = '/';
631 strcpy(pathname + len, filename);
632 if (stat(pathname, &statbuf) == 0 &&
633 /* Accept only regular files
634 with some execute bits set.
635 XXX not perfect, might still fail */
636 S_ISREG(statbuf.st_mode) &&
637 (statbuf.st_mode & 0111))
641 if (stat(pathname, &statbuf) < 0) {
642 perror_msg_and_die("Can't stat '%s'", filename);
644 strace_child = pid = fork();
646 perror_msg_and_die("fork");
648 if ((pid != 0 && daemonized_tracer) /* -D: parent to become a traced process */
649 || (pid == 0 && !daemonized_tracer) /* not -D: child to become a traced process */
656 /* Kludge for SGI, see proc_open for details. */
657 sa.sa_handler = foobar;
659 sigemptyset(&sa.sa_mask);
660 sigaction(SIGINT, &sa, NULL);
667 #else /* !USE_PROCFS */
668 if (!daemonized_tracer) {
669 if (ptrace(PTRACE_TRACEME, 0, (char *) 1, 0) < 0) {
670 perror_msg_and_die("ptrace(PTRACE_TRACEME, ...)");
676 if (username != NULL) {
677 uid_t run_euid = run_uid;
678 gid_t run_egid = run_gid;
680 if (statbuf.st_mode & S_ISUID)
681 run_euid = statbuf.st_uid;
682 if (statbuf.st_mode & S_ISGID)
683 run_egid = statbuf.st_gid;
685 * It is important to set groups before we
686 * lose privileges on setuid.
688 if (initgroups(username, run_gid) < 0) {
689 perror_msg_and_die("initgroups");
691 if (setregid(run_gid, run_egid) < 0) {
692 perror_msg_and_die("setregid");
694 if (setreuid(run_uid, run_euid) < 0) {
695 perror_msg_and_die("setreuid");
698 else if (geteuid() != 0)
699 setreuid(run_uid, run_uid);
701 if (!daemonized_tracer) {
703 * Induce a ptrace stop. Tracer (our parent)
704 * will resume us with PTRACE_SYSCALL and display
705 * the immediately following execve syscall.
706 * Can't do this on NOMMU systems, we are after
707 * vfork: parent is blocked, stopping would deadlock.
712 struct sigaction sv_sigchld;
713 sigaction(SIGCHLD, NULL, &sv_sigchld);
715 * Make sure it is not SIG_IGN, otherwise wait
718 signal(SIGCHLD, SIG_DFL);
720 * Wait for grandchild to attach to us.
721 * It kills child after that, and wait() unblocks.
726 sigaction(SIGCHLD, &sv_sigchld, NULL);
728 #endif /* !USE_PROCFS */
730 execv(pathname, argv);
731 perror_msg_and_die("exec");
734 /* We are the tracer */
736 if (!daemonized_tracer) {
739 tcp->flags |= TCB_STARTUP | TCB_IGNORE_ONE_SIGSTOP;
741 tcp->flags |= TCB_STARTUP;
744 /* With -D, *we* are child here, IOW: different pid. Fetch it: */
745 strace_tracer_pid = getpid();
746 /* The tracee is our parent: */
749 /* We want subsequent startup_attach() to attach to it: */
750 tcp->flags |= TCB_ATTACHED;
753 if (proc_open(tcp, 0) < 0) {
754 perror_msg_and_die("trouble opening proc file");
760 static void kill_save_errno(pid_t pid, int sig)
762 int saved_errno = errno;
764 (void) kill(pid, sig);
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 |
783 perror_msg_and_die("fork");
786 if (ptrace(PTRACE_TRACEME, 0, 0, 0) < 0)
787 perror_msg_and_die("%s: PTRACE_TRACEME doesn't work",
791 perror_msg_and_die("fork");
796 int status, tracee_pid;
799 tracee_pid = wait(&status);
800 if (tracee_pid <= 0) {
803 else if (errno == ECHILD)
805 kill_save_errno(pid, SIGKILL);
806 perror_msg_and_die("%s: unexpected wait result %d",
807 __func__, tracee_pid);
809 if (WIFEXITED(status)) {
810 if (WEXITSTATUS(status)) {
811 if (tracee_pid != pid)
812 kill_save_errno(pid, SIGKILL);
813 error_msg_and_die("%s: unexpected exit status %u",
814 __func__, WEXITSTATUS(status));
818 if (WIFSIGNALED(status)) {
819 if (tracee_pid != pid)
820 kill_save_errno(pid, SIGKILL);
821 error_msg_and_die("%s: unexpected signal %u",
822 __func__, WTERMSIG(status));
824 if (!WIFSTOPPED(status)) {
825 if (tracee_pid != pid)
826 kill_save_errno(tracee_pid, SIGKILL);
828 error_msg_and_die("%s: unexpected wait status %x",
831 if (tracee_pid != pid) {
832 found_grandchild = tracee_pid;
833 if (ptrace(PTRACE_CONT, tracee_pid, 0, 0) < 0) {
834 kill_save_errno(tracee_pid, SIGKILL);
835 kill_save_errno(pid, SIGKILL);
836 perror_msg_and_die("PTRACE_CONT doesn't work");
840 switch (WSTOPSIG(status)) {
842 if (ptrace(PTRACE_SETOPTIONS, pid, 0, test_options) < 0
843 && errno != EINVAL && errno != EIO)
844 perror_msg("PTRACE_SETOPTIONS");
847 if (status >> 16 == PTRACE_EVENT_FORK) {
850 if (ptrace(PTRACE_GETEVENTMSG, pid,
851 NULL, (long) &msg) == 0)
852 expected_grandchild = msg;
856 if (ptrace(PTRACE_SYSCALL, pid, 0, 0) < 0) {
857 kill_save_errno(pid, SIGKILL);
858 perror_msg_and_die("PTRACE_SYSCALL doesn't work");
861 if (expected_grandchild && expected_grandchild == found_grandchild) {
862 ptrace_setoptions |= test_options;
864 fprintf(stderr, "ptrace_setoptions = %#x\n",
868 error_msg("Test for PTRACE_O_TRACECLONE failed, "
869 "giving up using this feature.");
873 * Test whether the kernel support PTRACE_O_TRACESYSGOOD.
874 * First fork a new child, call ptrace(PTRACE_SETOPTIONS) on it,
875 * and then see whether it will stop with (SIGTRAP | 0x80).
877 * Use of this option enables correct handling of user-generated SIGTRAPs,
878 * and SIGTRAPs generated by special instructions such as int3 on x86:
879 * _start: .globl _start
884 * (compile with: "gcc -nostartfiles -nostdlib -o int3 int3.S")
887 test_ptrace_setoptions_for_all(void)
889 const unsigned int test_options = PTRACE_O_TRACESYSGOOD |
896 perror_msg_and_die("fork");
900 if (ptrace(PTRACE_TRACEME, 0L, 0L, 0L) < 0)
901 /* Note: exits with exitcode 1 */
902 perror_msg_and_die("%s: PTRACE_TRACEME doesn't work",
905 _exit(0); /* parent should see entry into this syscall */
909 int status, tracee_pid;
912 tracee_pid = wait(&status);
913 if (tracee_pid <= 0) {
916 kill_save_errno(pid, SIGKILL);
917 perror_msg_and_die("%s: unexpected wait result %d",
918 __func__, tracee_pid);
920 if (WIFEXITED(status)) {
921 if (WEXITSTATUS(status) == 0)
923 error_msg_and_die("%s: unexpected exit status %u",
924 __func__, WEXITSTATUS(status));
926 if (WIFSIGNALED(status)) {
927 error_msg_and_die("%s: unexpected signal %u",
928 __func__, WTERMSIG(status));
930 if (!WIFSTOPPED(status)) {
932 error_msg_and_die("%s: unexpected wait status %x",
935 if (WSTOPSIG(status) == SIGSTOP) {
937 * We don't check "options aren't accepted" error.
938 * If it happens, we'll never get (SIGTRAP | 0x80),
939 * and thus will decide to not use the option.
940 * IOW: the outcome of the test will be correct.
942 if (ptrace(PTRACE_SETOPTIONS, pid, 0L, test_options) < 0
943 && errno != EINVAL && errno != EIO)
944 perror_msg("PTRACE_SETOPTIONS");
946 if (WSTOPSIG(status) == (SIGTRAP | 0x80)) {
949 if (ptrace(PTRACE_SYSCALL, pid, 0L, 0L) < 0) {
950 kill_save_errno(pid, SIGKILL);
951 perror_msg_and_die("PTRACE_SYSCALL doesn't work");
956 syscall_trap_sig = (SIGTRAP | 0x80);
957 ptrace_setoptions |= test_options;
959 fprintf(stderr, "ptrace_setoptions = %#x\n",
964 error_msg("Test for PTRACE_O_TRACESYSGOOD failed, "
965 "giving up using this feature.");
970 main(int argc, char *argv[])
977 progname = argv[0] ? argv[0] : "strace";
979 strace_tracer_pid = getpid();
981 /* Allocate the initial tcbtab. */
982 tcbtabsize = argc; /* Surely enough for all -p args. */
983 tcbtab = calloc(tcbtabsize, sizeof(tcbtab[0]));
986 tcp = calloc(tcbtabsize, sizeof(*tcp));
989 for (c = 0; c < tcbtabsize; c++)
993 set_sortby(DEFAULT_SORTBY);
994 set_personality(DEFAULT_PERSONALITY);
995 qualify("trace=all");
996 qualify("abbrev=all");
997 qualify("verbose=all");
998 qualify("signal=all");
999 while ((c = getopt(argc, argv,
1004 "a:e:o:O:p:s:S:u:E:P:")) != EOF) {
1007 if (cflag == CFLAG_BOTH) {
1008 error_msg_and_die("-c and -C are mutually exclusive options");
1010 cflag = CFLAG_ONLY_STATS;
1013 if (cflag == CFLAG_ONLY_STATS) {
1014 error_msg_and_die("-c and -C are mutually exclusive options");
1023 daemonized_tracer = 1;
1058 qualify("abbrev=none");
1061 printf("%s -- version %s\n", PACKAGE_NAME, VERSION);
1065 not_failing_only = 1;
1068 acolumn = atoi(optarg);
1070 error_msg_and_die("Bad column width '%s'", optarg);
1076 outfname = strdup(optarg);
1079 set_overhead(atoi(optarg));
1084 error_msg("Invalid process id: '%s'", optarg);
1087 if (pid == strace_tracer_pid) {
1088 error_msg("I'm sorry, I can't let you do that, Dave.");
1091 tcp = alloc_tcb(pid, 0);
1092 tcp->flags |= TCB_ATTACHED;
1097 if (pathtrace_select(optarg)) {
1098 error_msg_and_die("Failed to select path '%s'", optarg);
1102 max_strlen = atoi(optarg);
1103 if (max_strlen < 0) {
1104 error_msg_and_die("Invalid -s argument: '%s'", optarg);
1111 username = strdup(optarg);
1114 if (putenv(optarg) < 0)
1115 die_out_of_memory();
1123 acolumn_spaces = malloc(acolumn + 1);
1124 if (!acolumn_spaces)
1125 die_out_of_memory();
1126 memset(acolumn_spaces, ' ', acolumn);
1127 acolumn_spaces[acolumn] = '\0';
1129 if ((optind == argc) == !pflag_seen)
1132 if (pflag_seen && daemonized_tracer) {
1133 error_msg_and_die("-D and -p are mutually exclusive options");
1139 if (followfork > 1 && cflag) {
1140 error_msg_and_die("(-c or -C) and -ff are mutually exclusive options");
1143 /* See if they want to run as another user. */
1144 if (username != NULL) {
1145 struct passwd *pent;
1147 if (getuid() != 0 || geteuid() != 0) {
1148 error_msg_and_die("You must be root to use the -u option");
1150 pent = getpwnam(username);
1152 error_msg_and_die("Cannot find user '%s'", username);
1154 run_uid = pent->pw_uid;
1155 run_gid = pent->pw_gid;
1164 test_ptrace_setoptions_followfork();
1165 test_ptrace_setoptions_for_all();
1168 /* Check if they want to redirect the output. */
1170 /* See if they want to pipe the output. */
1171 if (outfname[0] == '|' || outfname[0] == '!') {
1173 * We can't do the <outfname>.PID funny business
1174 * when using popen, so prohibit it.
1177 error_msg_and_die("Piping the output and -ff are mutually exclusive");
1178 outf = strace_popen(outfname + 1);
1180 else if (followfork <= 1)
1181 outf = strace_fopen(outfname);
1184 if (!outfname || outfname[0] == '|' || outfname[0] == '!') {
1185 char *buf = malloc(BUFSIZ);
1187 die_out_of_memory();
1188 setvbuf(outf, buf, _IOLBF, BUFSIZ);
1190 if (outfname && optind < argc) {
1195 /* Valid states here:
1196 optind < argc pflag_seen outfname interactive
1203 /* STARTUP_CHILD must be called before the signal handlers get
1204 installed below as they are inherited into the spawned process.
1205 Also we do not need to be protected by them as during interruption
1206 in the STARTUP_CHILD mode we kill the spawned process anyway. */
1208 startup_child(&argv[optind]);
1210 sigemptyset(&empty_set);
1211 sigemptyset(&blocked_set);
1212 sa.sa_handler = SIG_IGN;
1213 sigemptyset(&sa.sa_mask);
1215 sigaction(SIGTTOU, &sa, NULL);
1216 sigaction(SIGTTIN, &sa, NULL);
1218 sigaddset(&blocked_set, SIGHUP);
1219 sigaddset(&blocked_set, SIGINT);
1220 sigaddset(&blocked_set, SIGQUIT);
1221 sigaddset(&blocked_set, SIGPIPE);
1222 sigaddset(&blocked_set, SIGTERM);
1223 sa.sa_handler = interrupt;
1225 /* POSIX signals on sunos4.1 are a little broken. */
1226 sa.sa_flags = SA_INTERRUPT;
1229 sigaction(SIGHUP, &sa, NULL);
1230 sigaction(SIGINT, &sa, NULL);
1231 sigaction(SIGQUIT, &sa, NULL);
1232 sigaction(SIGPIPE, &sa, NULL);
1233 sigaction(SIGTERM, &sa, NULL);
1235 sa.sa_handler = reaper;
1236 sigaction(SIGCHLD, &sa, NULL);
1238 /* Make sure SIGCHLD has the default action so that waitpid
1239 definitely works without losing track of children. The user
1240 should not have given us a bogus state to inherit, but he might
1241 have. Arguably we should detect SIG_IGN here and pass it on
1242 to children, but probably noone really needs that. */
1243 sa.sa_handler = SIG_DFL;
1244 sigaction(SIGCHLD, &sa, NULL);
1245 #endif /* USE_PROCFS */
1247 if (pflag_seen || daemonized_tracer)
1254 if (exit_code > 0xff) {
1255 /* Child was killed by a signal, mimic that. */
1257 signal(exit_code, SIG_DFL);
1259 /* Paranoia - what if this signal is not fatal?
1260 Exit with 128 + signo then. */
1269 /* Allocate some more TCBs and expand the table.
1270 We don't want to relocate the TCBs because our
1271 callers have pointers and it would be a pain.
1272 So tcbtab is a table of pointers. Since we never
1273 free the TCBs, we allocate a single chunk of many. */
1275 struct tcb *newtcbs = calloc(tcbtabsize, sizeof(newtcbs[0]));
1276 struct tcb **newtab = realloc(tcbtab, tcbtabsize * 2 * sizeof(tcbtab[0]));
1277 if (!newtab || !newtcbs)
1278 die_out_of_memory();
1281 while (i < tcbtabsize)
1282 tcbtab[i++] = newtcbs++;
1286 alloc_tcb(int pid, int command_options_parsed)
1291 if (nprocs == tcbtabsize)
1294 for (i = 0; i < tcbtabsize; i++) {
1296 if ((tcp->flags & TCB_INUSE) == 0) {
1297 memset(tcp, 0, sizeof(*tcp));
1299 tcp->flags = TCB_INUSE;
1300 tcp->outf = outf; /* Initialise to current out file */
1301 #if SUPPORTED_PERSONALITIES > 1
1302 tcp->currpers = current_personality;
1309 fprintf(stderr, "new tcb for pid %d, active tcbs:%d\n", tcp->pid, nprocs);
1310 if (command_options_parsed)
1315 error_msg_and_die("bug in alloc_tcb");
1320 proc_open(struct tcb *tcp, int attaching)
1330 #ifndef HAVE_POLLABLE_PROCFS
1331 static int last_pfd;
1334 #ifdef HAVE_MP_PROCFS
1335 /* Open the process pseudo-files in /proc. */
1336 sprintf(proc, "/proc/%d/ctl", tcp->pid);
1337 tcp->pfd = open(proc, O_WRONLY|O_EXCL);
1339 perror("strace: open(\"/proc/...\", ...)");
1342 set_cloexec_flag(tcp->pfd);
1343 sprintf(proc, "/proc/%d/status", tcp->pid);
1344 tcp->pfd_stat = open(proc, O_RDONLY|O_EXCL);
1345 if (tcp->pfd_stat < 0) {
1346 perror("strace: open(\"/proc/...\", ...)");
1349 set_cloexec_flag(tcp->pfd_stat);
1350 sprintf(proc, "/proc/%d/as", tcp->pid);
1351 tcp->pfd_as = open(proc, O_RDONLY|O_EXCL);
1352 if (tcp->pfd_as < 0) {
1353 perror("strace: open(\"/proc/...\", ...)");
1356 set_cloexec_flag(tcp->pfd_as);
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);
1367 perror("strace: open(\"/proc/...\", ...)");
1370 set_cloexec_flag(tcp->pfd);
1373 sprintf(proc, "/proc/%d/regs", tcp->pid);
1374 tcp->pfd_reg = open(proc, O_RDONLY);
1375 if (tcp->pfd_reg < 0) {
1376 perror("strace: open(\"/proc/.../regs\", ...)");
1380 sprintf(proc, "/proc/%d/status", tcp->pid);
1381 tcp->pfd_status = open(proc, O_RDONLY);
1382 if (tcp->pfd_status < 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)
1552 /* handle the case where we "opened" the child before
1553 it did the kill -STOP */
1554 if (tcp->status.PR_WHY == PR_SIGNALLED &&
1555 tcp->status.PR_WHAT == SIGSTOP)
1556 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)
1661 fprintf(stderr, "dropped tcb for pid %d, %d remain\n", tcp->pid, nprocs);
1664 if (tcp->pfd != -1) {
1668 if (tcp->pfd_reg != -1) {
1669 close(tcp->pfd_reg);
1672 if (tcp->pfd_status != -1) {
1673 close(tcp->pfd_status);
1674 tcp->pfd_status = -1;
1677 tcp->flags = 0; /* rebuild_pollv needs it */
1682 if (outfname && followfork > 1 && tcp->outf)
1685 memset(tcp, 0, sizeof(*tcp));
1688 /* detach traced process; continue with sig
1689 Never call DETACH twice on the same process as both unattached and
1690 attached-unstopped processes give the same ESRCH. For unattached process we
1691 would SIGSTOP it and wait for its SIGSTOP notification forever. */
1694 detach(struct tcb *tcp)
1698 int status, catch_sigstop;
1701 if (tcp->flags & TCB_BPTSET)
1706 * Linux wrongly insists the child be stopped
1707 * before detaching. Arghh. We go through hoops
1708 * to make a clean break of things.
1711 #undef PTRACE_DETACH
1712 #define PTRACE_DETACH PTRACE_SUNDETACH
1715 * We did PTRACE_ATTACH but possibly didn't see the expected SIGSTOP.
1716 * We must catch exactly one as otherwise the detached process
1717 * would be left stopped (process state T).
1719 catch_sigstop = (tcp->flags & TCB_IGNORE_ONE_SIGSTOP);
1720 error = ptrace(PTRACE_DETACH, tcp->pid, (char *) 1, 0);
1722 /* On a clear day, you can see forever. */
1724 else if (errno != ESRCH) {
1725 /* Shouldn't happen. */
1726 perror("detach: ptrace(PTRACE_DETACH, ...)");
1728 else if (my_tkill(tcp->pid, 0) < 0) {
1730 perror("detach: checking sanity");
1732 else if (!catch_sigstop && my_tkill(tcp->pid, SIGSTOP) < 0) {
1734 perror("detach: stopping child");
1738 if (catch_sigstop) {
1741 if (wait4(tcp->pid, &status, __WALL, NULL) < 0) {
1742 if (errno == ECHILD) /* Already gone. */
1744 if (errno != EINVAL) {
1745 perror("detach: waiting");
1749 /* No __WALL here. */
1750 if (waitpid(tcp->pid, &status, 0) < 0) {
1751 if (errno != ECHILD) {
1752 perror("detach: waiting");
1756 /* If no processes, try clones. */
1757 if (wait4(tcp->pid, &status, __WCLONE,
1759 if (errno != ECHILD)
1760 perror("detach: waiting");
1763 #endif /* __WCLONE */
1768 if (!WIFSTOPPED(status)) {
1769 /* Au revoir, mon ami. */
1772 if (WSTOPSIG(status) == SIGSTOP) {
1773 ptrace_restart(PTRACE_DETACH, tcp, 0);
1776 error = ptrace_restart(PTRACE_CONT, tcp,
1777 WSTOPSIG(status) == syscall_trap_sig ? 0
1778 : WSTOPSIG(status));
1786 /* PTRACE_DETACH won't respect `sig' argument, so we post it here. */
1787 error = ptrace_restart(PTRACE_DETACH, tcp, 0);
1791 fprintf(stderr, "Process %u detached\n", tcp->pid);
1800 static void reaper(int sig)
1805 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
1809 #endif /* USE_PROCFS */
1817 for (i = 0; i < tcbtabsize; i++) {
1819 if (!(tcp->flags & TCB_INUSE))
1823 "cleanup: looking at pid %u\n", tcp->pid);
1825 (!outfname || followfork < 2 || tcp_last == tcp)) {
1826 tprints(" <unfinished ...>");
1829 if (tcp->flags & TCB_ATTACHED)
1832 kill(tcp->pid, SIGCONT);
1833 kill(tcp->pid, SIGTERM);
1846 #ifndef HAVE_STRERROR
1848 #if !HAVE_DECL_SYS_ERRLIST
1849 extern int sys_nerr;
1850 extern char *sys_errlist[];
1851 #endif /* HAVE_DECL_SYS_ERRLIST */
1854 strerror(int err_no)
1856 static char buf[64];
1858 if (err_no < 1 || err_no >= sys_nerr) {
1859 sprintf(buf, "Unknown error %d", err_no);
1862 return sys_errlist[err_no];
1865 #endif /* HAVE_STERRROR */
1867 #ifndef HAVE_STRSIGNAL
1869 #if defined HAVE_SYS_SIGLIST && !defined HAVE_DECL_SYS_SIGLIST
1870 extern char *sys_siglist[];
1872 #if defined HAVE_SYS__SIGLIST && !defined HAVE_DECL__SYS_SIGLIST
1873 extern char *_sys_siglist[];
1879 static char buf[64];
1881 if (sig < 1 || sig >= NSIG) {
1882 sprintf(buf, "Unknown signal %d", sig);
1885 #ifdef HAVE__SYS_SIGLIST
1886 return _sys_siglist[sig];
1888 return sys_siglist[sig];
1892 #endif /* HAVE_STRSIGNAL */
1902 pollv = malloc(nprocs * sizeof(pollv[0]));
1904 die_out_of_memory();
1906 for (i = j = 0; i < tcbtabsize; i++) {
1907 struct tcb *tcp = tcbtab[i];
1908 if (!(tcp->flags & TCB_INUSE))
1910 pollv[j].fd = tcp->pfd;
1911 pollv[j].events = POLLWANT;
1915 error_msg_and_die("proc miscount");
1919 #ifndef HAVE_POLLABLE_PROCFS
1922 proc_poll_open(void)
1926 if (pipe(proc_poll_pipe) < 0) {
1927 perror_msg_and_die("pipe");
1929 for (i = 0; i < 2; i++) {
1930 set_cloexec_flag(proc_poll_pipe[i]);
1935 proc_poll(struct pollfd *pollv, int nfds, int timeout)
1939 struct proc_pollfd pollinfo;
1941 n = read(proc_poll_pipe[0], &pollinfo, sizeof(pollinfo));
1944 if (n != sizeof(struct proc_pollfd)) {
1945 error_msg_and_die("panic: short read: %d", n);
1947 for (i = 0; i < nprocs; i++) {
1948 if (pollv[i].fd == pollinfo.fd)
1949 pollv[i].revents = pollinfo.revents;
1951 pollv[i].revents = 0;
1953 poller_pid = pollinfo.pid;
1958 wakeup_handler(int sig)
1963 proc_poller(int pfd)
1965 struct proc_pollfd pollinfo;
1966 struct sigaction sa;
1967 sigset_t blocked_set, empty_set;
1972 struct procfs_status pfs;
1973 #endif /* FREEBSD */
1977 perror_msg_and_die("fork");
1984 sa.sa_handler = interactive ? SIG_DFL : SIG_IGN;
1986 sigemptyset(&sa.sa_mask);
1987 sigaction(SIGHUP, &sa, NULL);
1988 sigaction(SIGINT, &sa, NULL);
1989 sigaction(SIGQUIT, &sa, NULL);
1990 sigaction(SIGPIPE, &sa, NULL);
1991 sigaction(SIGTERM, &sa, NULL);
1992 sa.sa_handler = wakeup_handler;
1993 sigaction(SIGUSR1, &sa, NULL);
1994 sigemptyset(&blocked_set);
1995 sigaddset(&blocked_set, SIGUSR1);
1996 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
1997 sigemptyset(&empty_set);
1999 if (getrlimit(RLIMIT_NOFILE, &rl) < 0) {
2000 perror_msg_and_die("getrlimit(RLIMIT_NOFILE, ...)");
2003 for (i = 0; i < n; i++) {
2004 if (i != pfd && i != proc_poll_pipe[1])
2009 pollinfo.pid = getpid();
2012 if (ioctl(pfd, PIOCWSTOP, NULL) < 0)
2014 if (ioctl(pfd, PIOCWSTOP, &pfs) < 0)
2021 pollinfo.revents = POLLERR;
2024 pollinfo.revents = POLLHUP;
2027 perror("proc_poller: PIOCWSTOP");
2029 write(proc_poll_pipe[1], &pollinfo, sizeof(pollinfo));
2032 pollinfo.revents = POLLWANT;
2033 write(proc_poll_pipe[1], &pollinfo, sizeof(pollinfo));
2034 sigsuspend(&empty_set);
2038 #endif /* !HAVE_POLLABLE_PROCFS */
2048 if (followfork < 2 &&
2049 last < nprocs && (pollv[last].revents & POLLWANT)) {
2051 * The previous process is ready to run again. We'll
2052 * let it do so if it is currently in a syscall. This
2053 * heuristic improves the readability of the trace.
2055 tcp = pfd2tcb(pollv[last].fd);
2056 if (tcp && exiting(tcp))
2057 return pollv[last].fd;
2060 for (i = 0; i < nprocs; i++) {
2061 /* Let competing children run round robin. */
2062 j = (i + last + 1) % nprocs;
2063 if (pollv[j].revents & (POLLHUP | POLLERR)) {
2064 tcp = pfd2tcb(pollv[j].fd);
2066 error_msg_and_die("lost proc");
2071 if (pollv[j].revents & POLLWANT) {
2076 error_msg_and_die("nothing ready");
2083 struct tcb *in_syscall = NULL;
2088 int ioctl_result = 0, ioctl_errno = 0;
2093 sigprocmask(SIG_SETMASK, &empty_set, NULL);
2100 #ifndef HAVE_POLLABLE_PROCFS
2101 if (proc_poll_pipe[0] == -1) {
2103 tcp = first_used_tcb();
2110 #ifndef HAVE_POLLABLE_PROCFS
2112 /* fall through ... */
2113 #endif /* !HAVE_POLLABLE_PROCFS */
2115 #ifdef HAVE_POLLABLE_PROCFS
2117 /* On some systems (e.g. UnixWare) we get too much ugly
2118 "unfinished..." stuff when multiple proceses are in
2119 syscalls. Here's a nasty hack */
2126 pv.events = POLLWANT;
2127 what = poll(&pv, 1, 1);
2133 else if (what == 1 && pv.revents & POLLWANT) {
2139 if (poll(pollv, nprocs, INFTIM) < 0) {
2144 #else /* !HAVE_POLLABLE_PROCFS */
2145 if (proc_poll(pollv, nprocs, INFTIM) < 0) {
2150 #endif /* !HAVE_POLLABLE_PROCFS */
2157 /* Look up `pfd' in our table. */
2160 error_msg_and_die("unknown pfd: %u", pfd);
2165 /* Get the status of the process. */
2168 ioctl_result = IOCTL_WSTOP(tcp);
2170 /* Thanks to some scheduling mystery, the first poller
2171 sometimes waits for the already processed end of fork
2172 event. Doing a non blocking poll here solves the problem. */
2173 if (proc_poll_pipe[0] != -1)
2174 ioctl_result = IOCTL_STATUS(tcp);
2176 ioctl_result = IOCTL_WSTOP(tcp);
2177 #endif /* FREEBSD */
2178 ioctl_errno = errno;
2179 #ifndef HAVE_POLLABLE_PROCFS
2180 if (proc_poll_pipe[0] != -1) {
2181 if (ioctl_result < 0)
2182 kill(poller_pid, SIGKILL);
2184 kill(poller_pid, SIGUSR1);
2186 #endif /* !HAVE_POLLABLE_PROCFS */
2192 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
2194 if (ioctl_result < 0) {
2195 /* Find out what happened if it failed. */
2196 switch (ioctl_errno) {
2207 perror_msg_and_die("PIOCWSTOP");
2212 if ((tcp->flags & TCB_STARTUP) && (tcp->status.PR_WHY == PR_SYSEXIT)) {
2213 /* discard first event for a syscall we never entered */
2214 IOCTL(tcp->pfd, PIOCRUN, 0);
2219 /* clear the just started flag */
2220 tcp->flags &= ~TCB_STARTUP;
2222 /* set current output file */
2224 curcol = tcp->curcol;
2227 struct timeval stime;
2232 len = pread(tcp->pfd_status, buf, sizeof(buf) - 1, 0);
2236 "%*s %*d %*d %*d %*d %*d,%*d %*s %*d,%*d %*d,%*d %ld,%ld",
2237 &stime.tv_sec, &stime.tv_usec);
2239 stime.tv_sec = stime.tv_usec = 0;
2240 #else /* !FREEBSD */
2241 stime.tv_sec = tcp->status.pr_stime.tv_sec;
2242 stime.tv_usec = tcp->status.pr_stime.tv_nsec/1000;
2243 #endif /* !FREEBSD */
2244 tv_sub(&tcp->dtime, &stime, &tcp->stime);
2247 what = tcp->status.PR_WHAT;
2248 switch (tcp->status.PR_WHY) {
2251 if (tcp->status.PR_FLAGS & PR_ASLEEP) {
2252 tcp->status.PR_WHY = PR_SYSENTRY;
2253 if (trace_syscall(tcp) < 0) {
2254 error_msg_and_die("syscall trouble");
2258 #endif /* !FREEBSD */
2264 if (trace_syscall(tcp) < 0) {
2265 error_msg_and_die("syscall trouble");
2269 if (cflag != CFLAG_ONLY_STATS
2270 && (qual_flags[what] & QUAL_SIGNAL)) {
2272 tprintf("--- %s (%s) ---",
2273 signame(what), strsignal(what));
2276 if (tcp->status.PR_INFO.si_signo == what) {
2278 tprints(" siginfo=");
2279 printsiginfo(&tcp->status.PR_INFO, 1);
2286 if (cflag != CFLAGS_ONLY_STATS
2287 && (qual_flags[what] & QUAL_FAULT)) {
2289 tprintf("=== FAULT %d ===", what);
2294 case 0: /* handle case we polled for nothing */
2298 error_msg_and_die("odd stop %d", tcp->status.PR_WHY);
2301 /* Remember current print column before continuing. */
2302 tcp->curcol = curcol;
2305 if (IOCTL(tcp->pfd, PIOCRUN, &arg) < 0)
2307 if (IOCTL(tcp->pfd, PIOCRUN, 0) < 0)
2310 perror_msg_and_die("PIOCRUN");
2316 #else /* !USE_PROCFS */
2327 struct rusage *rup = cflag ? &ru : NULL;
2329 static int wait4_options = __WALL;
2333 while (nprocs != 0) {
2337 sigprocmask(SIG_SETMASK, &empty_set, NULL);
2340 pid = wait4(-1, &status, wait4_options, rup);
2341 if (pid < 0 && (wait4_options & __WALL) && errno == EINVAL) {
2342 /* this kernel does not support __WALL */
2343 wait4_options &= ~__WALL;
2344 pid = wait4(-1, &status, wait4_options, rup);
2346 if (pid < 0 && !(wait4_options & __WALL) && errno == ECHILD) {
2347 /* most likely a "cloned" process */
2348 pid = wait4(-1, &status, __WCLONE, rup);
2350 perror_msg("wait4(__WCLONE) failed");
2354 pid = wait4(-1, &status, 0, rup);
2355 # endif /* __WALL */
2358 pid = wait(&status);
2362 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
2365 switch (wait_errno) {
2370 * We would like to verify this case
2371 * but sometimes a race in Solbourne's
2372 * version of SunOS sometimes reports
2373 * ECHILD before sending us SIGCHILD.
2378 perror("strace: wait");
2382 if (pid == popen_pid) {
2383 if (WIFEXITED(status) || WIFSIGNALED(status))
2388 char buf[sizeof("WIFEXITED,exitcode=%u") + sizeof(int)*3 /*paranoia:*/ + 16];
2390 unsigned ev = (unsigned)status >> 16;
2392 static const char *const event_names[] = {
2393 [PTRACE_EVENT_CLONE] = "CLONE",
2394 [PTRACE_EVENT_FORK] = "FORK",
2395 [PTRACE_EVENT_VFORK] = "VFORK",
2396 [PTRACE_EVENT_VFORK_DONE] = "VFORK_DONE",
2397 [PTRACE_EVENT_EXEC] = "EXEC",
2398 [PTRACE_EVENT_EXIT] = "EXIT",
2401 if (ev < ARRAY_SIZE(event_names))
2402 e = event_names[ev];
2404 sprintf(buf, "?? (%u)", ev);
2407 fprintf(stderr, " PTRACE_EVENT_%s", e);
2411 if (WIFSIGNALED(status))
2413 sprintf(buf, "WIFSIGNALED,%ssig=%s",
2414 WCOREDUMP(status) ? "core," : "",
2415 signame(WTERMSIG(status)));
2417 sprintf(buf, "WIFSIGNALED,sig=%s",
2418 signame(WTERMSIG(status)));
2420 if (WIFEXITED(status))
2421 sprintf(buf, "WIFEXITED,exitcode=%u", WEXITSTATUS(status));
2422 if (WIFSTOPPED(status))
2423 sprintf(buf, "WIFSTOPPED,sig=%s", signame(WSTOPSIG(status)));
2425 if (WIFCONTINUED(status))
2426 strcpy(buf, "WIFCONTINUED");
2428 fprintf(stderr, " [wait(0x%04x) = %u] %s\n", status, pid, buf);
2431 /* Look up `pid' in our table. */
2436 /* This is needed to go with the CLONE_PTRACE
2437 changes in process.c/util.c: we might see
2438 the child's initial trap before we see the
2439 parent return from the clone syscall.
2440 Leave the child suspended until the parent
2441 returns from its system call. Only then
2442 will we have the association of parent and
2443 child so that we know how to do clearbpt
2445 tcp = alloctcb(pid);
2446 tcp->flags |= TCB_ATTACHED | TCB_STARTUP | TCB_IGNORE_ONE_SIGSTOP;
2448 fprintf(stderr, "Process %d attached\n",
2452 /* This can happen if a clone call used
2453 CLONE_PTRACE itself. */
2456 if (WIFSTOPPED(status))
2457 ptrace(PTRACE_CONT, pid, (char *) 1, 0);
2458 error_msg_and_die("Unknown pid: %u", pid);
2461 /* set current output file */
2463 curcol = tcp->curcol;
2466 tv_sub(&tcp->dtime, &ru.ru_stime, &tcp->stime);
2467 tcp->stime = ru.ru_stime;
2471 if (WIFSIGNALED(status)) {
2472 if (pid == strace_child)
2473 exit_code = 0x100 | WTERMSIG(status);
2474 if (cflag != CFLAG_ONLY_STATS
2475 && (qual_flags[WTERMSIG(status)] & QUAL_SIGNAL)) {
2478 tprintf("+++ killed by %s %s+++",
2479 signame(WTERMSIG(status)),
2480 WCOREDUMP(status) ? "(core dumped) " : "");
2482 tprintf("+++ killed by %s +++",
2483 signame(WTERMSIG(status)));
2491 if (WIFEXITED(status)) {
2492 if (pid == strace_child)
2493 exit_code = WEXITSTATUS(status);
2494 if (tcp == tcp_last) {
2495 if ((tcp->flags & (TCB_INSYSCALL|TCB_REPRINT)) == TCB_INSYSCALL)
2496 tprintf(" <unfinished ... exit status %d>\n",
2497 WEXITSTATUS(status));
2500 if (!cflag /* && (qual_flags[WTERMSIG(status)] & QUAL_SIGNAL) */ ) {
2502 tprintf("+++ exited with %d +++", WEXITSTATUS(status));
2509 if (!WIFSTOPPED(status)) {
2510 fprintf(stderr, "PANIC: pid %u not stopped\n", pid);
2515 /* Is this the very first time we see this tracee stopped? */
2516 if (tcp->flags & TCB_STARTUP) {
2518 fprintf(stderr, "pid %d has TCB_STARTUP, initializing it\n", tcp->pid);
2519 tcp->flags &= ~TCB_STARTUP;
2520 if (tcp->flags & TCB_BPTSET) {
2522 * One example is a breakpoint inherited from
2523 * parent through fork().
2525 if (clearbpt(tcp) < 0) {
2533 if (ptrace_setoptions) {
2535 fprintf(stderr, "setting opts %x on pid %d\n", ptrace_setoptions, tcp->pid);
2536 if (ptrace(PTRACE_SETOPTIONS, tcp->pid, NULL, ptrace_setoptions) < 0) {
2537 if (errno != ESRCH) {
2538 /* Should never happen, really */
2539 perror_msg_and_die("PTRACE_SETOPTIONS");
2546 if (((unsigned)status >> 16) != 0) {
2547 /* Ptrace event (we ignore all of them for now) */
2548 goto restart_tracee_with_sig_0;
2551 sig = WSTOPSIG(status);
2553 /* Is this post-attach SIGSTOP?
2554 * Interestingly, the process may stop
2555 * with STOPSIG equal to some other signal
2556 * than SIGSTOP if we happend to attach
2557 * just before the process takes a signal.
2559 if (sig == SIGSTOP && (tcp->flags & TCB_IGNORE_ONE_SIGSTOP)) {
2561 fprintf(stderr, "ignored SIGSTOP on pid %d\n", tcp->pid);
2562 tcp->flags &= ~TCB_IGNORE_ONE_SIGSTOP;
2563 goto restart_tracee_with_sig_0;
2566 if (sig != syscall_trap_sig) {
2567 if (cflag != CFLAG_ONLY_STATS
2568 && (qual_flags[sig] & QUAL_SIGNAL)) {
2570 #if defined(PT_CR_IPSR) && defined(PT_CR_IIP)
2574 upeek(tcp, PT_CR_IPSR, &psr);
2575 upeek(tcp, PT_CR_IIP, &pc);
2578 pc += (psr >> PSR_RI) & 0x3;
2579 # define PC_FORMAT_STR " @ %lx"
2580 # define PC_FORMAT_ARG , pc
2582 # define PC_FORMAT_STR ""
2583 # define PC_FORMAT_ARG /* nothing */
2586 if (ptrace(PTRACE_GETSIGINFO, pid, 0, (long) &si) == 0) {
2588 printsiginfo(&si, verbose(tcp));
2589 tprintf(" (%s)" PC_FORMAT_STR " ---",
2593 tprintf("--- %s by %s" PC_FORMAT_STR " ---",
2600 goto restart_tracee;
2603 /* We handled quick cases, we are permitted to interrupt now. */
2607 /* This should be syscall entry or exit.
2608 * (Or it still can be that pesky post-execve SIGTRAP!)
2611 if (trace_syscall(tcp) < 0 && !tcp->ptrace_errno) {
2612 /* ptrace() failed in trace_syscall() with ESRCH.
2613 * Likely a result of process disappearing mid-flight.
2614 * Observed case: exit_group() terminating
2615 * all processes in thread group.
2617 if (tcp->flags & TCB_ATTACHED) {
2619 /* Do we have dangling line "syscall(param, param"?
2620 * Finish the line then.
2622 tcp_last->flags |= TCB_REPRINT;
2623 tprints(" <unfinished ...>");
2627 /* We assume that ptrace error was caused by process death.
2628 * We used to detach(tcp) here, but since we no longer
2629 * implement "detach before death" policy/hack,
2630 * we can let this process to report its death to us
2631 * normally, via WIFEXITED or WIFSIGNALED wait status.
2634 /* It's our real child (and we also trace it) */
2635 /* my_tkill(pid, SIGKILL); - why? */
2636 /* droptcb(tcp); - why? */
2640 restart_tracee_with_sig_0:
2643 /* Remember current print column before continuing. */
2644 tcp->curcol = curcol;
2645 if (ptrace_restart(PTRACE_SYSCALL, tcp, sig) < 0) {
2653 #endif /* !USE_PROCFS */
2656 tprintf(const char *fmt, ...)
2660 va_start(args, fmt);
2662 int n = vfprintf(outf, fmt, args);
2665 perror(outfname == NULL
2666 ? "<writing to pipe>" : outfname);
2674 tprints(const char *str)
2677 int n = fputs(str, outf);
2679 curcol += strlen(str);
2683 perror(outfname == NULL
2684 ? "<writing to pipe>" : outfname);
2689 printleader(struct tcb *tcp)
2692 if (tcp_last->ptrace_errno) {
2693 if (tcp_last->flags & TCB_INSYSCALL) {
2694 tprints(" <unavailable>) ");
2697 tprints("= ? <unavailable>\n");
2698 tcp_last->ptrace_errno = 0;
2699 } else if (!outfname || followfork < 2 || tcp_last == tcp) {
2700 tcp_last->flags |= TCB_REPRINT;
2701 tprints(" <unfinished ...>\n");
2705 if ((followfork == 1 || pflag_seen > 1) && outfname)
2706 tprintf("%-5d ", tcp->pid);
2707 else if (nprocs > 1 && !outfname)
2708 tprintf("[pid %5u] ", tcp->pid);
2710 char str[sizeof("HH:MM:SS")];
2711 struct timeval tv, dtv;
2712 static struct timeval otv;
2714 gettimeofday(&tv, NULL);
2716 if (otv.tv_sec == 0)
2718 tv_sub(&dtv, &tv, &otv);
2719 tprintf("%6ld.%06ld ",
2720 (long) dtv.tv_sec, (long) dtv.tv_usec);
2723 else if (tflag > 2) {
2724 tprintf("%ld.%06ld ",
2725 (long) tv.tv_sec, (long) tv.tv_usec);
2728 time_t local = tv.tv_sec;
2729 strftime(str, sizeof(str), "%T", localtime(&local));
2731 tprintf("%s.%06ld ", str, (long) tv.tv_usec);
2733 tprintf("%s ", str);
2743 if (curcol < acolumn)
2744 tprints(acolumn_spaces + curcol);
2754 #ifdef HAVE_MP_PROCFS
2757 mp_ioctl(int fd, int cmd, void *arg, int size)
2759 struct iovec iov[2];
2762 iov[0].iov_base = &cmd;
2763 iov[0].iov_len = sizeof cmd;
2766 iov[1].iov_base = arg;
2767 iov[1].iov_len = size;
2770 return writev(fd, iov, n);