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>
38 #include <sys/param.h>
40 #include <sys/resource.h>
50 # include <asm/unistd.h>
51 # if defined __NR_tgkill
52 # define my_tgkill(pid, tid, sig) syscall (__NR_tgkill, (pid), (tid), (sig))
53 # elif defined __NR_tkill
54 # define my_tgkill(pid, tid, sig) syscall (__NR_tkill, (tid), (sig))
56 /* kill() may choose arbitrarily the target task of the process group
57 while we later wait on a that specific TID. PID process waits become
58 TID task specific waits for a process under ptrace(2). */
59 # warning "Neither tkill(2) nor tgkill(2) available, risk of strace hangs!"
60 # define my_tgkill(pid, tid, sig) kill ((tid), (sig))
64 #if defined(IA64) && defined(LINUX)
65 # include <asm/ptrace_offsets.h>
73 #include <sys/stropts.h>
80 extern char **environ;
85 int debug = 0, followfork = 0;
86 int dtime = 0, cflag = 0, xflag = 0, qflag = 0;
87 static int iflag = 0, interactive = 0, pflag_seen = 0, rflag = 0, tflag = 0;
89 * daemonized_tracer supports -D option.
90 * With this option, strace forks twice.
91 * Unlike normal case, with -D *grandparent* process exec's,
92 * becoming a traced process. Child exits (this prevents traced process
93 * from having children it doesn't expect to have), and grandchild
94 * attaches to grandparent similarly to strace -p PID.
95 * This allows for more transparent interaction in cases
96 * when process and its parent are communicating via signals,
97 * wait() etc. Without -D, strace process gets lodged in between,
98 * disrupting parent<->child link.
100 static bool daemonized_tracer = 0;
102 /* Sometimes we want to print only succeeding syscalls. */
103 int not_failing_only = 0;
105 static int exit_code = 0;
106 static int strace_child = 0;
108 static char *username = NULL;
112 int acolumn = DEFAULT_ACOLUMN;
113 int max_strlen = DEFAULT_STRLEN;
114 static char *outfname = NULL;
117 unsigned int nprocs, tcbtabsize;
119 extern char **environ;
121 static int detach P((struct tcb *tcp, int sig));
122 static int trace P((void));
123 static void cleanup P((void));
124 static void interrupt P((int sig));
125 static sigset_t empty_set, blocked_set;
127 #ifdef HAVE_SIG_ATOMIC_T
128 static volatile sig_atomic_t interrupted;
129 #else /* !HAVE_SIG_ATOMIC_T */
131 static volatile int interrupted;
132 #else /* !__STDC__ */
133 static int interrupted;
134 #endif /* !__STDC__ */
135 #endif /* !HAVE_SIG_ATOMIC_T */
139 static struct tcb *pfd2tcb P((int pfd));
140 static void reaper P((int sig));
141 static void rebuild_pollv P((void));
142 static struct pollfd *pollv;
144 #ifndef HAVE_POLLABLE_PROCFS
146 static void proc_poll_open P((void));
147 static void proc_poller P((int pfd));
155 static int poller_pid;
156 static int proc_poll_pipe[2] = { -1, -1 };
158 #endif /* !HAVE_POLLABLE_PROCFS */
160 #ifdef HAVE_MP_PROCFS
161 #define POLLWANT POLLWRNORM
163 #define POLLWANT POLLPRI
165 #endif /* USE_PROCFS */
173 usage: strace [-dffhiqrtttTvVxx] [-a column] [-e expr] ... [-o file]\n\
174 [-p pid] ... [-s strsize] [-u username] [-E var=val] ...\n\
175 [command [arg ...]]\n\
176 or: strace -c -D [-e expr] ... [-O overhead] [-S sortby] [-E var=val] ...\n\
177 [command [arg ...]]\n\
178 -c -- count time, calls, and errors for each syscall and report summary\n\
179 -f -- follow forks, -ff -- with output into separate files\n\
180 -F -- attempt to follow vforks, -h -- print help message\n\
181 -i -- print instruction pointer at time of syscall\n\
182 -q -- suppress messages about attaching, detaching, etc.\n\
183 -r -- print relative timestamp, -t -- absolute timestamp, -tt -- with usecs\n\
184 -T -- print time spent in each syscall, -V -- print version\n\
185 -v -- verbose mode: print unabbreviated argv, stat, termio[s], etc. args\n\
186 -x -- print non-ascii strings in hex, -xx -- print all strings in hex\n\
187 -a column -- alignment COLUMN for printing syscall results (default %d)\n\
188 -e expr -- a qualifying expression: option=[!]all or option=[!]val1[,val2]...\n\
189 options: trace, abbrev, verbose, raw, signal, read, or write\n\
190 -o file -- send trace output to FILE instead of stderr\n\
191 -O overhead -- set overhead for tracing syscalls to OVERHEAD usecs\n\
192 -p pid -- trace process with process id PID, may be repeated\n\
193 -D -- run tracer process as a detached grandchild, not as parent\n\
194 -s strsize -- limit length of print strings to STRSIZE chars (default %d)\n\
195 -S sortby -- sort syscall counts by: time, calls, name, nothing (default %s)\n\
196 -u username -- run command as username handling setuid and/or setgid\n\
197 -E var=val -- put var=val in the environment for command\n\
198 -E var -- remove var from the environment for command\n\
199 " /* this is broken, so don't document it
200 -z -- print only succeeding syscalls\n\
202 , DEFAULT_ACOLUMN, DEFAULT_STRLEN, DEFAULT_SORTBY);
216 set_cloexec_flag(int fd)
220 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
222 fprintf(stderr, "%s: fcntl F_GETFD: %s\n",
223 progname, strerror(errno));
227 newflags = flags | FD_CLOEXEC;
228 if (flags == newflags)
231 if (fcntl(fd, F_SETFD, newflags) < 0)
233 fprintf(stderr, "%s: fcntl F_SETFD: %s\n",
234 progname, strerror(errno));
242 * When strace is setuid executable, we have to swap uids
243 * before and after filesystem and process management operations.
249 int euid = geteuid(), uid = getuid();
251 if (euid != uid && setreuid(euid, uid) < 0)
253 fprintf(stderr, "%s: setreuid: %s\n",
254 progname, strerror(errno));
261 # define fopen_for_output fopen64
263 # define fopen_for_output fopen
267 strace_fopen(const char *path, const char *mode)
272 if ((fp = fopen_for_output(path, mode)) == NULL)
273 fprintf(stderr, "%s: can't fopen '%s': %s\n",
274 progname, path, strerror(errno));
276 if (fp && set_cloexec_flag(fileno(fp)) < 0)
284 static int popen_pid = -1;
287 # define _PATH_BSHELL "/bin/sh"
291 * We cannot use standard popen(3) here because we have to distinguish
292 * popen child process from other processes we trace, and standard popen(3)
293 * does not export its child's pid.
296 strace_popen(const char *command)
303 fprintf(stderr, "%s: pipe: %s\n",
304 progname, strerror(errno));
309 if (set_cloexec_flag(fds[1]) < 0)
317 if ((popen_pid = fork()) == -1)
319 fprintf(stderr, "%s: fork: %s\n",
320 progname, strerror(errno));
332 return fdopen(fds[1], "w");
337 if (fds[0] && (dup2(fds[0], 0) || close(fds[0])))
339 fprintf(stderr, "%s: dup2: %s\n",
340 progname, strerror(errno));
343 execl(_PATH_BSHELL, "sh", "-c", command, NULL);
344 fprintf(stderr, "%s: execl: %s: %s\n",
345 progname, _PATH_BSHELL, strerror(errno));
351 newoutf(struct tcb *tcp)
353 if (outfname && followfork > 1) {
354 char name[520 + sizeof(int) * 3];
357 sprintf(name, "%.512s.%u", outfname, tcp->pid);
358 if ((fp = strace_fopen(name, "w")) == NULL)
372 * Block user interruptions as we would leave the traced
373 * process stopped (process state T) if we would terminate in
374 * between PTRACE_ATTACH and wait4 () on SIGSTOP.
375 * We rely on cleanup () from this point on.
378 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
380 if (daemonized_tracer) {
385 if (pid) { /* parent */
387 * Wait for child to attach to straced process
388 * (our parent). Child SIGKILLs us after it attached.
389 * Parent's wait() is unblocked by our death,
390 * it proceeds to exec the straced program.
393 _exit(0); /* paranoia */
397 for (tcbi = 0; tcbi < tcbtabsize; tcbi++) {
399 if (!(tcp->flags & TCB_INUSE) || !(tcp->flags & TCB_ATTACHED))
402 if (tcp->flags & TCB_CLONE_THREAD)
405 /* Reinitialize the output since it may have changed. */
407 if (newoutf(tcp) < 0)
411 if (proc_open(tcp, 1) < 0) {
412 fprintf(stderr, "trouble opening proc file\n");
416 #else /* !USE_PROCFS */
418 if (followfork && !daemonized_tracer) {
419 char procdir[sizeof("/proc/%d/task") + sizeof(int) * 3];
422 sprintf(procdir, "/proc/%d/task", tcp->pid);
423 dir = opendir(procdir);
425 unsigned int ntid = 0, nerr = 0;
428 while ((de = readdir(dir)) != NULL) {
429 if (de->d_fileno == 0)
431 tid = atoi(de->d_name);
435 if (ptrace(PTRACE_ATTACH, tid, (char *) 1, 0) < 0)
437 else if (tid != tcbtab[tcbi]->pid) {
439 tcp->flags |= TCB_ATTACHED|TCB_CLONE_THREAD|TCB_CLONE_DETACHED|TCB_FOLLOWFORK;
440 tcbtab[tcbi]->nchildren++;
441 tcbtab[tcbi]->nclone_threads++;
442 tcbtab[tcbi]->nclone_detached++;
443 tcp->parent = tcbtab[tcbi];
446 sigprocmask(SIG_SETMASK, &empty_set, NULL);
449 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
455 perror("attach: ptrace(PTRACE_ATTACH, ...)");
460 fprintf(stderr, ntid > 1
461 ? "Process %u attached with %u threads - interrupt to quit\n"
462 : "Process %u attached - interrupt to quit\n",
463 tcbtab[tcbi]->pid, ntid);
466 } /* if (opendir worked) */
469 if (ptrace(PTRACE_ATTACH, tcp->pid, (char *) 1, 0) < 0) {
470 perror("attach: ptrace(PTRACE_ATTACH, ...)");
474 /* INTERRUPTED is going to be checked at the top of TRACE. */
476 if (daemonized_tracer) {
478 * It is our grandparent we trace, not a -p PID.
479 * Don't want to just detach on exit, so...
481 tcp->flags &= ~TCB_ATTACHED;
483 * Make parent go away.
484 * Also makes grandparent's wait() unblock.
486 kill(getppid(), SIGKILL);
489 #endif /* !USE_PROCFS */
492 "Process %u attached - interrupt to quit\n",
497 sigprocmask(SIG_SETMASK, &empty_set, NULL);
501 startup_child (char **argv)
504 const char *filename;
505 char pathname[MAXPATHLEN];
510 if (strchr(filename, '/')) {
511 if (strlen(filename) > sizeof pathname - 1) {
512 errno = ENAMETOOLONG;
513 perror("strace: exec");
516 strcpy(pathname, filename);
518 #ifdef USE_DEBUGGING_EXEC
520 * Debuggers customarily check the current directory
521 * first regardless of the path but doing that gives
522 * security geeks a panic attack.
524 else if (stat(filename, &statbuf) == 0)
525 strcpy(pathname, filename);
526 #endif /* USE_DEBUGGING_EXEC */
531 for (path = getenv("PATH"); path && *path; path += m) {
532 if (strchr(path, ':')) {
533 n = strchr(path, ':') - path;
537 m = n = strlen(path);
539 if (!getcwd(pathname, MAXPATHLEN))
541 len = strlen(pathname);
543 else if (n > sizeof pathname - 1)
546 strncpy(pathname, path, n);
549 if (len && pathname[len - 1] != '/')
550 pathname[len++] = '/';
551 strcpy(pathname + len, filename);
552 if (stat(pathname, &statbuf) == 0 &&
553 /* Accept only regular files
554 with some execute bits set.
555 XXX not perfect, might still fail */
556 S_ISREG(statbuf.st_mode) &&
557 (statbuf.st_mode & 0111))
561 if (stat(pathname, &statbuf) < 0) {
562 fprintf(stderr, "%s: %s: command not found\n",
566 strace_child = pid = fork();
568 perror("strace: fork");
572 if ((pid != 0 && daemonized_tracer) /* parent: to become a traced process */
573 || (pid == 0 && !daemonized_tracer) /* child: to become a traced process */
577 if (outf != stderr) close (fileno (outf));
579 /* Kludge for SGI, see proc_open for details. */
580 sa.sa_handler = foobar;
582 sigemptyset(&sa.sa_mask);
583 sigaction(SIGINT, &sa, NULL);
588 kill(pid, SIGSTOP); /* stop HERE */
590 #else /* !USE_PROCFS */
592 close(fileno (outf));
594 if (!daemonized_tracer) {
595 if (ptrace(PTRACE_TRACEME, 0, (char *) 1, 0) < 0) {
596 perror("strace: ptrace(PTRACE_TRACEME, ...)");
603 if (username != NULL || geteuid() == 0) {
604 uid_t run_euid = run_uid;
605 gid_t run_egid = run_gid;
607 if (statbuf.st_mode & S_ISUID)
608 run_euid = statbuf.st_uid;
609 if (statbuf.st_mode & S_ISGID)
610 run_egid = statbuf.st_gid;
613 * It is important to set groups before we
614 * lose privileges on setuid.
616 if (username != NULL) {
617 if (initgroups(username, run_gid) < 0) {
618 perror("initgroups");
621 if (setregid(run_gid, run_egid) < 0) {
625 if (setreuid(run_uid, run_euid) < 0) {
632 setreuid(run_uid, run_uid);
634 if (!daemonized_tracer) {
636 * Induce an immediate stop so that the parent
637 * will resume us with PTRACE_SYSCALL and display
638 * this execve call normally.
640 kill(getpid(), SIGSTOP);
642 struct sigaction sv_sigchld;
643 sigaction(SIGCHLD, NULL, &sv_sigchld);
645 * Make sure it is not SIG_IGN, otherwise wait
648 signal(SIGCHLD, SIG_DFL);
650 * Wait for grandchild to attach to us.
651 * It kills child after that, and wait() unblocks.
656 sigaction(SIGCHLD, &sv_sigchld, NULL);
658 #endif /* !USE_PROCFS */
660 execv(pathname, argv);
661 perror("strace: exec");
665 /* We are the tracer. */
666 tcp = alloctcb(daemonized_tracer ? getppid() : pid);
667 if (daemonized_tracer) {
668 /* We want subsequent startup_attach() to attach to it. */
669 tcp->flags |= TCB_ATTACHED;
672 if (proc_open(tcp, 0) < 0) {
673 fprintf(stderr, "trouble opening proc file\n");
677 #endif /* USE_PROCFS */
681 main(int argc, char *argv[])
688 static char buf[BUFSIZ];
690 progname = argv[0] ? argv[0] : "strace";
692 /* Allocate the initial tcbtab. */
693 tcbtabsize = argc; /* Surely enough for all -p args. */
694 if ((tcbtab = calloc(tcbtabsize, sizeof tcbtab[0])) == NULL) {
695 fprintf(stderr, "%s: out of memory\n", progname);
698 if ((tcbtab[0] = calloc(tcbtabsize, sizeof tcbtab[0][0])) == NULL) {
699 fprintf(stderr, "%s: out of memory\n", progname);
702 for (tcp = tcbtab[0]; tcp < &tcbtab[0][tcbtabsize]; ++tcp)
703 tcbtab[tcp - tcbtab[0]] = &tcbtab[0][tcp - tcbtab[0]];
707 set_sortby(DEFAULT_SORTBY);
708 set_personality(DEFAULT_PERSONALITY);
709 qualify("trace=all");
710 qualify("abbrev=all");
711 qualify("verbose=all");
712 qualify("signal=all");
713 while ((c = getopt(argc, argv,
718 "a:e:o:O:p:s:S:u:E:")) != EOF) {
728 /* Experimental, not documented in manpage yet. */
730 daemonized_tracer = 1;
762 qualify("abbrev=none");
765 printf("%s -- version %s\n", PACKAGE_NAME, VERSION);
769 not_failing_only = 1;
772 acolumn = atoi(optarg);
778 outfname = strdup(optarg);
781 set_overhead(atoi(optarg));
784 if ((pid = atoi(optarg)) <= 0) {
785 fprintf(stderr, "%s: Invalid process id: %s\n",
789 if (pid == getpid()) {
790 fprintf(stderr, "%s: I'm sorry, I can't let you do that, Dave.\n", progname);
793 tcp = alloc_tcb(pid, 0);
794 tcp->flags |= TCB_ATTACHED;
798 max_strlen = atoi(optarg);
799 if (max_strlen < 0) {
801 "%s: invalid -s argument: %s\n",
810 username = strdup(optarg);
813 if (putenv(optarg) < 0) {
814 fprintf(stderr, "%s: out of memory\n",
825 if ((optind == argc) == !pflag_seen)
831 if (followfork > 1 && cflag) {
833 "%s: -c and -ff are mutually exclusive options\n",
838 /* See if they want to run as another user. */
839 if (username != NULL) {
842 if (getuid() != 0 || geteuid() != 0) {
844 "%s: you must be root to use the -u option\n",
848 if ((pent = getpwnam(username)) == NULL) {
849 fprintf(stderr, "%s: cannot find user `%s'\n",
853 run_uid = pent->pw_uid;
854 run_gid = pent->pw_gid;
861 /* Check if they want to redirect the output. */
863 /* See if they want to pipe the output. */
864 if (outfname[0] == '|' || outfname[0] == '!') {
866 * We can't do the <outfname>.PID funny business
867 * when using popen, so prohibit it.
869 if (followfork > 1) {
871 %s: piping the output and -ff are mutually exclusive options\n",
876 if ((outf = strace_popen(outfname + 1)) == NULL)
879 else if (followfork <= 1 &&
880 (outf = strace_fopen(outfname, "w")) == NULL)
884 if (!outfname || outfname[0] == '|' || outfname[0] == '!')
885 setvbuf(outf, buf, _IOLBF, BUFSIZ);
886 if (outfname && optind < argc) {
890 /* Valid states here:
891 optind < argc pflag_seen outfname interactive
898 /* STARTUP_CHILD must be called before the signal handlers get
899 installed below as they are inherited into the spawned process.
900 Also we do not need to be protected by them as during interruption
901 in the STARTUP_CHILD mode we kill the spawned process anyway. */
903 startup_child(&argv[optind]);
905 sigemptyset(&empty_set);
906 sigemptyset(&blocked_set);
907 sa.sa_handler = SIG_IGN;
908 sigemptyset(&sa.sa_mask);
910 sigaction(SIGTTOU, &sa, NULL);
911 sigaction(SIGTTIN, &sa, NULL);
913 sigaddset(&blocked_set, SIGHUP);
914 sigaddset(&blocked_set, SIGINT);
915 sigaddset(&blocked_set, SIGQUIT);
916 sigaddset(&blocked_set, SIGPIPE);
917 sigaddset(&blocked_set, SIGTERM);
918 sa.sa_handler = interrupt;
920 /* POSIX signals on sunos4.1 are a little broken. */
921 sa.sa_flags = SA_INTERRUPT;
924 sigaction(SIGHUP, &sa, NULL);
925 sigaction(SIGINT, &sa, NULL);
926 sigaction(SIGQUIT, &sa, NULL);
927 sigaction(SIGPIPE, &sa, NULL);
928 sigaction(SIGTERM, &sa, NULL);
930 sa.sa_handler = reaper;
931 sigaction(SIGCHLD, &sa, NULL);
933 /* Make sure SIGCHLD has the default action so that waitpid
934 definitely works without losing track of children. The user
935 should not have given us a bogus state to inherit, but he might
936 have. Arguably we should detect SIG_IGN here and pass it on
937 to children, but probably noone really needs that. */
938 sa.sa_handler = SIG_DFL;
939 sigaction(SIGCHLD, &sa, NULL);
940 #endif /* USE_PROCFS */
942 if (pflag_seen || daemonized_tracer)
949 if (exit_code > 0xff) {
950 /* Child was killed by a signal, mimic that. */
952 signal(exit_code, SIG_DFL);
954 /* Paranoia - what if this signal is not fatal?
955 Exit with 128 + signo then. */
964 /* Allocate some more TCBs and expand the table.
965 We don't want to relocate the TCBs because our
966 callers have pointers and it would be a pain.
967 So tcbtab is a table of pointers. Since we never
968 free the TCBs, we allocate a single chunk of many. */
969 struct tcb **newtab = (struct tcb **)
970 realloc(tcbtab, 2 * tcbtabsize * sizeof tcbtab[0]);
971 struct tcb *newtcbs = (struct tcb *) calloc(tcbtabsize,
974 if (newtab == NULL || newtcbs == NULL) {
975 fprintf(stderr, "%s: expand_tcbtab: out of memory\n",
980 for (i = tcbtabsize; i < 2 * tcbtabsize; ++i)
981 newtab[i] = &newtcbs[i - tcbtabsize];
987 alloc_tcb(int pid, int command_options_parsed)
992 if (nprocs == tcbtabsize)
995 for (i = 0; i < tcbtabsize; i++) {
997 if ((tcp->flags & TCB_INUSE) == 0) {
1002 #ifdef TCB_CLONE_THREAD
1003 tcp->nclone_threads = tcp->nclone_detached = 0;
1004 tcp->nclone_waiting = 0;
1006 tcp->flags = TCB_INUSE | TCB_STARTUP;
1007 tcp->outf = outf; /* Initialise to current out file */
1008 tcp->stime.tv_sec = 0;
1009 tcp->stime.tv_usec = 0;
1012 if (command_options_parsed)
1017 fprintf(stderr, "%s: bug in alloc_tcb\n", progname);
1024 proc_open(struct tcb *tcp, int attaching)
1034 #ifndef HAVE_POLLABLE_PROCFS
1035 static int last_pfd;
1038 #ifdef HAVE_MP_PROCFS
1039 /* Open the process pseudo-files in /proc. */
1040 sprintf(proc, "/proc/%d/ctl", tcp->pid);
1041 if ((tcp->pfd = open(proc, O_WRONLY|O_EXCL)) < 0) {
1042 perror("strace: open(\"/proc/...\", ...)");
1045 if (set_cloexec_flag(tcp->pfd) < 0) {
1048 sprintf(proc, "/proc/%d/status", tcp->pid);
1049 if ((tcp->pfd_stat = open(proc, O_RDONLY|O_EXCL)) < 0) {
1050 perror("strace: open(\"/proc/...\", ...)");
1053 if (set_cloexec_flag(tcp->pfd_stat) < 0) {
1056 sprintf(proc, "/proc/%d/as", tcp->pid);
1057 if ((tcp->pfd_as = open(proc, O_RDONLY|O_EXCL)) < 0) {
1058 perror("strace: open(\"/proc/...\", ...)");
1061 if (set_cloexec_flag(tcp->pfd_as) < 0) {
1065 /* Open the process pseudo-file in /proc. */
1067 sprintf(proc, "/proc/%d", tcp->pid);
1068 if ((tcp->pfd = open(proc, O_RDWR|O_EXCL)) < 0) {
1070 sprintf(proc, "/proc/%d/mem", tcp->pid);
1071 if ((tcp->pfd = open(proc, O_RDWR)) < 0) {
1072 #endif /* FREEBSD */
1073 perror("strace: open(\"/proc/...\", ...)");
1076 if (set_cloexec_flag(tcp->pfd) < 0) {
1081 sprintf(proc, "/proc/%d/regs", tcp->pid);
1082 if ((tcp->pfd_reg = open(proc, O_RDONLY)) < 0) {
1083 perror("strace: open(\"/proc/.../regs\", ...)");
1087 sprintf(proc, "/proc/%d/status", tcp->pid);
1088 if ((tcp->pfd_status = open(proc, O_RDONLY)) < 0) {
1089 perror("strace: open(\"/proc/.../status\", ...)");
1093 tcp->pfd_status = -1;
1094 #endif /* FREEBSD */
1098 * Wait for the child to pause. Because of a race
1099 * condition we have to poll for the event.
1102 if (IOCTL_STATUS (tcp) < 0) {
1103 perror("strace: PIOCSTATUS");
1106 if (tcp->status.PR_FLAGS & PR_ASLEEP)
1111 /* Stop the process so that we own the stop. */
1112 if (IOCTL(tcp->pfd, PIOCSTOP, (char *)NULL) < 0) {
1113 perror("strace: PIOCSTOP");
1118 /* Set Run-on-Last-Close. */
1120 if (IOCTL(tcp->pfd, PIOCSET, &arg) < 0) {
1121 perror("PIOCSET PR_RLC");
1124 /* Set or Reset Inherit-on-Fork. */
1126 if (IOCTL(tcp->pfd, followfork ? PIOCSET : PIOCRESET, &arg) < 0) {
1127 perror("PIOC{SET,RESET} PR_FORK");
1130 #else /* !PIOCSET */
1132 if (ioctl(tcp->pfd, PIOCSRLC) < 0) {
1136 if (ioctl(tcp->pfd, followfork ? PIOCSFORK : PIOCRFORK) < 0) {
1137 perror("PIOC{S,R}FORK");
1141 /* just unset the PF_LINGER flag for the Run-on-Last-Close. */
1142 if (ioctl(tcp->pfd, PIOCGFL, &arg) < 0) {
1147 if (ioctl(tcp->pfd, PIOCSFL, arg) < 0) {
1151 #endif /* FREEBSD */
1152 #endif /* !PIOCSET */
1154 /* Enable all syscall entries we care about. */
1155 premptyset(&syscalls);
1156 for (i = 1; i < MAX_QUALS; ++i) {
1157 if (i > (sizeof syscalls) * CHAR_BIT) break;
1158 if (qual_flags [i] & QUAL_TRACE) praddset (&syscalls, i);
1160 praddset (&syscalls, SYS_execve);
1162 praddset (&syscalls, SYS_fork);
1164 praddset (&syscalls, SYS_forkall);
1167 praddset (&syscalls, SYS_fork1);
1170 praddset (&syscalls, SYS_rfork1);
1173 praddset (&syscalls, SYS_rforkall);
1176 if (IOCTL(tcp->pfd, PIOCSENTRY, &syscalls) < 0) {
1177 perror("PIOCSENTRY");
1180 /* Enable the syscall exits. */
1181 if (IOCTL(tcp->pfd, PIOCSEXIT, &syscalls) < 0) {
1185 /* Enable signals we care about. */
1186 premptyset(&signals);
1187 for (i = 1; i < MAX_QUALS; ++i) {
1188 if (i > (sizeof signals) * CHAR_BIT) break;
1189 if (qual_flags [i] & QUAL_SIGNAL) praddset (&signals, i);
1191 if (IOCTL(tcp->pfd, PIOCSTRACE, &signals) < 0) {
1192 perror("PIOCSTRACE");
1195 /* Enable faults we care about */
1196 premptyset(&faults);
1197 for (i = 1; i < MAX_QUALS; ++i) {
1198 if (i > (sizeof faults) * CHAR_BIT) break;
1199 if (qual_flags [i] & QUAL_FAULT) praddset (&faults, i);
1201 if (IOCTL(tcp->pfd, PIOCSFAULT, &faults) < 0) {
1202 perror("PIOCSFAULT");
1206 /* set events flags. */
1207 arg = S_SIG | S_SCE | S_SCX ;
1208 if(ioctl(tcp->pfd, PIOCBIS, arg) < 0) {
1212 #endif /* FREEBSD */
1216 * The SGI PRSABORT doesn't work for pause() so
1217 * we send it a caught signal to wake it up.
1219 kill(tcp->pid, SIGINT);
1222 /* The child is in a pause(), abort it. */
1224 if (IOCTL (tcp->pfd, PIOCRUN, &arg) < 0) {
1231 /* wake up the child if it received the SIGSTOP */
1232 kill(tcp->pid, SIGCONT);
1235 /* Wait for the child to do something. */
1236 if (IOCTL_WSTOP (tcp) < 0) {
1237 perror("PIOCWSTOP");
1240 if (tcp->status.PR_WHY == PR_SYSENTRY) {
1241 tcp->flags &= ~TCB_INSYSCALL;
1243 if (known_scno(tcp) == SYS_execve)
1246 /* Set it running: maybe execve will be next. */
1249 if (IOCTL(tcp->pfd, PIOCRUN, &arg) < 0) {
1251 if (IOCTL(tcp->pfd, PIOCRUN, 0) < 0) {
1252 #endif /* FREEBSD */
1257 /* handle the case where we "opened" the child before
1258 it did the kill -STOP */
1259 if (tcp->status.PR_WHY == PR_SIGNALLED &&
1260 tcp->status.PR_WHAT == SIGSTOP)
1261 kill(tcp->pid, SIGCONT);
1268 if (attaching < 2) {
1269 /* We are attaching to an already running process.
1270 * Try to figure out the state of the process in syscalls,
1271 * to handle the first event well.
1272 * This is done by having a look at the "wchan" property of the
1273 * process, which tells where it is stopped (if it is). */
1275 char wchan[20]; /* should be enough */
1277 sprintf(proc, "/proc/%d/status", tcp->pid);
1278 status = fopen(proc, "r");
1280 (fscanf(status, "%*s %*d %*d %*d %*d %*d,%*d %*s %*d,%*d"
1281 "%*d,%*d %*d,%*d %19s", wchan) == 1) &&
1282 strcmp(wchan, "nochan") && strcmp(wchan, "spread") &&
1283 strcmp(wchan, "stopevent")) {
1284 /* The process is asleep in the middle of a syscall.
1285 Fake the syscall entry event */
1286 tcp->flags &= ~(TCB_INSYSCALL|TCB_STARTUP);
1287 tcp->status.PR_WHY = PR_SYSENTRY;
1292 } /* otherwise it's a fork being followed */
1294 #endif /* FREEBSD */
1295 #ifndef HAVE_POLLABLE_PROCFS
1296 if (proc_poll_pipe[0] != -1)
1297 proc_poller(tcp->pfd);
1298 else if (nprocs > 1) {
1300 proc_poller(last_pfd);
1301 proc_poller(tcp->pfd);
1303 last_pfd = tcp->pfd;
1304 #endif /* !HAVE_POLLABLE_PROCFS */
1308 #endif /* USE_PROCFS */
1317 for (i = 0; i < tcbtabsize; i++) {
1319 if (pid && tcp->pid != pid)
1321 if (tcp->flags & TCB_INUSE)
1335 for (i = 0; i < tcbtabsize; i++) {
1336 struct tcb *tcp = tcbtab[i];
1337 if (tcp->pfd != pfd)
1339 if (tcp->flags & TCB_INUSE)
1345 #endif /* USE_PROCFS */
1353 #ifdef TCB_CLONE_THREAD
1354 if (tcp->nclone_threads > 0) {
1355 /* There are other threads left in this process, but this
1356 is the one whose PID represents the whole process.
1357 We need to keep this record around as a zombie until
1358 all the threads die. */
1359 tcp->flags |= TCB_EXITING;
1366 if (tcp->parent != NULL) {
1367 tcp->parent->nchildren--;
1368 #ifdef TCB_CLONE_THREAD
1369 if (tcp->flags & TCB_CLONE_DETACHED)
1370 tcp->parent->nclone_detached--;
1371 if (tcp->flags & TCB_CLONE_THREAD)
1372 tcp->parent->nclone_threads--;
1374 #ifdef TCB_CLONE_DETACHED
1375 if (!(tcp->flags & TCB_CLONE_DETACHED))
1377 tcp->parent->nzombies++;
1379 /* Update `tcp->parent->parent->nchildren' and the other fields
1380 like NCLONE_DETACHED, only for zombie group leader that has
1381 already reported and been short-circuited at the top of this
1382 function. The same condition as at the top of DETACH. */
1383 if ((tcp->flags & TCB_CLONE_THREAD) &&
1384 tcp->parent->nclone_threads == 0 &&
1385 (tcp->parent->flags & TCB_EXITING))
1386 droptcb(tcp->parent);
1392 if (tcp->pfd != -1) {
1396 if (tcp->pfd_reg != -1) {
1397 close(tcp->pfd_reg);
1400 if (tcp->pfd_status != -1) {
1401 close(tcp->pfd_status);
1402 tcp->pfd_status = -1;
1404 #endif /* !FREEBSD */
1406 rebuild_pollv(); /* Note, flags needs to be cleared by now. */
1410 if (outfname && followfork > 1 && tcp->outf)
1425 if (!(tcp->flags & TCB_SUSPENDED)) {
1426 fprintf(stderr, "PANIC: pid %u not suspended\n", tcp->pid);
1429 tcp->flags &= ~TCB_SUSPENDED;
1430 #ifdef TCB_CLONE_THREAD
1431 if (tcp->flags & TCB_CLONE_THREAD)
1432 tcp->parent->nclone_waiting--;
1435 if (ptrace_restart(PTRACE_SYSCALL, tcp, 0) < 0)
1439 fprintf(stderr, "Process %u resumed\n", tcp->pid);
1444 resume_from_tcp (struct tcb *tcp)
1449 /* XXX This won't always be quite right (but it never was).
1450 A waiter with argument 0 or < -1 is waiting for any pid in
1451 a particular pgrp, which this child might or might not be
1452 in. The waiter will only wake up if it's argument is -1
1453 or if it's waiting for tcp->pid's pgrp. It makes a
1454 difference to wake up a waiter when there might be more
1455 traced children, because it could get a false ECHILD
1456 error. OTOH, if this was the last child in the pgrp, then
1457 it ought to wake up and get ECHILD. We would have to
1458 search the system for all pid's in the pgrp to be sure.
1460 && (t->waitpid == -1 ||
1461 (t->waitpid == 0 && getpgid (tcp->pid) == getpgid (t->pid))
1462 || (t->waitpid < 0 && t->waitpid == -getpid (t->pid)))
1466 (tcp->parent->flags & TCB_SUSPENDED) &&
1467 (tcp->parent->waitpid <= 0 || tcp->parent->waitpid == tcp->pid)) {
1468 error = resume(tcp->parent);
1471 #ifdef TCB_CLONE_THREAD
1472 if (tcp->parent && tcp->parent->nclone_waiting > 0) {
1473 /* Some other threads of our parent are waiting too. */
1476 /* Resume all the threads that were waiting for this PID. */
1477 for (i = 0; i < tcbtabsize; i++) {
1478 struct tcb *t = tcbtab[i];
1479 if (t->parent == tcp->parent && t != tcp
1480 && ((t->flags & (TCB_CLONE_THREAD|TCB_SUSPENDED))
1481 == (TCB_CLONE_THREAD|TCB_SUSPENDED))
1482 && t->waitpid == tcp->pid) {
1483 error |= resume (t);
1488 /* Noone was waiting for this PID in particular,
1489 so now we might need to resume some wildcarders. */
1490 for (i = 0; i < tcbtabsize; i++) {
1491 struct tcb *t = tcbtab[i];
1492 if (t->parent == tcp->parent && t != tcp
1494 & (TCB_CLONE_THREAD|TCB_SUSPENDED))
1495 == (TCB_CLONE_THREAD|TCB_SUSPENDED))
1498 error |= resume (t);
1508 #endif /* !USE_PROCFS */
1510 /* detach traced process; continue with sig
1511 Never call DETACH twice on the same process as both unattached and
1512 attached-unstopped processes give the same ESRCH. For unattached process we
1513 would SIGSTOP it and wait for its SIGSTOP notification forever. */
1522 int status, catch_sigstop;
1523 struct tcb *zombie = NULL;
1525 /* If the group leader is lingering only because of this other
1526 thread now dying, then detach the leader as well. */
1527 if ((tcp->flags & TCB_CLONE_THREAD) &&
1528 tcp->parent->nclone_threads == 1 &&
1529 (tcp->parent->flags & TCB_EXITING))
1530 zombie = tcp->parent;
1533 if (tcp->flags & TCB_BPTSET)
1538 * Linux wrongly insists the child be stopped
1539 * before detaching. Arghh. We go through hoops
1540 * to make a clean break of things.
1543 #undef PTRACE_DETACH
1544 #define PTRACE_DETACH PTRACE_SUNDETACH
1547 * On TCB_STARTUP we did PTRACE_ATTACH but still did not get the
1548 * expected SIGSTOP. We must catch exactly one as otherwise the
1549 * detached process would be left stopped (process state T).
1551 catch_sigstop = (tcp->flags & TCB_STARTUP);
1552 if ((error = ptrace(PTRACE_DETACH, tcp->pid, (char *) 1, sig)) == 0) {
1553 /* On a clear day, you can see forever. */
1555 else if (errno != ESRCH) {
1556 /* Shouldn't happen. */
1557 perror("detach: ptrace(PTRACE_DETACH, ...)");
1559 else if (my_tgkill((tcp->flags & TCB_CLONE_THREAD ? tcp->parent->pid
1563 perror("detach: checking sanity");
1565 else if (!catch_sigstop && my_tgkill((tcp->flags & TCB_CLONE_THREAD
1566 ? tcp->parent->pid : tcp->pid),
1567 tcp->pid, SIGSTOP) < 0) {
1569 perror("detach: stopping child");
1573 if (catch_sigstop) {
1576 if (wait4(tcp->pid, &status, __WALL, NULL) < 0) {
1577 if (errno == ECHILD) /* Already gone. */
1579 if (errno != EINVAL) {
1580 perror("detach: waiting");
1584 /* No __WALL here. */
1585 if (waitpid(tcp->pid, &status, 0) < 0) {
1586 if (errno != ECHILD) {
1587 perror("detach: waiting");
1591 /* If no processes, try clones. */
1592 if (wait4(tcp->pid, &status, __WCLONE,
1594 if (errno != ECHILD)
1595 perror("detach: waiting");
1598 #endif /* __WCLONE */
1603 if (!WIFSTOPPED(status)) {
1604 /* Au revoir, mon ami. */
1607 if (WSTOPSIG(status) == SIGSTOP) {
1608 ptrace_restart(PTRACE_DETACH, tcp, sig);
1611 error = ptrace_restart(PTRACE_CONT, tcp,
1612 WSTOPSIG(status) == SIGTRAP ? 0
1613 : WSTOPSIG(status));
1621 /* PTRACE_DETACH won't respect `sig' argument, so we post it here. */
1622 if (sig && kill(tcp->pid, sig) < 0)
1623 perror("detach: kill");
1625 error = ptrace_restart(PTRACE_DETACH, tcp, sig);
1629 error |= resume_from_tcp (tcp);
1633 fprintf(stderr, "Process %u detached\n", tcp->pid);
1638 if (zombie != NULL) {
1639 /* TCP no longer exists therefore you must not detach () it. */
1656 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
1667 #endif /* USE_PROCFS */
1675 for (i = 0; i < tcbtabsize; i++) {
1677 if (!(tcp->flags & TCB_INUSE))
1681 "cleanup: looking at pid %u\n", tcp->pid);
1683 (!outfname || followfork < 2 || tcp_last == tcp)) {
1684 tprintf(" <unfinished ...>");
1687 if (tcp->flags & TCB_ATTACHED)
1690 kill(tcp->pid, SIGCONT);
1691 kill(tcp->pid, SIGTERM);
1705 #ifndef HAVE_STRERROR
1707 #if !HAVE_DECL_SYS_ERRLIST
1708 extern int sys_nerr;
1709 extern char *sys_errlist[];
1710 #endif /* HAVE_DECL_SYS_ERRLIST */
1716 static char buf[64];
1718 if (errno < 1 || errno >= sys_nerr) {
1719 sprintf(buf, "Unknown error %d", errno);
1722 return sys_errlist[errno];
1725 #endif /* HAVE_STERRROR */
1727 #ifndef HAVE_STRSIGNAL
1729 #if defined HAVE_SYS_SIGLIST && !defined HAVE_DECL_SYS_SIGLIST
1730 extern char *sys_siglist[];
1732 #if defined HAVE_SYS__SIGLIST && !defined HAVE_DECL__SYS_SIGLIST
1733 extern char *_sys_siglist[];
1740 static char buf[64];
1742 if (sig < 1 || sig >= NSIG) {
1743 sprintf(buf, "Unknown signal %d", sig);
1746 #ifdef HAVE__SYS_SIGLIST
1747 return _sys_siglist[sig];
1749 return sys_siglist[sig];
1753 #endif /* HAVE_STRSIGNAL */
1764 pollv = (struct pollfd *) malloc(nprocs * sizeof pollv[0]);
1765 if (pollv == NULL) {
1766 fprintf(stderr, "%s: out of memory\n", progname);
1770 for (i = j = 0; i < tcbtabsize; i++) {
1771 struct tcb *tcp = tcbtab[i];
1772 if (!(tcp->flags & TCB_INUSE))
1774 pollv[j].fd = tcp->pfd;
1775 pollv[j].events = POLLWANT;
1779 fprintf(stderr, "strace: proc miscount\n");
1784 #ifndef HAVE_POLLABLE_PROCFS
1791 if (pipe(proc_poll_pipe) < 0) {
1795 for (i = 0; i < 2; i++) {
1796 if (set_cloexec_flag(proc_poll_pipe[i]) < 0) {
1803 proc_poll(pollv, nfds, timeout)
1804 struct pollfd *pollv;
1810 struct proc_pollfd pollinfo;
1812 if ((n = read(proc_poll_pipe[0], &pollinfo, sizeof(pollinfo))) < 0)
1814 if (n != sizeof(struct proc_pollfd)) {
1815 fprintf(stderr, "panic: short read: %d\n", n);
1818 for (i = 0; i < nprocs; i++) {
1819 if (pollv[i].fd == pollinfo.fd)
1820 pollv[i].revents = pollinfo.revents;
1822 pollv[i].revents = 0;
1824 poller_pid = pollinfo.pid;
1838 struct proc_pollfd pollinfo;
1839 struct sigaction sa;
1840 sigset_t blocked_set, empty_set;
1845 struct procfs_status pfs;
1846 #endif /* FREEBSD */
1858 sa.sa_handler = interactive ? SIG_DFL : SIG_IGN;
1860 sigemptyset(&sa.sa_mask);
1861 sigaction(SIGHUP, &sa, NULL);
1862 sigaction(SIGINT, &sa, NULL);
1863 sigaction(SIGQUIT, &sa, NULL);
1864 sigaction(SIGPIPE, &sa, NULL);
1865 sigaction(SIGTERM, &sa, NULL);
1866 sa.sa_handler = wakeup_handler;
1867 sigaction(SIGUSR1, &sa, NULL);
1868 sigemptyset(&blocked_set);
1869 sigaddset(&blocked_set, SIGUSR1);
1870 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
1871 sigemptyset(&empty_set);
1873 if (getrlimit(RLIMIT_NOFILE, &rl) < 0) {
1874 perror("getrlimit(RLIMIT_NOFILE, ...)");
1878 for (i = 0; i < n; i++) {
1879 if (i != pfd && i != proc_poll_pipe[1])
1884 pollinfo.pid = getpid();
1887 if (ioctl(pfd, PIOCWSTOP, NULL) < 0)
1889 if (ioctl(pfd, PIOCWSTOP, &pfs) < 0)
1896 pollinfo.revents = POLLERR;
1899 pollinfo.revents = POLLHUP;
1902 perror("proc_poller: PIOCWSTOP");
1904 write(proc_poll_pipe[1], &pollinfo, sizeof(pollinfo));
1907 pollinfo.revents = POLLWANT;
1908 write(proc_poll_pipe[1], &pollinfo, sizeof(pollinfo));
1909 sigsuspend(&empty_set);
1913 #endif /* !HAVE_POLLABLE_PROCFS */
1923 if (followfork < 2 &&
1924 last < nprocs && (pollv[last].revents & POLLWANT)) {
1926 * The previous process is ready to run again. We'll
1927 * let it do so if it is currently in a syscall. This
1928 * heuristic improves the readability of the trace.
1930 tcp = pfd2tcb(pollv[last].fd);
1931 if (tcp && (tcp->flags & TCB_INSYSCALL))
1932 return pollv[last].fd;
1935 for (i = 0; i < nprocs; i++) {
1936 /* Let competing children run round robin. */
1937 j = (i + last + 1) % nprocs;
1938 if (pollv[j].revents & (POLLHUP | POLLERR)) {
1939 tcp = pfd2tcb(pollv[j].fd);
1941 fprintf(stderr, "strace: lost proc\n");
1947 if (pollv[j].revents & POLLWANT) {
1952 fprintf(stderr, "strace: nothing ready\n");
1960 struct tcb *in_syscall = NULL;
1965 int ioctl_result = 0, ioctl_errno = 0;
1970 sigprocmask(SIG_SETMASK, &empty_set, NULL);
1977 #ifndef HAVE_POLLABLE_PROCFS
1978 if (proc_poll_pipe[0] == -1) {
1987 #ifndef HAVE_POLLABLE_PROCFS
1989 /* fall through ... */
1990 #endif /* !HAVE_POLLABLE_PROCFS */
1992 #ifdef HAVE_POLLABLE_PROCFS
1994 /* On some systems (e.g. UnixWare) we get too much ugly
1995 "unfinished..." stuff when multiple proceses are in
1996 syscalls. Here's a nasty hack */
2003 pv.events = POLLWANT;
2004 if ((what = poll (&pv, 1, 1)) < 0) {
2009 else if (what == 1 && pv.revents & POLLWANT) {
2015 if (poll(pollv, nprocs, INFTIM) < 0) {
2020 #else /* !HAVE_POLLABLE_PROCFS */
2021 if (proc_poll(pollv, nprocs, INFTIM) < 0) {
2026 #endif /* !HAVE_POLLABLE_PROCFS */
2033 /* Look up `pfd' in our table. */
2034 if ((tcp = pfd2tcb(pfd)) == NULL) {
2035 fprintf(stderr, "unknown pfd: %u\n", pfd);
2041 /* Get the status of the process. */
2044 ioctl_result = IOCTL_WSTOP (tcp);
2046 /* Thanks to some scheduling mystery, the first poller
2047 sometimes waits for the already processed end of fork
2048 event. Doing a non blocking poll here solves the problem. */
2049 if (proc_poll_pipe[0] != -1)
2050 ioctl_result = IOCTL_STATUS (tcp);
2052 ioctl_result = IOCTL_WSTOP (tcp);
2053 #endif /* FREEBSD */
2054 ioctl_errno = errno;
2055 #ifndef HAVE_POLLABLE_PROCFS
2056 if (proc_poll_pipe[0] != -1) {
2057 if (ioctl_result < 0)
2058 kill(poller_pid, SIGKILL);
2060 kill(poller_pid, SIGUSR1);
2062 #endif /* !HAVE_POLLABLE_PROCFS */
2068 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
2070 if (ioctl_result < 0) {
2071 /* Find out what happened if it failed. */
2072 switch (ioctl_errno) {
2083 perror("PIOCWSTOP");
2089 if ((tcp->flags & TCB_STARTUP) && (tcp->status.PR_WHY == PR_SYSEXIT)) {
2090 /* discard first event for a syscall we never entered */
2091 IOCTL (tcp->pfd, PIOCRUN, 0);
2096 /* clear the just started flag */
2097 tcp->flags &= ~TCB_STARTUP;
2099 /* set current output file */
2103 struct timeval stime;
2108 if ((len = pread(tcp->pfd_status, buf, sizeof(buf) - 1, 0)) > 0) {
2111 "%*s %*d %*d %*d %*d %*d,%*d %*s %*d,%*d %*d,%*d %ld,%ld",
2112 &stime.tv_sec, &stime.tv_usec);
2114 stime.tv_sec = stime.tv_usec = 0;
2115 #else /* !FREEBSD */
2116 stime.tv_sec = tcp->status.pr_stime.tv_sec;
2117 stime.tv_usec = tcp->status.pr_stime.tv_nsec/1000;
2118 #endif /* !FREEBSD */
2119 tv_sub(&tcp->dtime, &stime, &tcp->stime);
2122 what = tcp->status.PR_WHAT;
2123 switch (tcp->status.PR_WHY) {
2126 if (tcp->status.PR_FLAGS & PR_ASLEEP) {
2127 tcp->status.PR_WHY = PR_SYSENTRY;
2128 if (trace_syscall(tcp) < 0) {
2129 fprintf(stderr, "syscall trouble\n");
2134 #endif /* !FREEBSD */
2140 if (trace_syscall(tcp) < 0) {
2141 fprintf(stderr, "syscall trouble\n");
2146 if (!cflag && (qual_flags[what] & QUAL_SIGNAL)) {
2148 tprintf("--- %s (%s) ---",
2149 signame(what), strsignal(what));
2152 if (tcp->status.PR_INFO.si_signo == what) {
2154 tprintf(" siginfo=");
2155 printsiginfo(&tcp->status.PR_INFO, 1);
2162 if (!cflag && (qual_flags[what] & QUAL_FAULT)) {
2164 tprintf("=== FAULT %d ===", what);
2169 case 0: /* handle case we polled for nothing */
2173 fprintf(stderr, "odd stop %d\n", tcp->status.PR_WHY);
2179 if (IOCTL (tcp->pfd, PIOCRUN, &arg) < 0) {
2181 if (IOCTL (tcp->pfd, PIOCRUN, 0) < 0) {
2190 #else /* !USE_PROCFS */
2192 #ifdef TCB_GROUP_EXITING
2193 /* Handle an exit detach or death signal that is taking all the
2194 related clone threads with it. This is called in three circumstances:
2195 SIG == -1 TCP has already died (TCB_ATTACHED is clear, strace is parent).
2196 SIG == 0 Continuing TCP will perform an exit_group syscall.
2197 SIG == other Continuing TCP with SIG will kill the process.
2200 handle_group_exit(struct tcb *tcp, int sig)
2202 /* We need to locate our records of all the clone threads
2203 related to TCP, either its children or siblings. */
2204 struct tcb *leader = NULL;
2206 if (tcp->flags & TCB_CLONE_THREAD)
2207 leader = tcp->parent;
2208 else if (tcp->nclone_detached > 0)
2212 if (leader != NULL && leader != tcp
2213 && !(leader->flags & TCB_GROUP_EXITING)
2214 && !(tcp->flags & TCB_STARTUP)
2217 "PANIC: handle_group_exit: %d leader %d\n",
2218 tcp->pid, leader ? leader->pid : -1);
2220 /* TCP no longer exists therefore you must not detach() it. */
2222 resume_from_tcp(tcp);
2224 droptcb(tcp); /* Already died. */
2227 /* Mark that we are taking the process down. */
2228 tcp->flags |= TCB_EXITING | TCB_GROUP_EXITING;
2229 if (tcp->flags & TCB_ATTACHED) {
2231 if (leader != NULL && leader != tcp)
2232 leader->flags |= TCB_GROUP_EXITING;
2234 if (ptrace_restart(PTRACE_CONT, tcp, sig) < 0) {
2238 if (leader != NULL) {
2239 leader->flags |= TCB_GROUP_EXITING;
2243 /* The leader will report to us as parent now,
2244 and then we'll get to the SIG==-1 case. */
2263 static int wait4_options = __WALL;
2267 while (nprocs != 0) {
2271 sigprocmask(SIG_SETMASK, &empty_set, NULL);
2274 pid = wait4(-1, &status, wait4_options, cflag ? &ru : NULL);
2275 if (pid < 0 && (wait4_options & __WALL) && errno == EINVAL) {
2276 /* this kernel does not support __WALL */
2277 wait4_options &= ~__WALL;
2279 pid = wait4(-1, &status, wait4_options,
2280 cflag ? &ru : NULL);
2282 if (pid < 0 && !(wait4_options & __WALL) && errno == ECHILD) {
2283 /* most likely a "cloned" process */
2284 pid = wait4(-1, &status, __WCLONE,
2285 cflag ? &ru : NULL);
2287 fprintf(stderr, "strace: clone wait4 "
2288 "failed: %s\n", strerror(errno));
2292 pid = wait4(-1, &status, 0, cflag ? &ru : NULL);
2296 pid = wait(&status);
2300 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
2303 switch (wait_errno) {
2308 * We would like to verify this case
2309 * but sometimes a race in Solbourne's
2310 * version of SunOS sometimes reports
2311 * ECHILD before sending us SIGCHILD.
2316 fprintf(stderr, "strace: proc miscount\n");
2322 perror("strace: wait");
2326 if (pid == popen_pid) {
2327 if (WIFEXITED(status) || WIFSIGNALED(status))
2332 fprintf(stderr, " [wait(%#x) = %u]\n", status, pid);
2334 /* Look up `pid' in our table. */
2335 if ((tcp = pid2tcb(pid)) == NULL) {
2338 /* This is needed to go with the CLONE_PTRACE
2339 changes in process.c/util.c: we might see
2340 the child's initial trap before we see the
2341 parent return from the clone syscall.
2342 Leave the child suspended until the parent
2343 returns from its system call. Only then
2344 will we have the association of parent and
2345 child so that we know how to do clearbpt
2347 tcp = alloctcb(pid);
2348 tcp->flags |= TCB_ATTACHED | TCB_SUSPENDED;
2351 Process %d attached (waiting for parent)\n",
2355 /* This can happen if a clone call used
2356 CLONE_PTRACE itself. */
2359 fprintf(stderr, "unknown pid: %u\n", pid);
2360 if (WIFSTOPPED(status))
2361 ptrace(PTRACE_CONT, pid, (char *) 1, 0);
2365 /* set current output file */
2369 tv_sub(&tcp->dtime, &ru.ru_stime, &tcp->stime);
2370 tcp->stime = ru.ru_stime;
2374 if (tcp->flags & TCB_SUSPENDED) {
2376 * Apparently, doing any ptrace() call on a stopped
2377 * process, provokes the kernel to report the process
2378 * status again on a subsequent wait(), even if the
2379 * process has not been actually restarted.
2380 * Since we have inspected the arguments of suspended
2381 * processes we end up here testing for this case.
2385 if (WIFSIGNALED(status)) {
2386 if (pid == strace_child)
2387 exit_code = 0x100 | WTERMSIG(status);
2389 && (qual_flags[WTERMSIG(status)] & QUAL_SIGNAL)) {
2391 tprintf("+++ killed by %s %s+++",
2392 signame(WTERMSIG(status)),
2394 WCOREDUMP(status) ? "(core dumped) " :
2399 #ifdef TCB_GROUP_EXITING
2400 handle_group_exit(tcp, -1);
2406 if (WIFEXITED(status)) {
2407 if (pid == strace_child)
2408 exit_code = WEXITSTATUS(status);
2410 fprintf(stderr, "pid %u exited with %d\n", pid, WEXITSTATUS(status));
2411 if ((tcp->flags & (TCB_ATTACHED|TCB_STARTUP)) == TCB_ATTACHED
2412 #ifdef TCB_GROUP_EXITING
2413 && !(tcp->parent && (tcp->parent->flags & TCB_GROUP_EXITING))
2414 && !(tcp->flags & TCB_GROUP_EXITING)
2418 "PANIC: attached pid %u exited with %d\n",
2419 pid, WEXITSTATUS(status));
2421 if (tcp == tcp_last) {
2422 if ((tcp->flags & (TCB_INSYSCALL|TCB_REPRINT)) == TCB_INSYSCALL)
2423 tprintf(" <unfinished ... exit status %d>\n",
2424 WEXITSTATUS(status));
2427 #ifdef TCB_GROUP_EXITING
2428 handle_group_exit(tcp, -1);
2434 if (!WIFSTOPPED(status)) {
2435 fprintf(stderr, "PANIC: pid %u not stopped\n", pid);
2440 fprintf(stderr, "pid %u stopped, [%s]\n",
2441 pid, signame(WSTOPSIG(status)));
2444 * Interestingly, the process may stop
2445 * with STOPSIG equal to some other signal
2446 * than SIGSTOP if we happend to attach
2447 * just before the process takes a signal.
2449 if ((tcp->flags & TCB_STARTUP) && WSTOPSIG(status) == SIGSTOP) {
2451 * This flag is there to keep us in sync.
2452 * Next time this process stops it should
2453 * really be entering a system call.
2455 tcp->flags &= ~TCB_STARTUP;
2456 if (tcp->flags & TCB_BPTSET) {
2458 * One example is a breakpoint inherited from
2459 * parent through fork ().
2461 if (clearbpt(tcp) < 0) /* Pretty fatal */ {
2470 if (WSTOPSIG(status) != SIGTRAP) {
2471 if (WSTOPSIG(status) == SIGSTOP &&
2472 (tcp->flags & TCB_SIGTRAPPED)) {
2474 * Trapped attempt to block SIGTRAP
2475 * Hope we are back in control now.
2477 tcp->flags &= ~(TCB_INSYSCALL | TCB_SIGTRAPPED);
2478 if (ptrace_restart(PTRACE_SYSCALL, tcp, 0) < 0) {
2485 && (qual_flags[WSTOPSIG(status)] & QUAL_SIGNAL)) {
2486 unsigned long addr = 0;
2488 #if defined(PT_CR_IPSR) && defined(PT_CR_IIP) && defined(PT_GETSIGINFO)
2493 upeek(tcp, PT_CR_IPSR, &psr);
2494 upeek(tcp, PT_CR_IIP, &pc);
2496 pc += (psr >> PSR_RI) & 0x3;
2497 ptrace(PT_GETSIGINFO, pid, 0, (long) &si);
2498 addr = (unsigned long) si.si_addr;
2499 #elif defined PTRACE_GETSIGINFO
2500 if (WSTOPSIG(status) == SIGSEGV ||
2501 WSTOPSIG(status) == SIGBUS) {
2503 if (ptrace(PTRACE_GETSIGINFO, pid,
2505 addr = (unsigned long)
2510 tprintf("--- %s (%s) @ %lx (%lx) ---",
2511 signame(WSTOPSIG(status)),
2512 strsignal(WSTOPSIG(status)), pc, addr);
2515 if (((tcp->flags & TCB_ATTACHED) ||
2516 tcp->nclone_threads > 0) &&
2517 !sigishandled(tcp, WSTOPSIG(status))) {
2518 #ifdef TCB_GROUP_EXITING
2519 handle_group_exit(tcp, WSTOPSIG(status));
2521 detach(tcp, WSTOPSIG(status));
2525 if (ptrace_restart(PTRACE_SYSCALL, tcp, WSTOPSIG(status)) < 0) {
2529 tcp->flags &= ~TCB_SUSPENDED;
2532 /* we handled the STATUS, we are permitted to interrupt now. */
2535 if (trace_syscall(tcp) < 0 && !tcp->ptrace_errno) {
2536 /* ptrace() failed in trace_syscall() with ESRCH.
2537 * Likely a result of process disappearing mid-flight.
2538 * Observed case: exit_group() terminating
2539 * all processes in thread group. In this case, threads
2540 * "disappear" in an unpredictable moment without any
2541 * notification to strace via wait().
2543 if (tcp->flags & TCB_ATTACHED) {
2545 /* Do we have dangling line "syscall(param, param"?
2546 * Finish the line then. We cannot
2548 tcp_last->flags |= TCB_REPRINT;
2549 tprintf(" <unfinished ...>");
2555 tcp->pid, (char *) 1, SIGTERM);
2560 if (tcp->flags & TCB_EXITING) {
2561 #ifdef TCB_GROUP_EXITING
2562 if (tcp->flags & TCB_GROUP_EXITING) {
2563 if (handle_group_exit(tcp, 0) < 0)
2568 if (tcp->flags & TCB_ATTACHED)
2570 else if (ptrace_restart(PTRACE_CONT, tcp, 0) < 0) {
2576 if (tcp->flags & TCB_SUSPENDED) {
2578 fprintf(stderr, "Process %u suspended\n", pid);
2582 if (ptrace_restart(PTRACE_SYSCALL, tcp, 0) < 0) {
2590 #endif /* !USE_PROCFS */
2596 #define VA_START(a, b) va_start(a, b)
2598 #include <varargs.h>
2599 #define VA_START(a, b) va_start(a)
2604 tprintf(const char *fmt, ...)
2606 tprintf(fmt, va_alist)
2613 VA_START(args, fmt);
2615 int n = vfprintf(outf, fmt, args);
2616 if (n < 0 && outf != stderr)
2617 perror(outfname == NULL
2618 ? "<writing to pipe>" : outfname);
2631 if (tcp_last->ptrace_errno) {
2632 if (tcp_last->flags & TCB_INSYSCALL) {
2633 tprintf(" <unavailable>)");
2636 tprintf("= ? <unavailable>\n");
2637 tcp_last->ptrace_errno = 0;
2638 } else if (!outfname || followfork < 2 || tcp_last == tcp) {
2639 tcp_last->flags |= TCB_REPRINT;
2640 tprintf(" <unfinished ...>\n");
2644 if ((followfork == 1 || pflag_seen > 1) && outfname)
2645 tprintf("%-5d ", tcp->pid);
2646 else if (nprocs > 1 && !outfname)
2647 tprintf("[pid %5u] ", tcp->pid);
2649 char str[sizeof("HH:MM:SS")];
2650 struct timeval tv, dtv;
2651 static struct timeval otv;
2653 gettimeofday(&tv, NULL);
2655 if (otv.tv_sec == 0)
2657 tv_sub(&dtv, &tv, &otv);
2658 tprintf("%6ld.%06ld ",
2659 (long) dtv.tv_sec, (long) dtv.tv_usec);
2662 else if (tflag > 2) {
2663 tprintf("%ld.%06ld ",
2664 (long) tv.tv_sec, (long) tv.tv_usec);
2667 time_t local = tv.tv_sec;
2668 strftime(str, sizeof(str), "%T", localtime(&local));
2670 tprintf("%s.%06ld ", str, (long) tv.tv_usec);
2672 tprintf("%s ", str);
2684 tprintf("%*s", col - curcol, "");
2694 #ifdef HAVE_MP_PROCFS
2697 mp_ioctl(int fd, int cmd, void *arg, int size)
2699 struct iovec iov[2];
2702 iov[0].iov_base = &cmd;
2703 iov[0].iov_len = sizeof cmd;
2706 iov[1].iov_base = arg;
2707 iov[1].iov_len = size;
2710 return writev(fd, iov, n);