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, interactive = 0, pflag_seen = 0, rflag = 0, tflag = 0;
91 * daemonized_tracer supports -D option.
92 * With this option, strace forks twice.
93 * Unlike normal case, with -D *grandparent* process exec's,
94 * becoming a traced process. Child exits (this prevents traced process
95 * from having children it doesn't expect to have), and grandchild
96 * attaches to grandparent similarly to strace -p PID.
97 * This allows for more transparent interaction in cases
98 * when process and its parent are communicating via signals,
99 * wait() etc. Without -D, strace process gets lodged in between,
100 * disrupting parent<->child link.
102 static bool daemonized_tracer = 0;
104 /* Sometimes we want to print only succeeding syscalls. */
105 int not_failing_only = 0;
107 /* Show path associated with fd arguments */
108 int show_fd_path = 0;
110 /* are we filtering traces based on paths? */
111 int tracing_paths = 0;
113 static int exit_code = 0;
114 static int strace_child = 0;
115 static int strace_tracer_pid = 0;
117 static char *username = NULL;
118 static uid_t run_uid;
119 static gid_t run_gid;
121 int max_strlen = DEFAULT_STRLEN;
122 static int acolumn = DEFAULT_ACOLUMN;
123 static char *acolumn_spaces;
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);
267 void die_out_of_memory(void)
269 static bool recursed = 0;
273 error_msg_and_die("Out of memory");
285 /* Glue for systems without a MMU that cannot provide fork() */
287 # define strace_vforked 0
289 # define strace_vforked 1
290 # define fork() vfork()
294 set_cloexec_flag(int fd)
298 flags = fcntl(fd, F_GETFD);
300 /* Can happen only if fd is bad.
301 * Should never happen: if it does, we have a bug
302 * in the caller. Therefore we just abort
303 * instead of propagating the error.
305 perror_msg_and_die("fcntl(%d, F_GETFD)", fd);
308 newflags = flags | FD_CLOEXEC;
309 if (flags == newflags)
312 fcntl(fd, F_SETFD, newflags); /* never fails */
316 * When strace is setuid executable, we have to swap uids
317 * before and after filesystem and process management operations.
323 int euid = geteuid(), uid = getuid();
325 if (euid != uid && setreuid(euid, uid) < 0) {
326 perror_msg_and_die("setreuid");
332 # define fopen_for_output fopen64
334 # define fopen_for_output fopen
338 strace_fopen(const char *path)
343 fp = fopen_for_output(path, "w");
345 perror_msg_and_die("Can't fopen '%s'", path);
347 set_cloexec_flag(fileno(fp));
351 static int popen_pid = 0;
354 # define _PATH_BSHELL "/bin/sh"
358 * We cannot use standard popen(3) here because we have to distinguish
359 * popen child process from other processes we trace, and standard popen(3)
360 * does not export its child's pid.
363 strace_popen(const char *command)
370 perror_msg_and_die("pipe");
372 set_cloexec_flag(fds[1]); /* never fails */
376 perror_msg_and_die("vfork");
378 if (popen_pid == 0) {
383 perror_msg_and_die("dup2");
386 execl(_PATH_BSHELL, "sh", "-c", command, NULL);
387 perror_msg_and_die("Can't execute '%s'", _PATH_BSHELL);
393 fp = fdopen(fds[1], "w");
400 newoutf(struct tcb *tcp)
402 if (outfname && followfork > 1) {
403 char name[520 + sizeof(int) * 3];
404 sprintf(name, "%.512s.%u", outfname, tcp->pid);
405 tcp->outf = strace_fopen(name);
416 * Block user interruptions as we would leave the traced
417 * process stopped (process state T) if we would terminate in
418 * between PTRACE_ATTACH and wait4 () on SIGSTOP.
419 * We rely on cleanup() from this point on.
422 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
424 if (daemonized_tracer) {
429 if (pid) { /* parent */
431 * Wait for grandchild to attach to straced process
432 * (grandparent). Grandchild SIGKILLs us after it attached.
433 * Grandparent's wait() is unblocked by our death,
434 * it proceeds to exec the straced program.
437 _exit(0); /* paranoia */
440 /* We will be the tracer process. Remember our new pid: */
441 strace_tracer_pid = getpid();
444 for (tcbi = 0; tcbi < tcbtabsize; tcbi++) {
447 if (!(tcp->flags & TCB_INUSE) || !(tcp->flags & TCB_ATTACHED))
450 if (tcp->flags & TCB_ATTACH_DONE)
453 /* Reinitialize the output since it may have changed. */
458 if (proc_open(tcp, 1) < 0) {
459 fprintf(stderr, "trouble opening proc file\n");
463 #else /* !USE_PROCFS */
465 if (followfork && !daemonized_tracer) {
466 char procdir[sizeof("/proc/%d/task") + sizeof(int) * 3];
469 sprintf(procdir, "/proc/%d/task", tcp->pid);
470 dir = opendir(procdir);
472 unsigned int ntid = 0, nerr = 0;
475 while ((de = readdir(dir)) != NULL) {
476 if (de->d_fileno == 0)
478 tid = atoi(de->d_name);
482 if (ptrace(PTRACE_ATTACH, tid, (char *) 1, 0) < 0) {
485 fprintf(stderr, "attach to pid %d failed\n", tid);
489 fprintf(stderr, "attach to pid %d succeeded\n", tid);
490 if (tid != tcp->pid) {
491 struct tcb *new_tcp = alloctcb(tid);
492 new_tcp->flags |= TCB_ATTACHED|TCB_ATTACH_DONE;
496 sigprocmask(SIG_SETMASK, &empty_set, NULL);
499 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
505 perror("attach: ptrace(PTRACE_ATTACH, ...)");
510 fprintf(stderr, ntid > 1
511 ? "Process %u attached with %u threads - interrupt to quit\n"
512 : "Process %u attached - interrupt to quit\n",
516 } /* if (opendir worked) */
519 if (ptrace(PTRACE_ATTACH, tcp->pid, (char *) 1, 0) < 0) {
520 perror("attach: ptrace(PTRACE_ATTACH, ...)");
525 fprintf(stderr, "attach to pid %d (main) succeeded\n", tcp->pid);
527 if (daemonized_tracer) {
529 * It is our grandparent we trace, not a -p PID.
530 * Don't want to just detach on exit, so...
532 tcp->flags &= ~TCB_ATTACHED;
534 * Make parent go away.
535 * Also makes grandparent's wait() unblock.
537 kill(getppid(), SIGKILL);
540 #endif /* !USE_PROCFS */
543 "Process %u attached - interrupt to quit\n",
545 } /* for each tcbtab[] */
549 /* TCB_ATTACH_DONE flag is used only in this function */
550 for (tcbi = 0; tcbi < tcbtabsize; tcbi++) {
552 tcp->flags &= ~TCB_ATTACH_DONE;
557 sigprocmask(SIG_SETMASK, &empty_set, NULL);
561 startup_child(char **argv)
564 const char *filename;
565 char pathname[MAXPATHLEN];
570 if (strchr(filename, '/')) {
571 if (strlen(filename) > sizeof pathname - 1) {
572 errno = ENAMETOOLONG;
573 perror_msg_and_die("exec");
575 strcpy(pathname, filename);
577 #ifdef USE_DEBUGGING_EXEC
579 * Debuggers customarily check the current directory
580 * first regardless of the path but doing that gives
581 * security geeks a panic attack.
583 else if (stat(filename, &statbuf) == 0)
584 strcpy(pathname, filename);
585 #endif /* USE_DEBUGGING_EXEC */
590 for (path = getenv("PATH"); path && *path; path += m) {
591 if (strchr(path, ':')) {
592 n = strchr(path, ':') - path;
596 m = n = strlen(path);
598 if (!getcwd(pathname, MAXPATHLEN))
600 len = strlen(pathname);
602 else if (n > sizeof pathname - 1)
605 strncpy(pathname, path, n);
608 if (len && pathname[len - 1] != '/')
609 pathname[len++] = '/';
610 strcpy(pathname + len, filename);
611 if (stat(pathname, &statbuf) == 0 &&
612 /* Accept only regular files
613 with some execute bits set.
614 XXX not perfect, might still fail */
615 S_ISREG(statbuf.st_mode) &&
616 (statbuf.st_mode & 0111))
620 if (stat(pathname, &statbuf) < 0) {
621 perror_msg_and_die("Can't stat '%s'", filename);
623 strace_child = pid = fork();
625 perror_msg_and_die("fork");
627 if ((pid != 0 && daemonized_tracer) /* -D: parent to become a traced process */
628 || (pid == 0 && !daemonized_tracer) /* not -D: child to become a traced process */
632 if (outf != stderr) close(fileno(outf));
634 /* Kludge for SGI, see proc_open for details. */
635 sa.sa_handler = foobar;
637 sigemptyset(&sa.sa_mask);
638 sigaction(SIGINT, &sa, NULL);
643 kill(pid, SIGSTOP); /* stop HERE */
645 #else /* !USE_PROCFS */
649 if (!daemonized_tracer) {
650 if (ptrace(PTRACE_TRACEME, 0, (char *) 1, 0) < 0) {
651 perror_msg_and_die("ptrace(PTRACE_TRACEME, ...)");
657 if (username != NULL || geteuid() == 0) {
658 uid_t run_euid = run_uid;
659 gid_t run_egid = run_gid;
661 if (statbuf.st_mode & S_ISUID)
662 run_euid = statbuf.st_uid;
663 if (statbuf.st_mode & S_ISGID)
664 run_egid = statbuf.st_gid;
667 * It is important to set groups before we
668 * lose privileges on setuid.
670 if (username != NULL) {
671 if (initgroups(username, run_gid) < 0) {
672 perror_msg_and_die("initgroups");
674 if (setregid(run_gid, run_egid) < 0) {
675 perror_msg_and_die("setregid");
677 if (setreuid(run_uid, run_euid) < 0) {
678 perror_msg_and_die("setreuid");
683 setreuid(run_uid, run_uid);
685 if (!daemonized_tracer) {
687 * Induce an immediate stop so that the parent
688 * will resume us with PTRACE_SYSCALL and display
689 * this execve call normally.
690 * Unless of course we're on a no-MMU system where
691 * we vfork()-ed, so we cannot stop the child.
694 kill(getpid(), SIGSTOP);
696 struct sigaction sv_sigchld;
697 sigaction(SIGCHLD, NULL, &sv_sigchld);
699 * Make sure it is not SIG_IGN, otherwise wait
702 signal(SIGCHLD, SIG_DFL);
704 * Wait for grandchild to attach to us.
705 * It kills child after that, and wait() unblocks.
710 sigaction(SIGCHLD, &sv_sigchld, NULL);
712 #endif /* !USE_PROCFS */
714 execv(pathname, argv);
715 perror_msg_and_die("exec");
718 /* We are the tracer. */
719 /* With -D, we are *child* here, IOW: different pid. Fetch it. */
720 strace_tracer_pid = getpid();
722 tcp = alloctcb(daemonized_tracer ? getppid() : pid);
723 if (daemonized_tracer) {
724 /* We want subsequent startup_attach() to attach to it. */
725 tcp->flags |= TCB_ATTACHED;
728 if (proc_open(tcp, 0) < 0) {
729 perror_msg_and_die("trouble opening proc file");
731 #endif /* USE_PROCFS */
735 static void kill_save_errno(pid_t pid, int sig)
737 int saved_errno = errno;
739 (void) kill(pid, sig);
744 * Test whether the kernel support PTRACE_O_TRACECLONE et al options.
745 * First fork a new child, call ptrace with PTRACE_SETOPTIONS on it,
746 * and then see which options are supported by the kernel.
749 test_ptrace_setoptions_followfork(void)
751 int pid, expected_grandchild = 0, found_grandchild = 0;
752 const unsigned int test_options = PTRACE_O_TRACECLONE |
758 perror_msg_and_die("fork");
761 if (ptrace(PTRACE_TRACEME, 0, 0, 0) < 0)
762 perror_msg_and_die("%s: PTRACE_TRACEME doesn't work",
766 perror_msg_and_die("fork");
771 int status, tracee_pid;
774 tracee_pid = wait(&status);
775 if (tracee_pid <= 0) {
778 else if (errno == ECHILD)
780 kill_save_errno(pid, SIGKILL);
781 perror_msg_and_die("%s: unexpected wait result %d",
782 __func__, tracee_pid);
784 if (WIFEXITED(status)) {
785 if (WEXITSTATUS(status)) {
786 if (tracee_pid != pid)
787 kill_save_errno(pid, SIGKILL);
788 error_msg_and_die("%s: unexpected exit status %u",
789 __func__, WEXITSTATUS(status));
793 if (WIFSIGNALED(status)) {
794 if (tracee_pid != pid)
795 kill_save_errno(pid, SIGKILL);
796 error_msg_and_die("%s: unexpected signal %u",
797 __func__, WTERMSIG(status));
799 if (!WIFSTOPPED(status)) {
800 if (tracee_pid != pid)
801 kill_save_errno(tracee_pid, SIGKILL);
803 error_msg_and_die("%s: unexpected wait status %x",
806 if (tracee_pid != pid) {
807 found_grandchild = tracee_pid;
808 if (ptrace(PTRACE_CONT, tracee_pid, 0, 0) < 0) {
809 kill_save_errno(tracee_pid, SIGKILL);
810 kill_save_errno(pid, SIGKILL);
811 perror_msg_and_die("PTRACE_CONT doesn't work");
815 switch (WSTOPSIG(status)) {
817 if (ptrace(PTRACE_SETOPTIONS, pid, 0, test_options) < 0
818 && errno != EINVAL && errno != EIO)
819 perror_msg("PTRACE_SETOPTIONS");
822 if (status >> 16 == PTRACE_EVENT_FORK) {
825 if (ptrace(PTRACE_GETEVENTMSG, pid,
826 NULL, (long) &msg) == 0)
827 expected_grandchild = msg;
831 if (ptrace(PTRACE_SYSCALL, pid, 0, 0) < 0) {
832 kill_save_errno(pid, SIGKILL);
833 perror_msg_and_die("PTRACE_SYSCALL doesn't work");
836 if (expected_grandchild && expected_grandchild == found_grandchild) {
837 ptrace_setoptions |= test_options;
839 fprintf(stderr, "ptrace_setoptions = %#x\n",
843 error_msg("Test for PTRACE_O_TRACECLONE failed, "
844 "giving up using this feature.");
848 * Test whether the kernel support PTRACE_O_TRACESYSGOOD.
849 * First fork a new child, call ptrace(PTRACE_SETOPTIONS) on it,
850 * and then see whether it will stop with (SIGTRAP | 0x80).
852 * Use of this option enables correct handling of user-generated SIGTRAPs,
853 * and SIGTRAPs generated by special instructions such as int3 on x86:
854 * _start: .globl _start
859 * (compile with: "gcc -nostartfiles -nostdlib -o int3 int3.S")
862 test_ptrace_setoptions_for_all(void)
864 const unsigned int test_options = PTRACE_O_TRACESYSGOOD |
871 perror_msg_and_die("fork");
875 if (ptrace(PTRACE_TRACEME, 0L, 0L, 0L) < 0)
876 /* Note: exits with exitcode 1 */
877 perror_msg_and_die("%s: PTRACE_TRACEME doesn't work",
880 _exit(0); /* parent should see entry into this syscall */
884 int status, tracee_pid;
887 tracee_pid = wait(&status);
888 if (tracee_pid <= 0) {
891 kill_save_errno(pid, SIGKILL);
892 perror_msg_and_die("%s: unexpected wait result %d",
893 __func__, tracee_pid);
895 if (WIFEXITED(status)) {
896 if (WEXITSTATUS(status) == 0)
898 error_msg_and_die("%s: unexpected exit status %u",
899 __func__, WEXITSTATUS(status));
901 if (WIFSIGNALED(status)) {
902 error_msg_and_die("%s: unexpected signal %u",
903 __func__, WTERMSIG(status));
905 if (!WIFSTOPPED(status)) {
907 error_msg_and_die("%s: unexpected wait status %x",
910 if (WSTOPSIG(status) == SIGSTOP) {
912 * We don't check "options aren't accepted" error.
913 * If it happens, we'll never get (SIGTRAP | 0x80),
914 * and thus will decide to not use the option.
915 * IOW: the outcome of the test will be correct.
917 if (ptrace(PTRACE_SETOPTIONS, pid, 0L, test_options) < 0
918 && errno != EINVAL && errno != EIO)
919 perror_msg("PTRACE_SETOPTIONS");
921 if (WSTOPSIG(status) == (SIGTRAP | 0x80)) {
924 if (ptrace(PTRACE_SYSCALL, pid, 0L, 0L) < 0) {
925 kill_save_errno(pid, SIGKILL);
926 perror_msg_and_die("PTRACE_SYSCALL doesn't work");
931 syscall_trap_sig = (SIGTRAP | 0x80);
932 ptrace_setoptions |= test_options;
934 fprintf(stderr, "ptrace_setoptions = %#x\n",
939 error_msg("Test for PTRACE_O_TRACESYSGOOD failed, "
940 "giving up using this feature.");
945 main(int argc, char *argv[])
952 progname = argv[0] ? argv[0] : "strace";
954 strace_tracer_pid = getpid();
956 /* Allocate the initial tcbtab. */
957 tcbtabsize = argc; /* Surely enough for all -p args. */
958 tcbtab = calloc(tcbtabsize, sizeof(tcbtab[0]));
961 tcp = calloc(tcbtabsize, sizeof(*tcp));
964 for (c = 0; c < tcbtabsize; c++)
969 set_sortby(DEFAULT_SORTBY);
970 set_personality(DEFAULT_PERSONALITY);
971 qualify("trace=all");
972 qualify("abbrev=all");
973 qualify("verbose=all");
974 qualify("signal=all");
975 while ((c = getopt(argc, argv,
980 "a:e:o:O:p:s:S:u:E:P:")) != EOF) {
983 if (cflag == CFLAG_BOTH) {
984 error_msg_and_die("-c and -C are mutually exclusive options");
986 cflag = CFLAG_ONLY_STATS;
989 if (cflag == CFLAG_ONLY_STATS) {
990 error_msg_and_die("-c and -C are mutually exclusive options");
999 daemonized_tracer = 1;
1034 qualify("abbrev=none");
1037 printf("%s -- version %s\n", PACKAGE_NAME, VERSION);
1041 not_failing_only = 1;
1044 acolumn = atoi(optarg);
1046 error_msg_and_die("Bad column width '%s'", optarg);
1052 outfname = strdup(optarg);
1055 set_overhead(atoi(optarg));
1060 error_msg("Invalid process id: '%s'", optarg);
1063 if (pid == strace_tracer_pid) {
1064 error_msg("I'm sorry, I can't let you do that, Dave.");
1067 tcp = alloc_tcb(pid, 0);
1068 tcp->flags |= TCB_ATTACHED;
1073 if (pathtrace_select(optarg)) {
1074 error_msg_and_die("Failed to select path '%s'", optarg);
1078 max_strlen = atoi(optarg);
1079 if (max_strlen < 0) {
1080 error_msg_and_die("Invalid -s argument: '%s'", optarg);
1087 username = strdup(optarg);
1090 if (putenv(optarg) < 0)
1091 die_out_of_memory();
1099 acolumn_spaces = malloc(acolumn + 1);
1100 if (!acolumn_spaces)
1101 die_out_of_memory();
1102 memset(acolumn_spaces, ' ', acolumn);
1103 acolumn_spaces[acolumn] = '\0';
1105 if ((optind == argc) == !pflag_seen)
1108 if (pflag_seen && daemonized_tracer) {
1109 error_msg_and_die("-D and -p are mutually exclusive options");
1115 if (followfork > 1 && cflag) {
1116 error_msg_and_die("(-c or -C) and -ff are mutually exclusive options");
1119 /* See if they want to run as another user. */
1120 if (username != NULL) {
1121 struct passwd *pent;
1123 if (getuid() != 0 || geteuid() != 0) {
1124 error_msg_and_die("You must be root to use the -u option");
1126 pent = getpwnam(username);
1128 error_msg_and_die("Cannot find user '%s'", username);
1130 run_uid = pent->pw_uid;
1131 run_gid = pent->pw_gid;
1140 test_ptrace_setoptions_followfork();
1141 test_ptrace_setoptions_for_all();
1144 /* Check if they want to redirect the output. */
1146 /* See if they want to pipe the output. */
1147 if (outfname[0] == '|' || outfname[0] == '!') {
1149 * We can't do the <outfname>.PID funny business
1150 * when using popen, so prohibit it.
1153 error_msg_and_die("Piping the output and -ff are mutually exclusive");
1154 outf = strace_popen(outfname + 1);
1156 else if (followfork <= 1)
1157 outf = strace_fopen(outfname);
1160 if (!outfname || outfname[0] == '|' || outfname[0] == '!') {
1161 static char buf[BUFSIZ];
1162 setvbuf(outf, buf, _IOLBF, BUFSIZ);
1164 if (outfname && optind < argc) {
1169 /* Valid states here:
1170 optind < argc pflag_seen outfname interactive
1177 /* STARTUP_CHILD must be called before the signal handlers get
1178 installed below as they are inherited into the spawned process.
1179 Also we do not need to be protected by them as during interruption
1180 in the STARTUP_CHILD mode we kill the spawned process anyway. */
1182 startup_child(&argv[optind]);
1184 sigemptyset(&empty_set);
1185 sigemptyset(&blocked_set);
1186 sa.sa_handler = SIG_IGN;
1187 sigemptyset(&sa.sa_mask);
1189 sigaction(SIGTTOU, &sa, NULL);
1190 sigaction(SIGTTIN, &sa, NULL);
1192 sigaddset(&blocked_set, SIGHUP);
1193 sigaddset(&blocked_set, SIGINT);
1194 sigaddset(&blocked_set, SIGQUIT);
1195 sigaddset(&blocked_set, SIGPIPE);
1196 sigaddset(&blocked_set, SIGTERM);
1197 sa.sa_handler = interrupt;
1199 /* POSIX signals on sunos4.1 are a little broken. */
1200 sa.sa_flags = SA_INTERRUPT;
1203 sigaction(SIGHUP, &sa, NULL);
1204 sigaction(SIGINT, &sa, NULL);
1205 sigaction(SIGQUIT, &sa, NULL);
1206 sigaction(SIGPIPE, &sa, NULL);
1207 sigaction(SIGTERM, &sa, NULL);
1209 sa.sa_handler = reaper;
1210 sigaction(SIGCHLD, &sa, NULL);
1212 /* Make sure SIGCHLD has the default action so that waitpid
1213 definitely works without losing track of children. The user
1214 should not have given us a bogus state to inherit, but he might
1215 have. Arguably we should detect SIG_IGN here and pass it on
1216 to children, but probably noone really needs that. */
1217 sa.sa_handler = SIG_DFL;
1218 sigaction(SIGCHLD, &sa, NULL);
1219 #endif /* USE_PROCFS */
1221 if (pflag_seen || daemonized_tracer)
1228 if (exit_code > 0xff) {
1229 /* Child was killed by a signal, mimic that. */
1231 signal(exit_code, SIG_DFL);
1233 /* Paranoia - what if this signal is not fatal?
1234 Exit with 128 + signo then. */
1243 /* Allocate some more TCBs and expand the table.
1244 We don't want to relocate the TCBs because our
1245 callers have pointers and it would be a pain.
1246 So tcbtab is a table of pointers. Since we never
1247 free the TCBs, we allocate a single chunk of many. */
1249 struct tcb *newtcbs = calloc(tcbtabsize, sizeof(newtcbs[0]));
1250 struct tcb **newtab = realloc(tcbtab, tcbtabsize * 2 * sizeof(tcbtab[0]));
1251 if (!newtab || !newtcbs)
1252 die_out_of_memory();
1255 while (i < tcbtabsize)
1256 tcbtab[i++] = newtcbs++;
1260 alloc_tcb(int pid, int command_options_parsed)
1265 if (nprocs == tcbtabsize)
1268 for (i = 0; i < tcbtabsize; i++) {
1270 if ((tcp->flags & TCB_INUSE) == 0) {
1271 memset(tcp, 0, sizeof(*tcp));
1273 tcp->flags = TCB_INUSE | TCB_STARTUP;
1274 tcp->outf = outf; /* Initialise to current out file */
1280 fprintf(stderr, "new tcb for pid %d, active tcbs:%d\n", tcp->pid, nprocs);
1281 if (command_options_parsed)
1286 error_msg_and_die("bug in alloc_tcb");
1291 proc_open(struct tcb *tcp, int attaching)
1301 #ifndef HAVE_POLLABLE_PROCFS
1302 static int last_pfd;
1305 #ifdef HAVE_MP_PROCFS
1306 /* Open the process pseudo-files in /proc. */
1307 sprintf(proc, "/proc/%d/ctl", tcp->pid);
1308 tcp->pfd = open(proc, O_WRONLY|O_EXCL);
1310 perror("strace: open(\"/proc/...\", ...)");
1313 set_cloexec_flag(tcp->pfd);
1314 sprintf(proc, "/proc/%d/status", tcp->pid);
1315 tcp->pfd_stat = open(proc, O_RDONLY|O_EXCL);
1316 if (tcp->pfd_stat < 0) {
1317 perror("strace: open(\"/proc/...\", ...)");
1320 set_cloexec_flag(tcp->pfd_stat);
1321 sprintf(proc, "/proc/%d/as", tcp->pid);
1322 tcp->pfd_as = open(proc, O_RDONLY|O_EXCL);
1323 if (tcp->pfd_as < 0) {
1324 perror("strace: open(\"/proc/...\", ...)");
1327 set_cloexec_flag(tcp->pfd_as);
1329 /* Open the process pseudo-file in /proc. */
1331 sprintf(proc, "/proc/%d", tcp->pid);
1332 tcp->pfd = open(proc, O_RDWR|O_EXCL);
1334 sprintf(proc, "/proc/%d/mem", tcp->pid);
1335 tcp->pfd = open(proc, O_RDWR);
1338 perror("strace: open(\"/proc/...\", ...)");
1341 set_cloexec_flag(tcp->pfd);
1344 sprintf(proc, "/proc/%d/regs", tcp->pid);
1345 tcp->pfd_reg = open(proc, O_RDONLY);
1346 if (tcp->pfd_reg < 0) {
1347 perror("strace: open(\"/proc/.../regs\", ...)");
1351 sprintf(proc, "/proc/%d/status", tcp->pid);
1352 tcp->pfd_status = open(proc, O_RDONLY);
1353 if (tcp->pfd_status < 0) {
1354 perror("strace: open(\"/proc/.../status\", ...)");
1358 tcp->pfd_status = -1;
1359 #endif /* FREEBSD */
1363 * Wait for the child to pause. Because of a race
1364 * condition we have to poll for the event.
1367 if (IOCTL_STATUS(tcp) < 0) {
1368 perror("strace: PIOCSTATUS");
1371 if (tcp->status.PR_FLAGS & PR_ASLEEP)
1376 /* Stop the process so that we own the stop. */
1377 if (IOCTL(tcp->pfd, PIOCSTOP, (char *)NULL) < 0) {
1378 perror("strace: PIOCSTOP");
1383 /* Set Run-on-Last-Close. */
1385 if (IOCTL(tcp->pfd, PIOCSET, &arg) < 0) {
1386 perror("PIOCSET PR_RLC");
1389 /* Set or Reset Inherit-on-Fork. */
1391 if (IOCTL(tcp->pfd, followfork ? PIOCSET : PIOCRESET, &arg) < 0) {
1392 perror("PIOC{SET,RESET} PR_FORK");
1395 #else /* !PIOCSET */
1397 if (ioctl(tcp->pfd, PIOCSRLC) < 0) {
1401 if (ioctl(tcp->pfd, followfork ? PIOCSFORK : PIOCRFORK) < 0) {
1402 perror("PIOC{S,R}FORK");
1406 /* just unset the PF_LINGER flag for the Run-on-Last-Close. */
1407 if (ioctl(tcp->pfd, PIOCGFL, &arg) < 0) {
1412 if (ioctl(tcp->pfd, PIOCSFL, arg) < 0) {
1416 #endif /* FREEBSD */
1417 #endif /* !PIOCSET */
1419 /* Enable all syscall entries we care about. */
1420 premptyset(&syscalls);
1421 for (i = 1; i < MAX_QUALS; ++i) {
1422 if (i > (sizeof syscalls) * CHAR_BIT) break;
1423 if (qual_flags[i] & QUAL_TRACE) praddset(&syscalls, i);
1425 praddset(&syscalls, SYS_execve);
1427 praddset(&syscalls, SYS_fork);
1429 praddset(&syscalls, SYS_forkall);
1432 praddset(&syscalls, SYS_fork1);
1435 praddset(&syscalls, SYS_rfork1);
1438 praddset(&syscalls, SYS_rforkall);
1441 if (IOCTL(tcp->pfd, PIOCSENTRY, &syscalls) < 0) {
1442 perror("PIOCSENTRY");
1445 /* Enable the syscall exits. */
1446 if (IOCTL(tcp->pfd, PIOCSEXIT, &syscalls) < 0) {
1450 /* Enable signals we care about. */
1451 premptyset(&signals);
1452 for (i = 1; i < MAX_QUALS; ++i) {
1453 if (i > (sizeof signals) * CHAR_BIT) break;
1454 if (qual_flags[i] & QUAL_SIGNAL) praddset(&signals, i);
1456 if (IOCTL(tcp->pfd, PIOCSTRACE, &signals) < 0) {
1457 perror("PIOCSTRACE");
1460 /* Enable faults we care about */
1461 premptyset(&faults);
1462 for (i = 1; i < MAX_QUALS; ++i) {
1463 if (i > (sizeof faults) * CHAR_BIT) break;
1464 if (qual_flags[i] & QUAL_FAULT) praddset(&faults, i);
1466 if (IOCTL(tcp->pfd, PIOCSFAULT, &faults) < 0) {
1467 perror("PIOCSFAULT");
1471 /* set events flags. */
1472 arg = S_SIG | S_SCE | S_SCX;
1473 if (ioctl(tcp->pfd, PIOCBIS, arg) < 0) {
1477 #endif /* FREEBSD */
1481 * The SGI PRSABORT doesn't work for pause() so
1482 * we send it a caught signal to wake it up.
1484 kill(tcp->pid, SIGINT);
1487 /* The child is in a pause(), abort it. */
1489 if (IOCTL(tcp->pfd, PIOCRUN, &arg) < 0) {
1496 /* wake up the child if it received the SIGSTOP */
1497 kill(tcp->pid, SIGCONT);
1500 /* Wait for the child to do something. */
1501 if (IOCTL_WSTOP(tcp) < 0) {
1502 perror("PIOCWSTOP");
1505 if (tcp->status.PR_WHY == PR_SYSENTRY) {
1506 tcp->flags &= ~TCB_INSYSCALL;
1508 if (known_scno(tcp) == SYS_execve)
1511 /* Set it running: maybe execve will be next. */
1514 if (IOCTL(tcp->pfd, PIOCRUN, &arg) < 0)
1516 if (IOCTL(tcp->pfd, PIOCRUN, 0) < 0)
1523 /* handle the case where we "opened" the child before
1524 it did the kill -STOP */
1525 if (tcp->status.PR_WHY == PR_SIGNALLED &&
1526 tcp->status.PR_WHAT == SIGSTOP)
1527 kill(tcp->pid, SIGCONT);
1533 if (attaching < 2) {
1534 /* We are attaching to an already running process.
1535 * Try to figure out the state of the process in syscalls,
1536 * to handle the first event well.
1537 * This is done by having a look at the "wchan" property of the
1538 * process, which tells where it is stopped (if it is). */
1540 char wchan[20]; /* should be enough */
1542 sprintf(proc, "/proc/%d/status", tcp->pid);
1543 status = fopen(proc, "r");
1545 (fscanf(status, "%*s %*d %*d %*d %*d %*d,%*d %*s %*d,%*d"
1546 "%*d,%*d %*d,%*d %19s", wchan) == 1) &&
1547 strcmp(wchan, "nochan") && strcmp(wchan, "spread") &&
1548 strcmp(wchan, "stopevent")) {
1549 /* The process is asleep in the middle of a syscall.
1550 Fake the syscall entry event */
1551 tcp->flags &= ~(TCB_INSYSCALL|TCB_STARTUP);
1552 tcp->status.PR_WHY = PR_SYSENTRY;
1557 } /* otherwise it's a fork being followed */
1559 #endif /* FREEBSD */
1560 #ifndef HAVE_POLLABLE_PROCFS
1561 if (proc_poll_pipe[0] != -1)
1562 proc_poller(tcp->pfd);
1563 else if (nprocs > 1) {
1565 proc_poller(last_pfd);
1566 proc_poller(tcp->pfd);
1568 last_pfd = tcp->pfd;
1569 #endif /* !HAVE_POLLABLE_PROCFS */
1573 #endif /* USE_PROCFS */
1583 for (i = 0; i < tcbtabsize; i++) {
1584 struct tcb *tcp = tcbtab[i];
1585 if (tcp->pid == pid && (tcp->flags & TCB_INUSE))
1595 first_used_tcb(void)
1599 for (i = 0; i < tcbtabsize; i++) {
1601 if (tcp->flags & TCB_INUSE)
1612 for (i = 0; i < tcbtabsize; i++) {
1613 struct tcb *tcp = tcbtab[i];
1614 if (tcp->pfd != pfd)
1616 if (tcp->flags & TCB_INUSE)
1622 #endif /* USE_PROCFS */
1625 droptcb(struct tcb *tcp)
1632 fprintf(stderr, "dropped tcb for pid %d, %d remain\n", tcp->pid, nprocs);
1635 if (tcp->pfd != -1) {
1639 if (tcp->pfd_reg != -1) {
1640 close(tcp->pfd_reg);
1643 if (tcp->pfd_status != -1) {
1644 close(tcp->pfd_status);
1645 tcp->pfd_status = -1;
1648 tcp->flags = 0; /* rebuild_pollv needs it */
1653 if (outfname && followfork > 1 && tcp->outf)
1656 memset(tcp, 0, sizeof(*tcp));
1659 /* detach traced process; continue with sig
1660 Never call DETACH twice on the same process as both unattached and
1661 attached-unstopped processes give the same ESRCH. For unattached process we
1662 would SIGSTOP it and wait for its SIGSTOP notification forever. */
1665 detach(struct tcb *tcp, int sig)
1669 int status, catch_sigstop;
1672 if (tcp->flags & TCB_BPTSET)
1677 * Linux wrongly insists the child be stopped
1678 * before detaching. Arghh. We go through hoops
1679 * to make a clean break of things.
1682 #undef PTRACE_DETACH
1683 #define PTRACE_DETACH PTRACE_SUNDETACH
1686 * On TCB_STARTUP we did PTRACE_ATTACH but still did not get the
1687 * expected SIGSTOP. We must catch exactly one as otherwise the
1688 * detached process would be left stopped (process state T).
1690 catch_sigstop = (tcp->flags & TCB_STARTUP);
1691 error = ptrace(PTRACE_DETACH, tcp->pid, (char *) 1, sig);
1693 /* On a clear day, you can see forever. */
1695 else if (errno != ESRCH) {
1696 /* Shouldn't happen. */
1697 perror("detach: ptrace(PTRACE_DETACH, ...)");
1699 else if (my_tkill(tcp->pid, 0) < 0) {
1701 perror("detach: checking sanity");
1703 else if (!catch_sigstop && my_tkill(tcp->pid, SIGSTOP) < 0) {
1705 perror("detach: stopping child");
1709 if (catch_sigstop) {
1712 if (wait4(tcp->pid, &status, __WALL, NULL) < 0) {
1713 if (errno == ECHILD) /* Already gone. */
1715 if (errno != EINVAL) {
1716 perror("detach: waiting");
1720 /* No __WALL here. */
1721 if (waitpid(tcp->pid, &status, 0) < 0) {
1722 if (errno != ECHILD) {
1723 perror("detach: waiting");
1727 /* If no processes, try clones. */
1728 if (wait4(tcp->pid, &status, __WCLONE,
1730 if (errno != ECHILD)
1731 perror("detach: waiting");
1734 #endif /* __WCLONE */
1739 if (!WIFSTOPPED(status)) {
1740 /* Au revoir, mon ami. */
1743 if (WSTOPSIG(status) == SIGSTOP) {
1744 ptrace_restart(PTRACE_DETACH, tcp, sig);
1747 error = ptrace_restart(PTRACE_CONT, tcp,
1748 WSTOPSIG(status) == syscall_trap_sig ? 0
1749 : WSTOPSIG(status));
1757 /* PTRACE_DETACH won't respect `sig' argument, so we post it here. */
1758 if (sig && kill(tcp->pid, sig) < 0)
1759 perror("detach: kill");
1761 error = ptrace_restart(PTRACE_DETACH, tcp, sig);
1765 fprintf(stderr, "Process %u detached\n", tcp->pid);
1774 static void reaper(int sig)
1779 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
1783 #endif /* USE_PROCFS */
1791 for (i = 0; i < tcbtabsize; i++) {
1793 if (!(tcp->flags & TCB_INUSE))
1797 "cleanup: looking at pid %u\n", tcp->pid);
1799 (!outfname || followfork < 2 || tcp_last == tcp)) {
1800 tprintf(" <unfinished ...>");
1803 if (tcp->flags & TCB_ATTACHED)
1806 kill(tcp->pid, SIGCONT);
1807 kill(tcp->pid, SIGTERM);
1820 #ifndef HAVE_STRERROR
1822 #if !HAVE_DECL_SYS_ERRLIST
1823 extern int sys_nerr;
1824 extern char *sys_errlist[];
1825 #endif /* HAVE_DECL_SYS_ERRLIST */
1828 strerror(int err_no)
1830 static char buf[64];
1832 if (err_no < 1 || err_no >= sys_nerr) {
1833 sprintf(buf, "Unknown error %d", err_no);
1836 return sys_errlist[err_no];
1839 #endif /* HAVE_STERRROR */
1841 #ifndef HAVE_STRSIGNAL
1843 #if defined HAVE_SYS_SIGLIST && !defined HAVE_DECL_SYS_SIGLIST
1844 extern char *sys_siglist[];
1846 #if defined HAVE_SYS__SIGLIST && !defined HAVE_DECL__SYS_SIGLIST
1847 extern char *_sys_siglist[];
1853 static char buf[64];
1855 if (sig < 1 || sig >= NSIG) {
1856 sprintf(buf, "Unknown signal %d", sig);
1859 #ifdef HAVE__SYS_SIGLIST
1860 return _sys_siglist[sig];
1862 return sys_siglist[sig];
1866 #endif /* HAVE_STRSIGNAL */
1876 pollv = malloc(nprocs * sizeof(pollv[0]));
1878 die_out_of_memory();
1880 for (i = j = 0; i < tcbtabsize; i++) {
1881 struct tcb *tcp = tcbtab[i];
1882 if (!(tcp->flags & TCB_INUSE))
1884 pollv[j].fd = tcp->pfd;
1885 pollv[j].events = POLLWANT;
1889 error_msg_and_die("proc miscount");
1893 #ifndef HAVE_POLLABLE_PROCFS
1896 proc_poll_open(void)
1900 if (pipe(proc_poll_pipe) < 0) {
1901 perror_msg_and_die("pipe");
1903 for (i = 0; i < 2; i++) {
1904 set_cloexec_flag(proc_poll_pipe[i]);
1909 proc_poll(struct pollfd *pollv, int nfds, int timeout)
1913 struct proc_pollfd pollinfo;
1915 n = read(proc_poll_pipe[0], &pollinfo, sizeof(pollinfo));
1918 if (n != sizeof(struct proc_pollfd)) {
1919 error_msg_and_die("panic: short read: %d", n);
1921 for (i = 0; i < nprocs; i++) {
1922 if (pollv[i].fd == pollinfo.fd)
1923 pollv[i].revents = pollinfo.revents;
1925 pollv[i].revents = 0;
1927 poller_pid = pollinfo.pid;
1932 wakeup_handler(int sig)
1937 proc_poller(int pfd)
1939 struct proc_pollfd pollinfo;
1940 struct sigaction sa;
1941 sigset_t blocked_set, empty_set;
1946 struct procfs_status pfs;
1947 #endif /* FREEBSD */
1951 perror_msg_and_die("fork");
1958 sa.sa_handler = interactive ? SIG_DFL : SIG_IGN;
1960 sigemptyset(&sa.sa_mask);
1961 sigaction(SIGHUP, &sa, NULL);
1962 sigaction(SIGINT, &sa, NULL);
1963 sigaction(SIGQUIT, &sa, NULL);
1964 sigaction(SIGPIPE, &sa, NULL);
1965 sigaction(SIGTERM, &sa, NULL);
1966 sa.sa_handler = wakeup_handler;
1967 sigaction(SIGUSR1, &sa, NULL);
1968 sigemptyset(&blocked_set);
1969 sigaddset(&blocked_set, SIGUSR1);
1970 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
1971 sigemptyset(&empty_set);
1973 if (getrlimit(RLIMIT_NOFILE, &rl) < 0) {
1974 perror_msg_and_die("getrlimit(RLIMIT_NOFILE, ...)");
1977 for (i = 0; i < n; i++) {
1978 if (i != pfd && i != proc_poll_pipe[1])
1983 pollinfo.pid = getpid();
1986 if (ioctl(pfd, PIOCWSTOP, NULL) < 0)
1988 if (ioctl(pfd, PIOCWSTOP, &pfs) < 0)
1995 pollinfo.revents = POLLERR;
1998 pollinfo.revents = POLLHUP;
2001 perror("proc_poller: PIOCWSTOP");
2003 write(proc_poll_pipe[1], &pollinfo, sizeof(pollinfo));
2006 pollinfo.revents = POLLWANT;
2007 write(proc_poll_pipe[1], &pollinfo, sizeof(pollinfo));
2008 sigsuspend(&empty_set);
2012 #endif /* !HAVE_POLLABLE_PROCFS */
2022 if (followfork < 2 &&
2023 last < nprocs && (pollv[last].revents & POLLWANT)) {
2025 * The previous process is ready to run again. We'll
2026 * let it do so if it is currently in a syscall. This
2027 * heuristic improves the readability of the trace.
2029 tcp = pfd2tcb(pollv[last].fd);
2030 if (tcp && exiting(tcp))
2031 return pollv[last].fd;
2034 for (i = 0; i < nprocs; i++) {
2035 /* Let competing children run round robin. */
2036 j = (i + last + 1) % nprocs;
2037 if (pollv[j].revents & (POLLHUP | POLLERR)) {
2038 tcp = pfd2tcb(pollv[j].fd);
2040 error_msg_and_die("lost proc");
2045 if (pollv[j].revents & POLLWANT) {
2050 error_msg_and_die("nothing ready");
2057 struct tcb *in_syscall = NULL;
2062 int ioctl_result = 0, ioctl_errno = 0;
2067 sigprocmask(SIG_SETMASK, &empty_set, NULL);
2074 #ifndef HAVE_POLLABLE_PROCFS
2075 if (proc_poll_pipe[0] == -1) {
2077 tcp = first_used_tcb();
2084 #ifndef HAVE_POLLABLE_PROCFS
2086 /* fall through ... */
2087 #endif /* !HAVE_POLLABLE_PROCFS */
2089 #ifdef HAVE_POLLABLE_PROCFS
2091 /* On some systems (e.g. UnixWare) we get too much ugly
2092 "unfinished..." stuff when multiple proceses are in
2093 syscalls. Here's a nasty hack */
2100 pv.events = POLLWANT;
2101 what = poll(&pv, 1, 1);
2107 else if (what == 1 && pv.revents & POLLWANT) {
2113 if (poll(pollv, nprocs, INFTIM) < 0) {
2118 #else /* !HAVE_POLLABLE_PROCFS */
2119 if (proc_poll(pollv, nprocs, INFTIM) < 0) {
2124 #endif /* !HAVE_POLLABLE_PROCFS */
2131 /* Look up `pfd' in our table. */
2134 error_msg_and_die("unknown pfd: %u", pfd);
2139 /* Get the status of the process. */
2142 ioctl_result = IOCTL_WSTOP(tcp);
2144 /* Thanks to some scheduling mystery, the first poller
2145 sometimes waits for the already processed end of fork
2146 event. Doing a non blocking poll here solves the problem. */
2147 if (proc_poll_pipe[0] != -1)
2148 ioctl_result = IOCTL_STATUS(tcp);
2150 ioctl_result = IOCTL_WSTOP(tcp);
2151 #endif /* FREEBSD */
2152 ioctl_errno = errno;
2153 #ifndef HAVE_POLLABLE_PROCFS
2154 if (proc_poll_pipe[0] != -1) {
2155 if (ioctl_result < 0)
2156 kill(poller_pid, SIGKILL);
2158 kill(poller_pid, SIGUSR1);
2160 #endif /* !HAVE_POLLABLE_PROCFS */
2166 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
2168 if (ioctl_result < 0) {
2169 /* Find out what happened if it failed. */
2170 switch (ioctl_errno) {
2181 perror_msg_and_die("PIOCWSTOP");
2186 if ((tcp->flags & TCB_STARTUP) && (tcp->status.PR_WHY == PR_SYSEXIT)) {
2187 /* discard first event for a syscall we never entered */
2188 IOCTL(tcp->pfd, PIOCRUN, 0);
2193 /* clear the just started flag */
2194 tcp->flags &= ~TCB_STARTUP;
2196 /* set current output file */
2198 curcol = tcp->curcol;
2201 struct timeval stime;
2206 len = pread(tcp->pfd_status, buf, sizeof(buf) - 1, 0);
2210 "%*s %*d %*d %*d %*d %*d,%*d %*s %*d,%*d %*d,%*d %ld,%ld",
2211 &stime.tv_sec, &stime.tv_usec);
2213 stime.tv_sec = stime.tv_usec = 0;
2214 #else /* !FREEBSD */
2215 stime.tv_sec = tcp->status.pr_stime.tv_sec;
2216 stime.tv_usec = tcp->status.pr_stime.tv_nsec/1000;
2217 #endif /* !FREEBSD */
2218 tv_sub(&tcp->dtime, &stime, &tcp->stime);
2221 what = tcp->status.PR_WHAT;
2222 switch (tcp->status.PR_WHY) {
2225 if (tcp->status.PR_FLAGS & PR_ASLEEP) {
2226 tcp->status.PR_WHY = PR_SYSENTRY;
2227 if (trace_syscall(tcp) < 0) {
2228 error_msg_and_die("syscall trouble");
2232 #endif /* !FREEBSD */
2238 if (trace_syscall(tcp) < 0) {
2239 error_msg_and_die("syscall trouble");
2243 if (cflag != CFLAG_ONLY_STATS
2244 && (qual_flags[what] & QUAL_SIGNAL)) {
2246 tprintf("--- %s (%s) ---",
2247 signame(what), strsignal(what));
2250 if (tcp->status.PR_INFO.si_signo == what) {
2252 tprintf(" siginfo=");
2253 printsiginfo(&tcp->status.PR_INFO, 1);
2260 if (cflag != CFLAGS_ONLY_STATS
2261 && (qual_flags[what] & QUAL_FAULT)) {
2263 tprintf("=== FAULT %d ===", what);
2268 case 0: /* handle case we polled for nothing */
2272 error_msg_and_die("odd stop %d", tcp->status.PR_WHY);
2275 /* Remember current print column before continuing. */
2276 tcp->curcol = curcol;
2279 if (IOCTL(tcp->pfd, PIOCRUN, &arg) < 0)
2281 if (IOCTL(tcp->pfd, PIOCRUN, 0) < 0)
2284 perror_msg_and_die("PIOCRUN");
2290 #else /* !USE_PROCFS */
2301 struct rusage *rup = cflag ? &ru : NULL;
2303 static int wait4_options = __WALL;
2307 while (nprocs != 0) {
2311 sigprocmask(SIG_SETMASK, &empty_set, NULL);
2314 pid = wait4(-1, &status, wait4_options, rup);
2315 if (pid < 0 && (wait4_options & __WALL) && errno == EINVAL) {
2316 /* this kernel does not support __WALL */
2317 wait4_options &= ~__WALL;
2318 pid = wait4(-1, &status, wait4_options, rup);
2320 if (pid < 0 && !(wait4_options & __WALL) && errno == ECHILD) {
2321 /* most likely a "cloned" process */
2322 pid = wait4(-1, &status, __WCLONE, rup);
2324 perror_msg("wait4(__WCLONE) failed");
2328 pid = wait4(-1, &status, 0, rup);
2329 # endif /* __WALL */
2332 pid = wait(&status);
2336 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
2339 switch (wait_errno) {
2344 * We would like to verify this case
2345 * but sometimes a race in Solbourne's
2346 * version of SunOS sometimes reports
2347 * ECHILD before sending us SIGCHILD.
2352 perror("strace: wait");
2356 if (pid == popen_pid) {
2357 if (WIFEXITED(status) || WIFSIGNALED(status))
2362 char buf[sizeof("WIFEXITED,exitcode=%u") + sizeof(int)*3 /*paranoia:*/ + 16];
2364 unsigned ev = (unsigned)status >> 16;
2366 static const char *const event_names[] = {
2367 [PTRACE_EVENT_CLONE] = "CLONE",
2368 [PTRACE_EVENT_FORK] = "FORK",
2369 [PTRACE_EVENT_VFORK] = "VFORK",
2370 [PTRACE_EVENT_VFORK_DONE] = "VFORK_DONE",
2371 [PTRACE_EVENT_EXEC] = "EXEC",
2372 [PTRACE_EVENT_EXIT] = "EXIT",
2375 if (ev < ARRAY_SIZE(event_names))
2376 e = event_names[ev];
2378 sprintf(buf, "?? (%u)", ev);
2381 fprintf(stderr, " PTRACE_EVENT_%s", e);
2385 if (WIFSIGNALED(status))
2387 sprintf(buf, "WIFSIGNALED,%ssig=%s",
2388 WCOREDUMP(status) ? "core," : "",
2389 signame(WTERMSIG(status)));
2391 sprintf(buf, "WIFSIGNALED,sig=%s",
2392 signame(WTERMSIG(status)));
2394 if (WIFEXITED(status))
2395 sprintf(buf, "WIFEXITED,exitcode=%u", WEXITSTATUS(status));
2396 if (WIFSTOPPED(status))
2397 sprintf(buf, "WIFSTOPPED,sig=%s", signame(WSTOPSIG(status)));
2399 if (WIFCONTINUED(status))
2400 strcpy(buf, "WIFCONTINUED");
2402 fprintf(stderr, " [wait(0x%04x) = %u] %s\n", status, pid, buf);
2405 /* Look up `pid' in our table. */
2410 /* This is needed to go with the CLONE_PTRACE
2411 changes in process.c/util.c: we might see
2412 the child's initial trap before we see the
2413 parent return from the clone syscall.
2414 Leave the child suspended until the parent
2415 returns from its system call. Only then
2416 will we have the association of parent and
2417 child so that we know how to do clearbpt
2419 tcp = alloctcb(pid);
2420 tcp->flags |= TCB_ATTACHED;
2422 fprintf(stderr, "Process %d attached\n",
2426 /* This can happen if a clone call used
2427 CLONE_PTRACE itself. */
2430 if (WIFSTOPPED(status))
2431 ptrace(PTRACE_CONT, pid, (char *) 1, 0);
2432 error_msg_and_die("Unknown pid: %u", pid);
2435 /* set current output file */
2437 curcol = tcp->curcol;
2440 tv_sub(&tcp->dtime, &ru.ru_stime, &tcp->stime);
2441 tcp->stime = ru.ru_stime;
2445 if (WIFSIGNALED(status)) {
2446 if (pid == strace_child)
2447 exit_code = 0x100 | WTERMSIG(status);
2448 if (cflag != CFLAG_ONLY_STATS
2449 && (qual_flags[WTERMSIG(status)] & QUAL_SIGNAL)) {
2452 tprintf("+++ killed by %s %s+++",
2453 signame(WTERMSIG(status)),
2454 WCOREDUMP(status) ? "(core dumped) " : "");
2456 tprintf("+++ killed by %s +++",
2457 signame(WTERMSIG(status)));
2464 if (WIFEXITED(status)) {
2465 if (pid == strace_child)
2466 exit_code = WEXITSTATUS(status);
2467 if (tcp == tcp_last) {
2468 if ((tcp->flags & (TCB_INSYSCALL|TCB_REPRINT)) == TCB_INSYSCALL)
2469 tprintf(" <unfinished ... exit status %d>\n",
2470 WEXITSTATUS(status));
2473 if (!cflag /* && (qual_flags[WTERMSIG(status)] & QUAL_SIGNAL) */ ) {
2475 tprintf("+++ exited with %d +++", WEXITSTATUS(status));
2481 if (!WIFSTOPPED(status)) {
2482 fprintf(stderr, "PANIC: pid %u not stopped\n", pid);
2488 /* Ptrace event (we ignore all of them for now) */
2493 * Interestingly, the process may stop
2494 * with STOPSIG equal to some other signal
2495 * than SIGSTOP if we happend to attach
2496 * just before the process takes a signal.
2497 * A no-MMU vforked child won't send up a signal,
2498 * so skip the first (lost) execve notification.
2500 if ((tcp->flags & TCB_STARTUP) &&
2501 (WSTOPSIG(status) == SIGSTOP || strace_vforked)) {
2503 * This flag is there to keep us in sync.
2504 * Next time this process stops it should
2505 * really be entering a system call.
2507 tcp->flags &= ~TCB_STARTUP;
2508 if (tcp->flags & TCB_BPTSET) {
2510 * One example is a breakpoint inherited from
2511 * parent through fork().
2513 if (clearbpt(tcp) < 0) /* Pretty fatal */ {
2520 if (ptrace_setoptions) {
2522 fprintf(stderr, "setting opts %x on pid %d\n", ptrace_setoptions, tcp->pid);
2523 if (ptrace(PTRACE_SETOPTIONS, tcp->pid, NULL, ptrace_setoptions) < 0) {
2524 if (errno != ESRCH) {
2525 /* Should never happen, really */
2526 perror_msg_and_die("PTRACE_SETOPTIONS");
2534 if (WSTOPSIG(status) != syscall_trap_sig) {
2535 if (WSTOPSIG(status) == SIGSTOP &&
2536 (tcp->flags & TCB_SIGTRAPPED)) {
2538 * Trapped attempt to block SIGTRAP
2539 * Hope we are back in control now.
2541 tcp->flags &= ~(TCB_INSYSCALL | TCB_SIGTRAPPED);
2542 if (ptrace_restart(PTRACE_SYSCALL, tcp, 0) < 0) {
2548 if (cflag != CFLAG_ONLY_STATS
2549 && (qual_flags[WSTOPSIG(status)] & QUAL_SIGNAL)) {
2551 #if defined(PT_CR_IPSR) && defined(PT_CR_IIP)
2555 upeek(tcp, PT_CR_IPSR, &psr);
2556 upeek(tcp, PT_CR_IIP, &pc);
2559 pc += (psr >> PSR_RI) & 0x3;
2560 # define PC_FORMAT_STR " @ %lx"
2561 # define PC_FORMAT_ARG , pc
2563 # define PC_FORMAT_STR ""
2564 # define PC_FORMAT_ARG /* nothing */
2567 if (ptrace(PTRACE_GETSIGINFO, pid, 0, &si) == 0) {
2569 printsiginfo(&si, verbose(tcp));
2570 tprintf(" (%s)" PC_FORMAT_STR " ---",
2571 strsignal(WSTOPSIG(status))
2574 tprintf("--- %s by %s" PC_FORMAT_STR " ---",
2575 strsignal(WSTOPSIG(status)),
2576 signame(WSTOPSIG(status))
2580 if (ptrace_restart(PTRACE_SYSCALL, tcp, WSTOPSIG(status)) < 0) {
2587 /* We handled quick cases, we are permitted to interrupt now. */
2591 /* This should be syscall entry or exit.
2592 * (Or it still can be that pesky post-execve SIGTRAP!)
2595 if (trace_syscall(tcp) < 0 && !tcp->ptrace_errno) {
2596 /* ptrace() failed in trace_syscall() with ESRCH.
2597 * Likely a result of process disappearing mid-flight.
2598 * Observed case: exit_group() terminating
2599 * all processes in thread group. In this case, threads
2600 * "disappear" in an unpredictable moment without any
2601 * notification to strace via wait().
2603 if (tcp->flags & TCB_ATTACHED) {
2605 /* Do we have dangling line "syscall(param, param"?
2606 * Finish the line then.
2608 tcp_last->flags |= TCB_REPRINT;
2609 tprintf(" <unfinished ...>");
2615 tcp->pid, (char *) 1, SIGTERM);
2621 /* Remember current print column before continuing. */
2622 tcp->curcol = curcol;
2623 if (ptrace_restart(PTRACE_SYSCALL, tcp, 0) < 0) {
2631 #endif /* !USE_PROCFS */
2634 tprintf(const char *fmt, ...)
2638 va_start(args, fmt);
2640 int n = vfprintf(outf, fmt, args);
2643 perror(outfname == NULL
2644 ? "<writing to pipe>" : outfname);
2653 printleader(struct tcb *tcp)
2656 if (tcp_last->ptrace_errno) {
2657 if (tcp_last->flags & TCB_INSYSCALL) {
2658 tprintf(" <unavailable>) ");
2661 tprintf("= ? <unavailable>\n");
2662 tcp_last->ptrace_errno = 0;
2663 } else if (!outfname || followfork < 2 || tcp_last == tcp) {
2664 tcp_last->flags |= TCB_REPRINT;
2665 tprintf(" <unfinished ...>\n");
2669 if ((followfork == 1 || pflag_seen > 1) && outfname)
2670 tprintf("%-5d ", tcp->pid);
2671 else if (nprocs > 1 && !outfname)
2672 tprintf("[pid %5u] ", tcp->pid);
2674 char str[sizeof("HH:MM:SS")];
2675 struct timeval tv, dtv;
2676 static struct timeval otv;
2678 gettimeofday(&tv, NULL);
2680 if (otv.tv_sec == 0)
2682 tv_sub(&dtv, &tv, &otv);
2683 tprintf("%6ld.%06ld ",
2684 (long) dtv.tv_sec, (long) dtv.tv_usec);
2687 else if (tflag > 2) {
2688 tprintf("%ld.%06ld ",
2689 (long) tv.tv_sec, (long) tv.tv_usec);
2692 time_t local = tv.tv_sec;
2693 strftime(str, sizeof(str), "%T", localtime(&local));
2695 tprintf("%s.%06ld ", str, (long) tv.tv_usec);
2697 tprintf("%s ", str);
2707 if (curcol < acolumn)
2708 tprintf(acolumn_spaces + curcol);
2718 #ifdef HAVE_MP_PROCFS
2721 mp_ioctl(int fd, int cmd, void *arg, int size)
2723 struct iovec iov[2];
2726 iov[0].iov_base = &cmd;
2727 iov[0].iov_len = sizeof cmd;
2730 iov[1].iov_base = arg;
2731 iov[1].iov_len = size;
2734 return writev(fd, iov, n);