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);
215 /* Glue for systems without a MMU that cannot provide fork() */
217 # define strace_vforked 0
219 # define strace_vforked 1
220 # define fork() vfork()
224 set_cloexec_flag(int fd)
228 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
230 fprintf(stderr, "%s: fcntl F_GETFD: %s\n",
231 progname, strerror(errno));
235 newflags = flags | FD_CLOEXEC;
236 if (flags == newflags)
239 if (fcntl(fd, F_SETFD, newflags) < 0)
241 fprintf(stderr, "%s: fcntl F_SETFD: %s\n",
242 progname, strerror(errno));
250 * When strace is setuid executable, we have to swap uids
251 * before and after filesystem and process management operations.
257 int euid = geteuid(), uid = getuid();
259 if (euid != uid && setreuid(euid, uid) < 0)
261 fprintf(stderr, "%s: setreuid: %s\n",
262 progname, strerror(errno));
269 # define fopen_for_output fopen64
271 # define fopen_for_output fopen
275 strace_fopen(const char *path, const char *mode)
280 if ((fp = fopen_for_output(path, mode)) == NULL)
281 fprintf(stderr, "%s: can't fopen '%s': %s\n",
282 progname, path, strerror(errno));
284 if (fp && set_cloexec_flag(fileno(fp)) < 0)
292 static int popen_pid = -1;
295 # define _PATH_BSHELL "/bin/sh"
299 * We cannot use standard popen(3) here because we have to distinguish
300 * popen child process from other processes we trace, and standard popen(3)
301 * does not export its child's pid.
304 strace_popen(const char *command)
311 fprintf(stderr, "%s: pipe: %s\n",
312 progname, strerror(errno));
317 if (set_cloexec_flag(fds[1]) < 0)
325 if ((popen_pid = fork()) == -1)
327 fprintf(stderr, "%s: fork: %s\n",
328 progname, strerror(errno));
340 return fdopen(fds[1], "w");
345 if (fds[0] && (dup2(fds[0], 0) || close(fds[0])))
347 fprintf(stderr, "%s: dup2: %s\n",
348 progname, strerror(errno));
351 execl(_PATH_BSHELL, "sh", "-c", command, NULL);
352 fprintf(stderr, "%s: execl: %s: %s\n",
353 progname, _PATH_BSHELL, strerror(errno));
359 newoutf(struct tcb *tcp)
361 if (outfname && followfork > 1) {
362 char name[520 + sizeof(int) * 3];
365 sprintf(name, "%.512s.%u", outfname, tcp->pid);
366 if ((fp = strace_fopen(name, "w")) == NULL)
380 * Block user interruptions as we would leave the traced
381 * process stopped (process state T) if we would terminate in
382 * between PTRACE_ATTACH and wait4 () on SIGSTOP.
383 * We rely on cleanup () from this point on.
386 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
388 if (daemonized_tracer) {
393 if (pid) { /* parent */
395 * Wait for child to attach to straced process
396 * (our parent). Child SIGKILLs us after it attached.
397 * Parent's wait() is unblocked by our death,
398 * it proceeds to exec the straced program.
401 _exit(0); /* paranoia */
405 for (tcbi = 0; tcbi < tcbtabsize; tcbi++) {
407 if (!(tcp->flags & TCB_INUSE) || !(tcp->flags & TCB_ATTACHED))
410 if (tcp->flags & TCB_CLONE_THREAD)
413 /* Reinitialize the output since it may have changed. */
415 if (newoutf(tcp) < 0)
419 if (proc_open(tcp, 1) < 0) {
420 fprintf(stderr, "trouble opening proc file\n");
424 #else /* !USE_PROCFS */
426 if (followfork && !daemonized_tracer) {
427 char procdir[sizeof("/proc/%d/task") + sizeof(int) * 3];
430 sprintf(procdir, "/proc/%d/task", tcp->pid);
431 dir = opendir(procdir);
433 unsigned int ntid = 0, nerr = 0;
436 while ((de = readdir(dir)) != NULL) {
437 if (de->d_fileno == 0)
439 tid = atoi(de->d_name);
443 if (ptrace(PTRACE_ATTACH, tid, (char *) 1, 0) < 0)
445 else if (tid != tcbtab[tcbi]->pid) {
447 tcp->flags |= TCB_ATTACHED|TCB_CLONE_THREAD|TCB_CLONE_DETACHED|TCB_FOLLOWFORK;
448 tcbtab[tcbi]->nchildren++;
449 tcbtab[tcbi]->nclone_threads++;
450 tcbtab[tcbi]->nclone_detached++;
451 tcp->parent = tcbtab[tcbi];
454 sigprocmask(SIG_SETMASK, &empty_set, NULL);
457 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
463 perror("attach: ptrace(PTRACE_ATTACH, ...)");
468 fprintf(stderr, ntid > 1
469 ? "Process %u attached with %u threads - interrupt to quit\n"
470 : "Process %u attached - interrupt to quit\n",
471 tcbtab[tcbi]->pid, ntid);
474 } /* if (opendir worked) */
477 if (ptrace(PTRACE_ATTACH, tcp->pid, (char *) 1, 0) < 0) {
478 perror("attach: ptrace(PTRACE_ATTACH, ...)");
482 /* INTERRUPTED is going to be checked at the top of TRACE. */
484 if (daemonized_tracer) {
486 * It is our grandparent we trace, not a -p PID.
487 * Don't want to just detach on exit, so...
489 tcp->flags &= ~TCB_ATTACHED;
491 * Make parent go away.
492 * Also makes grandparent's wait() unblock.
494 kill(getppid(), SIGKILL);
497 #endif /* !USE_PROCFS */
500 "Process %u attached - interrupt to quit\n",
505 sigprocmask(SIG_SETMASK, &empty_set, NULL);
509 startup_child (char **argv)
512 const char *filename;
513 char pathname[MAXPATHLEN];
518 if (strchr(filename, '/')) {
519 if (strlen(filename) > sizeof pathname - 1) {
520 errno = ENAMETOOLONG;
521 perror("strace: exec");
524 strcpy(pathname, filename);
526 #ifdef USE_DEBUGGING_EXEC
528 * Debuggers customarily check the current directory
529 * first regardless of the path but doing that gives
530 * security geeks a panic attack.
532 else if (stat(filename, &statbuf) == 0)
533 strcpy(pathname, filename);
534 #endif /* USE_DEBUGGING_EXEC */
539 for (path = getenv("PATH"); path && *path; path += m) {
540 if (strchr(path, ':')) {
541 n = strchr(path, ':') - path;
545 m = n = strlen(path);
547 if (!getcwd(pathname, MAXPATHLEN))
549 len = strlen(pathname);
551 else if (n > sizeof pathname - 1)
554 strncpy(pathname, path, n);
557 if (len && pathname[len - 1] != '/')
558 pathname[len++] = '/';
559 strcpy(pathname + len, filename);
560 if (stat(pathname, &statbuf) == 0 &&
561 /* Accept only regular files
562 with some execute bits set.
563 XXX not perfect, might still fail */
564 S_ISREG(statbuf.st_mode) &&
565 (statbuf.st_mode & 0111))
569 if (stat(pathname, &statbuf) < 0) {
570 fprintf(stderr, "%s: %s: command not found\n",
574 strace_child = pid = fork();
576 perror("strace: fork");
580 if ((pid != 0 && daemonized_tracer) /* parent: to become a traced process */
581 || (pid == 0 && !daemonized_tracer) /* child: to become a traced process */
585 if (outf != stderr) close (fileno (outf));
587 /* Kludge for SGI, see proc_open for details. */
588 sa.sa_handler = foobar;
590 sigemptyset(&sa.sa_mask);
591 sigaction(SIGINT, &sa, NULL);
596 kill(pid, SIGSTOP); /* stop HERE */
598 #else /* !USE_PROCFS */
600 close(fileno (outf));
602 if (!daemonized_tracer) {
603 if (ptrace(PTRACE_TRACEME, 0, (char *) 1, 0) < 0) {
604 perror("strace: ptrace(PTRACE_TRACEME, ...)");
611 if (username != NULL || geteuid() == 0) {
612 uid_t run_euid = run_uid;
613 gid_t run_egid = run_gid;
615 if (statbuf.st_mode & S_ISUID)
616 run_euid = statbuf.st_uid;
617 if (statbuf.st_mode & S_ISGID)
618 run_egid = statbuf.st_gid;
621 * It is important to set groups before we
622 * lose privileges on setuid.
624 if (username != NULL) {
625 if (initgroups(username, run_gid) < 0) {
626 perror("initgroups");
629 if (setregid(run_gid, run_egid) < 0) {
633 if (setreuid(run_uid, run_euid) < 0) {
640 setreuid(run_uid, run_uid);
642 if (!daemonized_tracer) {
644 * Induce an immediate stop so that the parent
645 * will resume us with PTRACE_SYSCALL and display
646 * this execve call normally.
647 * Unless of course we're on a no-MMU system where
648 * we vfork()-ed, so we cannot stop the child.
651 kill(getpid(), SIGSTOP);
653 struct sigaction sv_sigchld;
654 sigaction(SIGCHLD, NULL, &sv_sigchld);
656 * Make sure it is not SIG_IGN, otherwise wait
659 signal(SIGCHLD, SIG_DFL);
661 * Wait for grandchild to attach to us.
662 * It kills child after that, and wait() unblocks.
667 sigaction(SIGCHLD, &sv_sigchld, NULL);
669 #endif /* !USE_PROCFS */
671 execv(pathname, argv);
672 perror("strace: exec");
676 /* We are the tracer. */
677 tcp = alloctcb(daemonized_tracer ? getppid() : pid);
678 if (daemonized_tracer) {
679 /* We want subsequent startup_attach() to attach to it. */
680 tcp->flags |= TCB_ATTACHED;
683 if (proc_open(tcp, 0) < 0) {
684 fprintf(stderr, "trouble opening proc file\n");
688 #endif /* USE_PROCFS */
692 main(int argc, char *argv[])
699 static char buf[BUFSIZ];
701 progname = argv[0] ? argv[0] : "strace";
703 /* Allocate the initial tcbtab. */
704 tcbtabsize = argc; /* Surely enough for all -p args. */
705 if ((tcbtab = calloc(tcbtabsize, sizeof tcbtab[0])) == NULL) {
706 fprintf(stderr, "%s: out of memory\n", progname);
709 if ((tcbtab[0] = calloc(tcbtabsize, sizeof tcbtab[0][0])) == NULL) {
710 fprintf(stderr, "%s: out of memory\n", progname);
713 for (tcp = tcbtab[0]; tcp < &tcbtab[0][tcbtabsize]; ++tcp)
714 tcbtab[tcp - tcbtab[0]] = &tcbtab[0][tcp - tcbtab[0]];
718 set_sortby(DEFAULT_SORTBY);
719 set_personality(DEFAULT_PERSONALITY);
720 qualify("trace=all");
721 qualify("abbrev=all");
722 qualify("verbose=all");
723 qualify("signal=all");
724 while ((c = getopt(argc, argv,
729 "a:e:o:O:p:s:S:u:E:")) != EOF) {
739 /* Experimental, not documented in manpage yet. */
741 daemonized_tracer = 1;
773 qualify("abbrev=none");
776 printf("%s -- version %s\n", PACKAGE_NAME, VERSION);
780 not_failing_only = 1;
783 acolumn = atoi(optarg);
789 outfname = strdup(optarg);
792 set_overhead(atoi(optarg));
795 if ((pid = atoi(optarg)) <= 0) {
796 fprintf(stderr, "%s: Invalid process id: %s\n",
800 if (pid == getpid()) {
801 fprintf(stderr, "%s: I'm sorry, I can't let you do that, Dave.\n", progname);
804 tcp = alloc_tcb(pid, 0);
805 tcp->flags |= TCB_ATTACHED;
809 max_strlen = atoi(optarg);
810 if (max_strlen < 0) {
812 "%s: invalid -s argument: %s\n",
821 username = strdup(optarg);
824 if (putenv(optarg) < 0) {
825 fprintf(stderr, "%s: out of memory\n",
836 if ((optind == argc) == !pflag_seen)
842 if (followfork > 1 && cflag) {
844 "%s: -c and -ff are mutually exclusive options\n",
849 /* See if they want to run as another user. */
850 if (username != NULL) {
853 if (getuid() != 0 || geteuid() != 0) {
855 "%s: you must be root to use the -u option\n",
859 if ((pent = getpwnam(username)) == NULL) {
860 fprintf(stderr, "%s: cannot find user `%s'\n",
864 run_uid = pent->pw_uid;
865 run_gid = pent->pw_gid;
872 /* Check if they want to redirect the output. */
874 /* See if they want to pipe the output. */
875 if (outfname[0] == '|' || outfname[0] == '!') {
877 * We can't do the <outfname>.PID funny business
878 * when using popen, so prohibit it.
880 if (followfork > 1) {
882 %s: piping the output and -ff are mutually exclusive options\n",
887 if ((outf = strace_popen(outfname + 1)) == NULL)
890 else if (followfork <= 1 &&
891 (outf = strace_fopen(outfname, "w")) == NULL)
895 if (!outfname || outfname[0] == '|' || outfname[0] == '!')
896 setvbuf(outf, buf, _IOLBF, BUFSIZ);
897 if (outfname && optind < argc) {
901 /* Valid states here:
902 optind < argc pflag_seen outfname interactive
909 /* STARTUP_CHILD must be called before the signal handlers get
910 installed below as they are inherited into the spawned process.
911 Also we do not need to be protected by them as during interruption
912 in the STARTUP_CHILD mode we kill the spawned process anyway. */
914 startup_child(&argv[optind]);
916 sigemptyset(&empty_set);
917 sigemptyset(&blocked_set);
918 sa.sa_handler = SIG_IGN;
919 sigemptyset(&sa.sa_mask);
921 sigaction(SIGTTOU, &sa, NULL);
922 sigaction(SIGTTIN, &sa, NULL);
924 sigaddset(&blocked_set, SIGHUP);
925 sigaddset(&blocked_set, SIGINT);
926 sigaddset(&blocked_set, SIGQUIT);
927 sigaddset(&blocked_set, SIGPIPE);
928 sigaddset(&blocked_set, SIGTERM);
929 sa.sa_handler = interrupt;
931 /* POSIX signals on sunos4.1 are a little broken. */
932 sa.sa_flags = SA_INTERRUPT;
935 sigaction(SIGHUP, &sa, NULL);
936 sigaction(SIGINT, &sa, NULL);
937 sigaction(SIGQUIT, &sa, NULL);
938 sigaction(SIGPIPE, &sa, NULL);
939 sigaction(SIGTERM, &sa, NULL);
941 sa.sa_handler = reaper;
942 sigaction(SIGCHLD, &sa, NULL);
944 /* Make sure SIGCHLD has the default action so that waitpid
945 definitely works without losing track of children. The user
946 should not have given us a bogus state to inherit, but he might
947 have. Arguably we should detect SIG_IGN here and pass it on
948 to children, but probably noone really needs that. */
949 sa.sa_handler = SIG_DFL;
950 sigaction(SIGCHLD, &sa, NULL);
951 #endif /* USE_PROCFS */
953 if (pflag_seen || daemonized_tracer)
960 if (exit_code > 0xff) {
961 /* Child was killed by a signal, mimic that. */
963 signal(exit_code, SIG_DFL);
965 /* Paranoia - what if this signal is not fatal?
966 Exit with 128 + signo then. */
975 /* Allocate some more TCBs and expand the table.
976 We don't want to relocate the TCBs because our
977 callers have pointers and it would be a pain.
978 So tcbtab is a table of pointers. Since we never
979 free the TCBs, we allocate a single chunk of many. */
980 struct tcb **newtab = (struct tcb **)
981 realloc(tcbtab, 2 * tcbtabsize * sizeof tcbtab[0]);
982 struct tcb *newtcbs = (struct tcb *) calloc(tcbtabsize,
985 if (newtab == NULL || newtcbs == NULL) {
986 fprintf(stderr, "%s: expand_tcbtab: out of memory\n",
991 for (i = tcbtabsize; i < 2 * tcbtabsize; ++i)
992 newtab[i] = &newtcbs[i - tcbtabsize];
998 alloc_tcb(int pid, int command_options_parsed)
1003 if (nprocs == tcbtabsize)
1006 for (i = 0; i < tcbtabsize; i++) {
1008 if ((tcp->flags & TCB_INUSE) == 0) {
1013 #ifdef TCB_CLONE_THREAD
1014 tcp->nclone_threads = tcp->nclone_detached = 0;
1015 tcp->nclone_waiting = 0;
1017 tcp->flags = TCB_INUSE | TCB_STARTUP;
1018 tcp->outf = outf; /* Initialise to current out file */
1019 tcp->stime.tv_sec = 0;
1020 tcp->stime.tv_usec = 0;
1023 if (command_options_parsed)
1028 fprintf(stderr, "%s: bug in alloc_tcb\n", progname);
1035 proc_open(struct tcb *tcp, int attaching)
1045 #ifndef HAVE_POLLABLE_PROCFS
1046 static int last_pfd;
1049 #ifdef HAVE_MP_PROCFS
1050 /* Open the process pseudo-files in /proc. */
1051 sprintf(proc, "/proc/%d/ctl", tcp->pid);
1052 if ((tcp->pfd = open(proc, O_WRONLY|O_EXCL)) < 0) {
1053 perror("strace: open(\"/proc/...\", ...)");
1056 if (set_cloexec_flag(tcp->pfd) < 0) {
1059 sprintf(proc, "/proc/%d/status", tcp->pid);
1060 if ((tcp->pfd_stat = open(proc, O_RDONLY|O_EXCL)) < 0) {
1061 perror("strace: open(\"/proc/...\", ...)");
1064 if (set_cloexec_flag(tcp->pfd_stat) < 0) {
1067 sprintf(proc, "/proc/%d/as", tcp->pid);
1068 if ((tcp->pfd_as = open(proc, O_RDONLY|O_EXCL)) < 0) {
1069 perror("strace: open(\"/proc/...\", ...)");
1072 if (set_cloexec_flag(tcp->pfd_as) < 0) {
1076 /* Open the process pseudo-file in /proc. */
1078 sprintf(proc, "/proc/%d", tcp->pid);
1079 if ((tcp->pfd = open(proc, O_RDWR|O_EXCL)) < 0) {
1081 sprintf(proc, "/proc/%d/mem", tcp->pid);
1082 if ((tcp->pfd = open(proc, O_RDWR)) < 0) {
1083 #endif /* FREEBSD */
1084 perror("strace: open(\"/proc/...\", ...)");
1087 if (set_cloexec_flag(tcp->pfd) < 0) {
1092 sprintf(proc, "/proc/%d/regs", tcp->pid);
1093 if ((tcp->pfd_reg = open(proc, O_RDONLY)) < 0) {
1094 perror("strace: open(\"/proc/.../regs\", ...)");
1098 sprintf(proc, "/proc/%d/status", tcp->pid);
1099 if ((tcp->pfd_status = open(proc, O_RDONLY)) < 0) {
1100 perror("strace: open(\"/proc/.../status\", ...)");
1104 tcp->pfd_status = -1;
1105 #endif /* FREEBSD */
1109 * Wait for the child to pause. Because of a race
1110 * condition we have to poll for the event.
1113 if (IOCTL_STATUS (tcp) < 0) {
1114 perror("strace: PIOCSTATUS");
1117 if (tcp->status.PR_FLAGS & PR_ASLEEP)
1122 /* Stop the process so that we own the stop. */
1123 if (IOCTL(tcp->pfd, PIOCSTOP, (char *)NULL) < 0) {
1124 perror("strace: PIOCSTOP");
1129 /* Set Run-on-Last-Close. */
1131 if (IOCTL(tcp->pfd, PIOCSET, &arg) < 0) {
1132 perror("PIOCSET PR_RLC");
1135 /* Set or Reset Inherit-on-Fork. */
1137 if (IOCTL(tcp->pfd, followfork ? PIOCSET : PIOCRESET, &arg) < 0) {
1138 perror("PIOC{SET,RESET} PR_FORK");
1141 #else /* !PIOCSET */
1143 if (ioctl(tcp->pfd, PIOCSRLC) < 0) {
1147 if (ioctl(tcp->pfd, followfork ? PIOCSFORK : PIOCRFORK) < 0) {
1148 perror("PIOC{S,R}FORK");
1152 /* just unset the PF_LINGER flag for the Run-on-Last-Close. */
1153 if (ioctl(tcp->pfd, PIOCGFL, &arg) < 0) {
1158 if (ioctl(tcp->pfd, PIOCSFL, arg) < 0) {
1162 #endif /* FREEBSD */
1163 #endif /* !PIOCSET */
1165 /* Enable all syscall entries we care about. */
1166 premptyset(&syscalls);
1167 for (i = 1; i < MAX_QUALS; ++i) {
1168 if (i > (sizeof syscalls) * CHAR_BIT) break;
1169 if (qual_flags [i] & QUAL_TRACE) praddset (&syscalls, i);
1171 praddset (&syscalls, SYS_execve);
1173 praddset (&syscalls, SYS_fork);
1175 praddset (&syscalls, SYS_forkall);
1178 praddset (&syscalls, SYS_fork1);
1181 praddset (&syscalls, SYS_rfork1);
1184 praddset (&syscalls, SYS_rforkall);
1187 if (IOCTL(tcp->pfd, PIOCSENTRY, &syscalls) < 0) {
1188 perror("PIOCSENTRY");
1191 /* Enable the syscall exits. */
1192 if (IOCTL(tcp->pfd, PIOCSEXIT, &syscalls) < 0) {
1196 /* Enable signals we care about. */
1197 premptyset(&signals);
1198 for (i = 1; i < MAX_QUALS; ++i) {
1199 if (i > (sizeof signals) * CHAR_BIT) break;
1200 if (qual_flags [i] & QUAL_SIGNAL) praddset (&signals, i);
1202 if (IOCTL(tcp->pfd, PIOCSTRACE, &signals) < 0) {
1203 perror("PIOCSTRACE");
1206 /* Enable faults we care about */
1207 premptyset(&faults);
1208 for (i = 1; i < MAX_QUALS; ++i) {
1209 if (i > (sizeof faults) * CHAR_BIT) break;
1210 if (qual_flags [i] & QUAL_FAULT) praddset (&faults, i);
1212 if (IOCTL(tcp->pfd, PIOCSFAULT, &faults) < 0) {
1213 perror("PIOCSFAULT");
1217 /* set events flags. */
1218 arg = S_SIG | S_SCE | S_SCX ;
1219 if(ioctl(tcp->pfd, PIOCBIS, arg) < 0) {
1223 #endif /* FREEBSD */
1227 * The SGI PRSABORT doesn't work for pause() so
1228 * we send it a caught signal to wake it up.
1230 kill(tcp->pid, SIGINT);
1233 /* The child is in a pause(), abort it. */
1235 if (IOCTL (tcp->pfd, PIOCRUN, &arg) < 0) {
1242 /* wake up the child if it received the SIGSTOP */
1243 kill(tcp->pid, SIGCONT);
1246 /* Wait for the child to do something. */
1247 if (IOCTL_WSTOP (tcp) < 0) {
1248 perror("PIOCWSTOP");
1251 if (tcp->status.PR_WHY == PR_SYSENTRY) {
1252 tcp->flags &= ~TCB_INSYSCALL;
1254 if (known_scno(tcp) == SYS_execve)
1257 /* Set it running: maybe execve will be next. */
1260 if (IOCTL(tcp->pfd, PIOCRUN, &arg) < 0) {
1262 if (IOCTL(tcp->pfd, PIOCRUN, 0) < 0) {
1263 #endif /* FREEBSD */
1268 /* handle the case where we "opened" the child before
1269 it did the kill -STOP */
1270 if (tcp->status.PR_WHY == PR_SIGNALLED &&
1271 tcp->status.PR_WHAT == SIGSTOP)
1272 kill(tcp->pid, SIGCONT);
1279 if (attaching < 2) {
1280 /* We are attaching to an already running process.
1281 * Try to figure out the state of the process in syscalls,
1282 * to handle the first event well.
1283 * This is done by having a look at the "wchan" property of the
1284 * process, which tells where it is stopped (if it is). */
1286 char wchan[20]; /* should be enough */
1288 sprintf(proc, "/proc/%d/status", tcp->pid);
1289 status = fopen(proc, "r");
1291 (fscanf(status, "%*s %*d %*d %*d %*d %*d,%*d %*s %*d,%*d"
1292 "%*d,%*d %*d,%*d %19s", wchan) == 1) &&
1293 strcmp(wchan, "nochan") && strcmp(wchan, "spread") &&
1294 strcmp(wchan, "stopevent")) {
1295 /* The process is asleep in the middle of a syscall.
1296 Fake the syscall entry event */
1297 tcp->flags &= ~(TCB_INSYSCALL|TCB_STARTUP);
1298 tcp->status.PR_WHY = PR_SYSENTRY;
1303 } /* otherwise it's a fork being followed */
1305 #endif /* FREEBSD */
1306 #ifndef HAVE_POLLABLE_PROCFS
1307 if (proc_poll_pipe[0] != -1)
1308 proc_poller(tcp->pfd);
1309 else if (nprocs > 1) {
1311 proc_poller(last_pfd);
1312 proc_poller(tcp->pfd);
1314 last_pfd = tcp->pfd;
1315 #endif /* !HAVE_POLLABLE_PROCFS */
1319 #endif /* USE_PROCFS */
1328 for (i = 0; i < tcbtabsize; i++) {
1330 if (pid && tcp->pid != pid)
1332 if (tcp->flags & TCB_INUSE)
1346 for (i = 0; i < tcbtabsize; i++) {
1347 struct tcb *tcp = tcbtab[i];
1348 if (tcp->pfd != pfd)
1350 if (tcp->flags & TCB_INUSE)
1356 #endif /* USE_PROCFS */
1364 #ifdef TCB_CLONE_THREAD
1365 if (tcp->nclone_threads > 0) {
1366 /* There are other threads left in this process, but this
1367 is the one whose PID represents the whole process.
1368 We need to keep this record around as a zombie until
1369 all the threads die. */
1370 tcp->flags |= TCB_EXITING;
1377 if (tcp->parent != NULL) {
1378 tcp->parent->nchildren--;
1379 #ifdef TCB_CLONE_THREAD
1380 if (tcp->flags & TCB_CLONE_DETACHED)
1381 tcp->parent->nclone_detached--;
1382 if (tcp->flags & TCB_CLONE_THREAD)
1383 tcp->parent->nclone_threads--;
1385 #ifdef TCB_CLONE_DETACHED
1386 if (!(tcp->flags & TCB_CLONE_DETACHED))
1388 tcp->parent->nzombies++;
1390 /* Update `tcp->parent->parent->nchildren' and the other fields
1391 like NCLONE_DETACHED, only for zombie group leader that has
1392 already reported and been short-circuited at the top of this
1393 function. The same condition as at the top of DETACH. */
1394 if ((tcp->flags & TCB_CLONE_THREAD) &&
1395 tcp->parent->nclone_threads == 0 &&
1396 (tcp->parent->flags & TCB_EXITING))
1397 droptcb(tcp->parent);
1403 if (tcp->pfd != -1) {
1407 if (tcp->pfd_reg != -1) {
1408 close(tcp->pfd_reg);
1411 if (tcp->pfd_status != -1) {
1412 close(tcp->pfd_status);
1413 tcp->pfd_status = -1;
1415 #endif /* !FREEBSD */
1417 rebuild_pollv(); /* Note, flags needs to be cleared by now. */
1421 if (outfname && followfork > 1 && tcp->outf)
1436 if (!(tcp->flags & TCB_SUSPENDED)) {
1437 fprintf(stderr, "PANIC: pid %u not suspended\n", tcp->pid);
1440 tcp->flags &= ~TCB_SUSPENDED;
1441 #ifdef TCB_CLONE_THREAD
1442 if (tcp->flags & TCB_CLONE_THREAD)
1443 tcp->parent->nclone_waiting--;
1446 if (ptrace_restart(PTRACE_SYSCALL, tcp, 0) < 0)
1450 fprintf(stderr, "Process %u resumed\n", tcp->pid);
1455 resume_from_tcp (struct tcb *tcp)
1460 /* XXX This won't always be quite right (but it never was).
1461 A waiter with argument 0 or < -1 is waiting for any pid in
1462 a particular pgrp, which this child might or might not be
1463 in. The waiter will only wake up if it's argument is -1
1464 or if it's waiting for tcp->pid's pgrp. It makes a
1465 difference to wake up a waiter when there might be more
1466 traced children, because it could get a false ECHILD
1467 error. OTOH, if this was the last child in the pgrp, then
1468 it ought to wake up and get ECHILD. We would have to
1469 search the system for all pid's in the pgrp to be sure.
1471 && (t->waitpid == -1 ||
1472 (t->waitpid == 0 && getpgid (tcp->pid) == getpgid (t->pid))
1473 || (t->waitpid < 0 && t->waitpid == -getpid (t->pid)))
1477 (tcp->parent->flags & TCB_SUSPENDED) &&
1478 (tcp->parent->waitpid <= 0 || tcp->parent->waitpid == tcp->pid)) {
1479 error = resume(tcp->parent);
1482 #ifdef TCB_CLONE_THREAD
1483 if (tcp->parent && tcp->parent->nclone_waiting > 0) {
1484 /* Some other threads of our parent are waiting too. */
1487 /* Resume all the threads that were waiting for this PID. */
1488 for (i = 0; i < tcbtabsize; i++) {
1489 struct tcb *t = tcbtab[i];
1490 if (t->parent == tcp->parent && t != tcp
1491 && ((t->flags & (TCB_CLONE_THREAD|TCB_SUSPENDED))
1492 == (TCB_CLONE_THREAD|TCB_SUSPENDED))
1493 && t->waitpid == tcp->pid) {
1494 error |= resume (t);
1499 /* Noone was waiting for this PID in particular,
1500 so now we might need to resume some wildcarders. */
1501 for (i = 0; i < tcbtabsize; i++) {
1502 struct tcb *t = tcbtab[i];
1503 if (t->parent == tcp->parent && t != tcp
1505 & (TCB_CLONE_THREAD|TCB_SUSPENDED))
1506 == (TCB_CLONE_THREAD|TCB_SUSPENDED))
1509 error |= resume (t);
1519 #endif /* !USE_PROCFS */
1521 /* detach traced process; continue with sig
1522 Never call DETACH twice on the same process as both unattached and
1523 attached-unstopped processes give the same ESRCH. For unattached process we
1524 would SIGSTOP it and wait for its SIGSTOP notification forever. */
1533 int status, catch_sigstop;
1534 struct tcb *zombie = NULL;
1536 /* If the group leader is lingering only because of this other
1537 thread now dying, then detach the leader as well. */
1538 if ((tcp->flags & TCB_CLONE_THREAD) &&
1539 tcp->parent->nclone_threads == 1 &&
1540 (tcp->parent->flags & TCB_EXITING))
1541 zombie = tcp->parent;
1544 if (tcp->flags & TCB_BPTSET)
1549 * Linux wrongly insists the child be stopped
1550 * before detaching. Arghh. We go through hoops
1551 * to make a clean break of things.
1554 #undef PTRACE_DETACH
1555 #define PTRACE_DETACH PTRACE_SUNDETACH
1558 * On TCB_STARTUP we did PTRACE_ATTACH but still did not get the
1559 * expected SIGSTOP. We must catch exactly one as otherwise the
1560 * detached process would be left stopped (process state T).
1562 catch_sigstop = (tcp->flags & TCB_STARTUP);
1563 if ((error = ptrace(PTRACE_DETACH, tcp->pid, (char *) 1, sig)) == 0) {
1564 /* On a clear day, you can see forever. */
1566 else if (errno != ESRCH) {
1567 /* Shouldn't happen. */
1568 perror("detach: ptrace(PTRACE_DETACH, ...)");
1570 else if (my_tgkill((tcp->flags & TCB_CLONE_THREAD ? tcp->parent->pid
1574 perror("detach: checking sanity");
1576 else if (!catch_sigstop && my_tgkill((tcp->flags & TCB_CLONE_THREAD
1577 ? tcp->parent->pid : tcp->pid),
1578 tcp->pid, SIGSTOP) < 0) {
1580 perror("detach: stopping child");
1584 if (catch_sigstop) {
1587 if (wait4(tcp->pid, &status, __WALL, NULL) < 0) {
1588 if (errno == ECHILD) /* Already gone. */
1590 if (errno != EINVAL) {
1591 perror("detach: waiting");
1595 /* No __WALL here. */
1596 if (waitpid(tcp->pid, &status, 0) < 0) {
1597 if (errno != ECHILD) {
1598 perror("detach: waiting");
1602 /* If no processes, try clones. */
1603 if (wait4(tcp->pid, &status, __WCLONE,
1605 if (errno != ECHILD)
1606 perror("detach: waiting");
1609 #endif /* __WCLONE */
1614 if (!WIFSTOPPED(status)) {
1615 /* Au revoir, mon ami. */
1618 if (WSTOPSIG(status) == SIGSTOP) {
1619 ptrace_restart(PTRACE_DETACH, tcp, sig);
1622 error = ptrace_restart(PTRACE_CONT, tcp,
1623 WSTOPSIG(status) == SIGTRAP ? 0
1624 : WSTOPSIG(status));
1632 /* PTRACE_DETACH won't respect `sig' argument, so we post it here. */
1633 if (sig && kill(tcp->pid, sig) < 0)
1634 perror("detach: kill");
1636 error = ptrace_restart(PTRACE_DETACH, tcp, sig);
1640 error |= resume_from_tcp (tcp);
1644 fprintf(stderr, "Process %u detached\n", tcp->pid);
1649 if (zombie != NULL) {
1650 /* TCP no longer exists therefore you must not detach () it. */
1667 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
1678 #endif /* USE_PROCFS */
1686 for (i = 0; i < tcbtabsize; i++) {
1688 if (!(tcp->flags & TCB_INUSE))
1692 "cleanup: looking at pid %u\n", tcp->pid);
1694 (!outfname || followfork < 2 || tcp_last == tcp)) {
1695 tprintf(" <unfinished ...>");
1698 if (tcp->flags & TCB_ATTACHED)
1701 kill(tcp->pid, SIGCONT);
1702 kill(tcp->pid, SIGTERM);
1716 #ifndef HAVE_STRERROR
1718 #if !HAVE_DECL_SYS_ERRLIST
1719 extern int sys_nerr;
1720 extern char *sys_errlist[];
1721 #endif /* HAVE_DECL_SYS_ERRLIST */
1727 static char buf[64];
1729 if (errno < 1 || errno >= sys_nerr) {
1730 sprintf(buf, "Unknown error %d", errno);
1733 return sys_errlist[errno];
1736 #endif /* HAVE_STERRROR */
1738 #ifndef HAVE_STRSIGNAL
1740 #if defined HAVE_SYS_SIGLIST && !defined HAVE_DECL_SYS_SIGLIST
1741 extern char *sys_siglist[];
1743 #if defined HAVE_SYS__SIGLIST && !defined HAVE_DECL__SYS_SIGLIST
1744 extern char *_sys_siglist[];
1751 static char buf[64];
1753 if (sig < 1 || sig >= NSIG) {
1754 sprintf(buf, "Unknown signal %d", sig);
1757 #ifdef HAVE__SYS_SIGLIST
1758 return _sys_siglist[sig];
1760 return sys_siglist[sig];
1764 #endif /* HAVE_STRSIGNAL */
1775 pollv = (struct pollfd *) malloc(nprocs * sizeof pollv[0]);
1776 if (pollv == NULL) {
1777 fprintf(stderr, "%s: out of memory\n", progname);
1781 for (i = j = 0; i < tcbtabsize; i++) {
1782 struct tcb *tcp = tcbtab[i];
1783 if (!(tcp->flags & TCB_INUSE))
1785 pollv[j].fd = tcp->pfd;
1786 pollv[j].events = POLLWANT;
1790 fprintf(stderr, "strace: proc miscount\n");
1795 #ifndef HAVE_POLLABLE_PROCFS
1802 if (pipe(proc_poll_pipe) < 0) {
1806 for (i = 0; i < 2; i++) {
1807 if (set_cloexec_flag(proc_poll_pipe[i]) < 0) {
1814 proc_poll(pollv, nfds, timeout)
1815 struct pollfd *pollv;
1821 struct proc_pollfd pollinfo;
1823 if ((n = read(proc_poll_pipe[0], &pollinfo, sizeof(pollinfo))) < 0)
1825 if (n != sizeof(struct proc_pollfd)) {
1826 fprintf(stderr, "panic: short read: %d\n", n);
1829 for (i = 0; i < nprocs; i++) {
1830 if (pollv[i].fd == pollinfo.fd)
1831 pollv[i].revents = pollinfo.revents;
1833 pollv[i].revents = 0;
1835 poller_pid = pollinfo.pid;
1849 struct proc_pollfd pollinfo;
1850 struct sigaction sa;
1851 sigset_t blocked_set, empty_set;
1856 struct procfs_status pfs;
1857 #endif /* FREEBSD */
1869 sa.sa_handler = interactive ? SIG_DFL : SIG_IGN;
1871 sigemptyset(&sa.sa_mask);
1872 sigaction(SIGHUP, &sa, NULL);
1873 sigaction(SIGINT, &sa, NULL);
1874 sigaction(SIGQUIT, &sa, NULL);
1875 sigaction(SIGPIPE, &sa, NULL);
1876 sigaction(SIGTERM, &sa, NULL);
1877 sa.sa_handler = wakeup_handler;
1878 sigaction(SIGUSR1, &sa, NULL);
1879 sigemptyset(&blocked_set);
1880 sigaddset(&blocked_set, SIGUSR1);
1881 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
1882 sigemptyset(&empty_set);
1884 if (getrlimit(RLIMIT_NOFILE, &rl) < 0) {
1885 perror("getrlimit(RLIMIT_NOFILE, ...)");
1889 for (i = 0; i < n; i++) {
1890 if (i != pfd && i != proc_poll_pipe[1])
1895 pollinfo.pid = getpid();
1898 if (ioctl(pfd, PIOCWSTOP, NULL) < 0)
1900 if (ioctl(pfd, PIOCWSTOP, &pfs) < 0)
1907 pollinfo.revents = POLLERR;
1910 pollinfo.revents = POLLHUP;
1913 perror("proc_poller: PIOCWSTOP");
1915 write(proc_poll_pipe[1], &pollinfo, sizeof(pollinfo));
1918 pollinfo.revents = POLLWANT;
1919 write(proc_poll_pipe[1], &pollinfo, sizeof(pollinfo));
1920 sigsuspend(&empty_set);
1924 #endif /* !HAVE_POLLABLE_PROCFS */
1934 if (followfork < 2 &&
1935 last < nprocs && (pollv[last].revents & POLLWANT)) {
1937 * The previous process is ready to run again. We'll
1938 * let it do so if it is currently in a syscall. This
1939 * heuristic improves the readability of the trace.
1941 tcp = pfd2tcb(pollv[last].fd);
1942 if (tcp && (tcp->flags & TCB_INSYSCALL))
1943 return pollv[last].fd;
1946 for (i = 0; i < nprocs; i++) {
1947 /* Let competing children run round robin. */
1948 j = (i + last + 1) % nprocs;
1949 if (pollv[j].revents & (POLLHUP | POLLERR)) {
1950 tcp = pfd2tcb(pollv[j].fd);
1952 fprintf(stderr, "strace: lost proc\n");
1958 if (pollv[j].revents & POLLWANT) {
1963 fprintf(stderr, "strace: nothing ready\n");
1971 struct tcb *in_syscall = NULL;
1976 int ioctl_result = 0, ioctl_errno = 0;
1981 sigprocmask(SIG_SETMASK, &empty_set, NULL);
1988 #ifndef HAVE_POLLABLE_PROCFS
1989 if (proc_poll_pipe[0] == -1) {
1998 #ifndef HAVE_POLLABLE_PROCFS
2000 /* fall through ... */
2001 #endif /* !HAVE_POLLABLE_PROCFS */
2003 #ifdef HAVE_POLLABLE_PROCFS
2005 /* On some systems (e.g. UnixWare) we get too much ugly
2006 "unfinished..." stuff when multiple proceses are in
2007 syscalls. Here's a nasty hack */
2014 pv.events = POLLWANT;
2015 if ((what = poll (&pv, 1, 1)) < 0) {
2020 else if (what == 1 && pv.revents & POLLWANT) {
2026 if (poll(pollv, nprocs, INFTIM) < 0) {
2031 #else /* !HAVE_POLLABLE_PROCFS */
2032 if (proc_poll(pollv, nprocs, INFTIM) < 0) {
2037 #endif /* !HAVE_POLLABLE_PROCFS */
2044 /* Look up `pfd' in our table. */
2045 if ((tcp = pfd2tcb(pfd)) == NULL) {
2046 fprintf(stderr, "unknown pfd: %u\n", pfd);
2052 /* Get the status of the process. */
2055 ioctl_result = IOCTL_WSTOP (tcp);
2057 /* Thanks to some scheduling mystery, the first poller
2058 sometimes waits for the already processed end of fork
2059 event. Doing a non blocking poll here solves the problem. */
2060 if (proc_poll_pipe[0] != -1)
2061 ioctl_result = IOCTL_STATUS (tcp);
2063 ioctl_result = IOCTL_WSTOP (tcp);
2064 #endif /* FREEBSD */
2065 ioctl_errno = errno;
2066 #ifndef HAVE_POLLABLE_PROCFS
2067 if (proc_poll_pipe[0] != -1) {
2068 if (ioctl_result < 0)
2069 kill(poller_pid, SIGKILL);
2071 kill(poller_pid, SIGUSR1);
2073 #endif /* !HAVE_POLLABLE_PROCFS */
2079 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
2081 if (ioctl_result < 0) {
2082 /* Find out what happened if it failed. */
2083 switch (ioctl_errno) {
2094 perror("PIOCWSTOP");
2100 if ((tcp->flags & TCB_STARTUP) && (tcp->status.PR_WHY == PR_SYSEXIT)) {
2101 /* discard first event for a syscall we never entered */
2102 IOCTL (tcp->pfd, PIOCRUN, 0);
2107 /* clear the just started flag */
2108 tcp->flags &= ~TCB_STARTUP;
2110 /* set current output file */
2114 struct timeval stime;
2119 if ((len = pread(tcp->pfd_status, buf, sizeof(buf) - 1, 0)) > 0) {
2122 "%*s %*d %*d %*d %*d %*d,%*d %*s %*d,%*d %*d,%*d %ld,%ld",
2123 &stime.tv_sec, &stime.tv_usec);
2125 stime.tv_sec = stime.tv_usec = 0;
2126 #else /* !FREEBSD */
2127 stime.tv_sec = tcp->status.pr_stime.tv_sec;
2128 stime.tv_usec = tcp->status.pr_stime.tv_nsec/1000;
2129 #endif /* !FREEBSD */
2130 tv_sub(&tcp->dtime, &stime, &tcp->stime);
2133 what = tcp->status.PR_WHAT;
2134 switch (tcp->status.PR_WHY) {
2137 if (tcp->status.PR_FLAGS & PR_ASLEEP) {
2138 tcp->status.PR_WHY = PR_SYSENTRY;
2139 if (trace_syscall(tcp) < 0) {
2140 fprintf(stderr, "syscall trouble\n");
2145 #endif /* !FREEBSD */
2151 if (trace_syscall(tcp) < 0) {
2152 fprintf(stderr, "syscall trouble\n");
2157 if (!cflag && (qual_flags[what] & QUAL_SIGNAL)) {
2159 tprintf("--- %s (%s) ---",
2160 signame(what), strsignal(what));
2163 if (tcp->status.PR_INFO.si_signo == what) {
2165 tprintf(" siginfo=");
2166 printsiginfo(&tcp->status.PR_INFO, 1);
2173 if (!cflag && (qual_flags[what] & QUAL_FAULT)) {
2175 tprintf("=== FAULT %d ===", what);
2180 case 0: /* handle case we polled for nothing */
2184 fprintf(stderr, "odd stop %d\n", tcp->status.PR_WHY);
2190 if (IOCTL (tcp->pfd, PIOCRUN, &arg) < 0) {
2192 if (IOCTL (tcp->pfd, PIOCRUN, 0) < 0) {
2201 #else /* !USE_PROCFS */
2203 #ifdef TCB_GROUP_EXITING
2204 /* Handle an exit detach or death signal that is taking all the
2205 related clone threads with it. This is called in three circumstances:
2206 SIG == -1 TCP has already died (TCB_ATTACHED is clear, strace is parent).
2207 SIG == 0 Continuing TCP will perform an exit_group syscall.
2208 SIG == other Continuing TCP with SIG will kill the process.
2211 handle_group_exit(struct tcb *tcp, int sig)
2213 /* We need to locate our records of all the clone threads
2214 related to TCP, either its children or siblings. */
2215 struct tcb *leader = NULL;
2217 if (tcp->flags & TCB_CLONE_THREAD)
2218 leader = tcp->parent;
2219 else if (tcp->nclone_detached > 0)
2223 if (leader != NULL && leader != tcp
2224 && !(leader->flags & TCB_GROUP_EXITING)
2225 && !(tcp->flags & TCB_STARTUP)
2228 "PANIC: handle_group_exit: %d leader %d\n",
2229 tcp->pid, leader ? leader->pid : -1);
2231 /* TCP no longer exists therefore you must not detach() it. */
2233 resume_from_tcp(tcp);
2235 droptcb(tcp); /* Already died. */
2238 /* Mark that we are taking the process down. */
2239 tcp->flags |= TCB_EXITING | TCB_GROUP_EXITING;
2240 if (tcp->flags & TCB_ATTACHED) {
2242 if (leader != NULL && leader != tcp)
2243 leader->flags |= TCB_GROUP_EXITING;
2245 if (ptrace_restart(PTRACE_CONT, tcp, sig) < 0) {
2249 if (leader != NULL) {
2250 leader->flags |= TCB_GROUP_EXITING;
2254 /* The leader will report to us as parent now,
2255 and then we'll get to the SIG==-1 case. */
2274 static int wait4_options = __WALL;
2278 while (nprocs != 0) {
2282 sigprocmask(SIG_SETMASK, &empty_set, NULL);
2285 pid = wait4(-1, &status, wait4_options, cflag ? &ru : NULL);
2286 if (pid < 0 && (wait4_options & __WALL) && errno == EINVAL) {
2287 /* this kernel does not support __WALL */
2288 wait4_options &= ~__WALL;
2290 pid = wait4(-1, &status, wait4_options,
2291 cflag ? &ru : NULL);
2293 if (pid < 0 && !(wait4_options & __WALL) && errno == ECHILD) {
2294 /* most likely a "cloned" process */
2295 pid = wait4(-1, &status, __WCLONE,
2296 cflag ? &ru : NULL);
2298 fprintf(stderr, "strace: clone wait4 "
2299 "failed: %s\n", strerror(errno));
2303 pid = wait4(-1, &status, 0, cflag ? &ru : NULL);
2307 pid = wait(&status);
2311 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
2314 switch (wait_errno) {
2319 * We would like to verify this case
2320 * but sometimes a race in Solbourne's
2321 * version of SunOS sometimes reports
2322 * ECHILD before sending us SIGCHILD.
2327 fprintf(stderr, "strace: proc miscount\n");
2333 perror("strace: wait");
2337 if (pid == popen_pid) {
2338 if (WIFEXITED(status) || WIFSIGNALED(status))
2343 fprintf(stderr, " [wait(%#x) = %u]\n", status, pid);
2345 /* Look up `pid' in our table. */
2346 if ((tcp = pid2tcb(pid)) == NULL) {
2349 /* This is needed to go with the CLONE_PTRACE
2350 changes in process.c/util.c: we might see
2351 the child's initial trap before we see the
2352 parent return from the clone syscall.
2353 Leave the child suspended until the parent
2354 returns from its system call. Only then
2355 will we have the association of parent and
2356 child so that we know how to do clearbpt
2358 tcp = alloctcb(pid);
2359 tcp->flags |= TCB_ATTACHED | TCB_SUSPENDED;
2362 Process %d attached (waiting for parent)\n",
2366 /* This can happen if a clone call used
2367 CLONE_PTRACE itself. */
2370 fprintf(stderr, "unknown pid: %u\n", pid);
2371 if (WIFSTOPPED(status))
2372 ptrace(PTRACE_CONT, pid, (char *) 1, 0);
2376 /* set current output file */
2380 tv_sub(&tcp->dtime, &ru.ru_stime, &tcp->stime);
2381 tcp->stime = ru.ru_stime;
2385 if (tcp->flags & TCB_SUSPENDED) {
2387 * Apparently, doing any ptrace() call on a stopped
2388 * process, provokes the kernel to report the process
2389 * status again on a subsequent wait(), even if the
2390 * process has not been actually restarted.
2391 * Since we have inspected the arguments of suspended
2392 * processes we end up here testing for this case.
2396 if (WIFSIGNALED(status)) {
2397 if (pid == strace_child)
2398 exit_code = 0x100 | WTERMSIG(status);
2400 && (qual_flags[WTERMSIG(status)] & QUAL_SIGNAL)) {
2402 tprintf("+++ killed by %s %s+++",
2403 signame(WTERMSIG(status)),
2405 WCOREDUMP(status) ? "(core dumped) " :
2410 #ifdef TCB_GROUP_EXITING
2411 handle_group_exit(tcp, -1);
2417 if (WIFEXITED(status)) {
2418 if (pid == strace_child)
2419 exit_code = WEXITSTATUS(status);
2421 fprintf(stderr, "pid %u exited with %d\n", pid, WEXITSTATUS(status));
2422 if ((tcp->flags & (TCB_ATTACHED|TCB_STARTUP)) == TCB_ATTACHED
2423 #ifdef TCB_GROUP_EXITING
2424 && !(tcp->parent && (tcp->parent->flags & TCB_GROUP_EXITING))
2425 && !(tcp->flags & TCB_GROUP_EXITING)
2429 "PANIC: attached pid %u exited with %d\n",
2430 pid, WEXITSTATUS(status));
2432 if (tcp == tcp_last) {
2433 if ((tcp->flags & (TCB_INSYSCALL|TCB_REPRINT)) == TCB_INSYSCALL)
2434 tprintf(" <unfinished ... exit status %d>\n",
2435 WEXITSTATUS(status));
2438 #ifdef TCB_GROUP_EXITING
2439 handle_group_exit(tcp, -1);
2445 if (!WIFSTOPPED(status)) {
2446 fprintf(stderr, "PANIC: pid %u not stopped\n", pid);
2451 fprintf(stderr, "pid %u stopped, [%s]\n",
2452 pid, signame(WSTOPSIG(status)));
2455 * Interestingly, the process may stop
2456 * with STOPSIG equal to some other signal
2457 * than SIGSTOP if we happend to attach
2458 * just before the process takes a signal.
2459 * A no-MMU vforked child won't send up a signal,
2460 * so skip the first (lost) execve notification.
2462 if ((tcp->flags & TCB_STARTUP) &&
2463 (WSTOPSIG(status) == SIGSTOP || strace_vforked)) {
2465 * This flag is there to keep us in sync.
2466 * Next time this process stops it should
2467 * really be entering a system call.
2469 tcp->flags &= ~TCB_STARTUP;
2470 if (tcp->flags & TCB_BPTSET) {
2472 * One example is a breakpoint inherited from
2473 * parent through fork ().
2475 if (clearbpt(tcp) < 0) /* Pretty fatal */ {
2484 if (WSTOPSIG(status) != SIGTRAP) {
2485 if (WSTOPSIG(status) == SIGSTOP &&
2486 (tcp->flags & TCB_SIGTRAPPED)) {
2488 * Trapped attempt to block SIGTRAP
2489 * Hope we are back in control now.
2491 tcp->flags &= ~(TCB_INSYSCALL | TCB_SIGTRAPPED);
2492 if (ptrace_restart(PTRACE_SYSCALL, tcp, 0) < 0) {
2499 && (qual_flags[WSTOPSIG(status)] & QUAL_SIGNAL)) {
2500 unsigned long addr = 0;
2502 #if defined(PT_CR_IPSR) && defined(PT_CR_IIP) && defined(PT_GETSIGINFO)
2507 upeek(tcp, PT_CR_IPSR, &psr);
2508 upeek(tcp, PT_CR_IIP, &pc);
2510 pc += (psr >> PSR_RI) & 0x3;
2511 ptrace(PT_GETSIGINFO, pid, 0, (long) &si);
2512 addr = (unsigned long) si.si_addr;
2513 #elif defined PTRACE_GETSIGINFO
2514 if (WSTOPSIG(status) == SIGSEGV ||
2515 WSTOPSIG(status) == SIGBUS) {
2517 if (ptrace(PTRACE_GETSIGINFO, pid,
2519 addr = (unsigned long)
2524 tprintf("--- %s (%s) @ %lx (%lx) ---",
2525 signame(WSTOPSIG(status)),
2526 strsignal(WSTOPSIG(status)), pc, addr);
2529 if (((tcp->flags & TCB_ATTACHED) ||
2530 tcp->nclone_threads > 0) &&
2531 !sigishandled(tcp, WSTOPSIG(status))) {
2532 #ifdef TCB_GROUP_EXITING
2533 handle_group_exit(tcp, WSTOPSIG(status));
2535 detach(tcp, WSTOPSIG(status));
2539 if (ptrace_restart(PTRACE_SYSCALL, tcp, WSTOPSIG(status)) < 0) {
2543 tcp->flags &= ~TCB_SUSPENDED;
2546 /* we handled the STATUS, we are permitted to interrupt now. */
2549 if (trace_syscall(tcp) < 0 && !tcp->ptrace_errno) {
2550 /* ptrace() failed in trace_syscall() with ESRCH.
2551 * Likely a result of process disappearing mid-flight.
2552 * Observed case: exit_group() terminating
2553 * all processes in thread group. In this case, threads
2554 * "disappear" in an unpredictable moment without any
2555 * notification to strace via wait().
2557 if (tcp->flags & TCB_ATTACHED) {
2559 /* Do we have dangling line "syscall(param, param"?
2560 * Finish the line then. We cannot
2562 tcp_last->flags |= TCB_REPRINT;
2563 tprintf(" <unfinished ...>");
2569 tcp->pid, (char *) 1, SIGTERM);
2574 if (tcp->flags & TCB_EXITING) {
2575 #ifdef TCB_GROUP_EXITING
2576 if (tcp->flags & TCB_GROUP_EXITING) {
2577 if (handle_group_exit(tcp, 0) < 0)
2582 if (tcp->flags & TCB_ATTACHED)
2584 else if (ptrace_restart(PTRACE_CONT, tcp, 0) < 0) {
2590 if (tcp->flags & TCB_SUSPENDED) {
2592 fprintf(stderr, "Process %u suspended\n", pid);
2596 if (ptrace_restart(PTRACE_SYSCALL, tcp, 0) < 0) {
2604 #endif /* !USE_PROCFS */
2610 #define VA_START(a, b) va_start(a, b)
2612 #include <varargs.h>
2613 #define VA_START(a, b) va_start(a)
2618 tprintf(const char *fmt, ...)
2620 tprintf(fmt, va_alist)
2627 VA_START(args, fmt);
2629 int n = vfprintf(outf, fmt, args);
2630 if (n < 0 && outf != stderr)
2631 perror(outfname == NULL
2632 ? "<writing to pipe>" : outfname);
2645 if (tcp_last->ptrace_errno) {
2646 if (tcp_last->flags & TCB_INSYSCALL) {
2647 tprintf(" <unavailable>)");
2650 tprintf("= ? <unavailable>\n");
2651 tcp_last->ptrace_errno = 0;
2652 } else if (!outfname || followfork < 2 || tcp_last == tcp) {
2653 tcp_last->flags |= TCB_REPRINT;
2654 tprintf(" <unfinished ...>\n");
2658 if ((followfork == 1 || pflag_seen > 1) && outfname)
2659 tprintf("%-5d ", tcp->pid);
2660 else if (nprocs > 1 && !outfname)
2661 tprintf("[pid %5u] ", tcp->pid);
2663 char str[sizeof("HH:MM:SS")];
2664 struct timeval tv, dtv;
2665 static struct timeval otv;
2667 gettimeofday(&tv, NULL);
2669 if (otv.tv_sec == 0)
2671 tv_sub(&dtv, &tv, &otv);
2672 tprintf("%6ld.%06ld ",
2673 (long) dtv.tv_sec, (long) dtv.tv_usec);
2676 else if (tflag > 2) {
2677 tprintf("%ld.%06ld ",
2678 (long) tv.tv_sec, (long) tv.tv_usec);
2681 time_t local = tv.tv_sec;
2682 strftime(str, sizeof(str), "%T", localtime(&local));
2684 tprintf("%s.%06ld ", str, (long) tv.tv_usec);
2686 tprintf("%s ", str);
2698 tprintf("%*s", col - curcol, "");
2708 #ifdef HAVE_MP_PROCFS
2711 mp_ioctl(int fd, int cmd, void *arg, int size)
2713 struct iovec iov[2];
2716 iov[0].iov_base = &cmd;
2717 iov[0].iov_len = sizeof cmd;
2720 iov[1].iov_base = arg;
2721 iov[1].iov_len = size;
2724 return writev(fd, iov, n);