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.
33 #include <sys/types.h>
38 #include <sys/param.h>
40 #include <sys/resource.h>
48 #if defined(IA64) && defined(LINUX)
49 # include <asm/ptrace_offsets.h>
57 #include <sys/stropts.h>
65 int debug = 0, followfork = 0, followvfork = 0, interactive = 0;
66 int rflag = 0, tflag = 0, dtime = 0, cflag = 0;
67 int iflag = 0, xflag = 0, qflag = 0;
70 /* Sometimes we want to print only succeeding syscalls. */
71 int not_failing_only = 0;
73 char *username = NULL;
77 int acolumn = DEFAULT_ACOLUMN;
78 int max_strlen = DEFAULT_STRLEN;
79 char *outfname = NULL;
82 unsigned int nprocs, tcbtabsize;
84 extern char version[];
85 extern char **environ;
87 static struct tcb *pid2tcb P((int pid));
88 static int trace P((void));
89 static void cleanup P((void));
90 static void interrupt P((int sig));
91 static sigset_t empty_set, blocked_set;
93 #ifdef HAVE_SIG_ATOMIC_T
94 static volatile sig_atomic_t interrupted;
95 #else /* !HAVE_SIG_ATOMIC_T */
97 static volatile int interrupted;
99 static int interrupted;
100 #endif /* !__STDC__ */
101 #endif /* !HAVE_SIG_ATOMIC_T */
105 static struct tcb *pfd2tcb P((int pfd));
106 static void reaper P((int sig));
107 static void rebuild_pollv P((void));
108 static struct pollfd *pollv;
110 #ifndef HAVE_POLLABLE_PROCFS
112 static void proc_poll_open P((void));
113 static void proc_poller P((int pfd));
121 static int poller_pid;
122 static int proc_poll_pipe[2] = { -1, -1 };
124 #endif /* !HAVE_POLLABLE_PROCFS */
126 #ifdef HAVE_MP_PROCFS
127 #define POLLWANT POLLWRNORM
129 #define POLLWANT POLLPRI
131 #endif /* USE_PROCFS */
139 usage: strace [-dffhiqrtttTvVxx] [-a column] [-e expr] ... [-o file]\n\
140 [-p pid] ... [-s strsize] [-u username] [command [arg ...]]\n\
141 or: strace -c [-e expr] ... [-O overhead] [-S sortby] [command [arg ...]]\n\
142 -c -- count time, calls, and errors for each syscall and report summary\n\
143 -f -- follow forks, -ff -- with output into separate files\n\
144 -F -- attempt to follow vforks, -h -- print help message\n\
145 -i -- print instruction pointer at time of syscall\n\
146 -q -- suppress messages about attaching, detaching, etc.\n\
147 -r -- print relative timestamp, -t -- absolute timestamp, -tt -- with usecs\n\
148 -T -- print time spent in each syscall, -V -- print version\n\
149 -v -- verbose mode: print unabbreviated argv, stat, termio[s], etc. args\n\
150 -x -- print non-ascii strings in hex, -xx -- print all strings in hex\n\
151 -a column -- alignment COLUMN for printing syscall results (default %d)\n\
152 -e expr -- a qualifying expression: option=[!]all or option=[!]val1[,val2]...\n\
153 options: trace, abbrev, verbose, raw, signal, read, or write\n\
154 -o file -- send trace output to FILE instead of stderr\n\
155 -O overhead -- set overhead for tracing syscalls to OVERHEAD usecs\n\
156 -p pid -- trace process with process id PID, may be repeated\n\
157 -s strsize -- limit length of print strings to STRSIZE chars (default %d)\n\
158 -S sortby -- sort syscall counts by: time, calls, name, nothing (default %s)\n\
159 -u username -- run command as username handling setuid and/or setgid\n\
160 -z -- print only succeeding syscalls\n\
161 ", DEFAULT_ACOLUMN, DEFAULT_STRLEN, DEFAULT_SORTBY);
185 static char buf[BUFSIZ];
187 /* Allocate the initial tcbtab. */
188 tcbtabsize = argc; /* Surely enough for all -p args. */
189 tcbtab = (struct tcb **) malloc (tcbtabsize * sizeof tcbtab[0]);
190 tcbtab[0] = (struct tcb *) calloc (tcbtabsize, sizeof *tcbtab[0]);
191 for (tcp = tcbtab[0]; tcp < &tcbtab[0][tcbtabsize]; ++tcp)
192 tcbtab[tcp - tcbtab[0]] = &tcbtab[0][tcp - tcbtab[0]];
197 qualify("trace=all");
198 qualify("abbrev=all");
199 qualify("verbose=all");
200 qualify("signal=all");
201 set_sortby(DEFAULT_SORTBY);
202 set_personality(DEFAULT_PERSONALITY);
203 while ((c = getopt(argc, argv,
204 "+cdfFhiqrtTvVxza:e:o:O:p:s:S:u:")) != EOF) {
242 qualify("abbrev=none");
245 printf("%s\n", version);
249 not_failing_only = 1;
252 acolumn = atoi(optarg);
258 outfname = strdup(optarg);
261 set_overhead(atoi(optarg));
264 if ((pid = atoi(optarg)) == 0) {
265 fprintf(stderr, "%s: Invalid process id: %s\n",
269 if (pid == getpid()) {
270 fprintf(stderr, "%s: I'm sorry, I can't let you do that, Dave.\n", progname);
273 if ((tcp = alloctcb(pid)) == NULL) {
274 fprintf(stderr, "%s: tcb table full, please recompile strace\n",
278 tcp->flags |= TCB_ATTACHED;
282 max_strlen = atoi(optarg);
288 username = strdup(optarg);
296 /* See if they want to run as another user. */
297 if (username != NULL) {
300 if (getuid() != 0 || geteuid() != 0) {
302 "%s: you must be root to use the -u option\n",
306 if ((pent = getpwnam(username)) == NULL) {
307 fprintf(stderr, "%s: cannot find user `%s'\n",
311 run_uid = pent->pw_uid;
312 run_gid = pent->pw_gid;
320 setreuid(geteuid(), getuid());
323 /* See if they want to pipe the output. */
324 if (outfname && (outfname[0] == '|' || outfname[0] == '!')) {
325 if ((outf = popen(outfname + 1, "w")) == NULL) {
326 fprintf(stderr, "%s: can't popen '%s': %s\n",
327 progname, outfname + 1, strerror(errno));
334 /* Check if they want to redirect the output. */
338 if ((outf = fopen(outfname, "w")) == NULL) {
339 fprintf(stderr, "%s: can't fopen '%s': %s\n",
340 progname, outfname, strerror(errno));
344 if ((f=fcntl(fileno(outf), F_GETFD)) < 0 ) {
345 perror("failed to get flags for outputfile");
349 if (fcntl(fileno(outf), F_SETFD, f|FD_CLOEXEC) < 0 ) {
350 perror("failed to set flags for outputfile");
356 setreuid(geteuid(), getuid());
361 setvbuf(outf, buf, _IOLBF, BUFSIZ);
363 else if (optind < argc)
368 for (c = 0; c < tcbtabsize; c++) {
370 /* Reinitialize the output since it may have changed. */
372 if (!(tcp->flags & TCB_INUSE) || !(tcp->flags & TCB_ATTACHED))
375 if (proc_open(tcp, 1) < 0) {
376 fprintf(stderr, "trouble opening proc file\n");
380 #else /* !USE_PROCFS */
381 if (ptrace(PTRACE_ATTACH, tcp->pid, (char *) 1, 0) < 0) {
382 perror("attach: ptrace(PTRACE_ATTACH, ...)");
386 #endif /* !USE_PROCFS */
389 "Process %u attached - interrupt to quit\n",
396 char pathname[MAXPATHLEN];
398 filename = argv[optind];
399 if (strchr(filename, '/'))
400 strcpy(pathname, filename);
401 #ifdef USE_DEBUGGING_EXEC
403 * Debuggers customarily check the current directory
404 * first regardless of the path but doing that gives
405 * security geeks a panic attack.
407 else if (stat(filename, &statbuf) == 0)
408 strcpy(pathname, filename);
409 #endif /* USE_DEBUGGING_EXEC */
414 for (path = getenv("PATH"); path && *path; path += m) {
415 if (strchr(path, ':')) {
416 n = strchr(path, ':') - path;
420 m = n = strlen(path);
422 getcwd(pathname, MAXPATHLEN);
423 len = strlen(pathname);
426 strncpy(pathname, path, n);
429 if (len && pathname[len - 1] != '/')
430 pathname[len++] = '/';
431 strcpy(pathname + len, filename);
432 if (stat(pathname, &statbuf) == 0)
436 if (stat(pathname, &statbuf) < 0) {
437 fprintf(stderr, "%s: %s: command not found\n",
441 switch (pid = fork()) {
443 perror("strace: fork");
449 if (outf != stderr) close (fileno (outf));
451 /* Kludge for SGI, see proc_open for details. */
452 sa.sa_handler = foobar;
454 sigemptyset(&sa.sa_mask);
455 sigaction(SIGINT, &sa, NULL);
460 kill(getpid(), SIGSTOP); /* stop HERE */
462 #else /* !USE_PROCFS */
464 close(fileno (outf));
466 if (ptrace(PTRACE_TRACEME, 0, (char *) 1, 0) < 0) {
467 perror("strace: ptrace(PTRACE_TRACEME, ...)");
471 kill(getpid(), SIGSTOP);
473 if (username != NULL || geteuid() == 0) {
474 uid_t run_euid = run_uid;
475 gid_t run_egid = run_gid;
477 if (statbuf.st_mode & S_ISUID)
478 run_euid = statbuf.st_uid;
479 if (statbuf.st_mode & S_ISGID)
480 run_egid = statbuf.st_gid;
483 * It is important to set groups before we
484 * lose privileges on setuid.
486 if (username != NULL) {
487 if (initgroups(username, run_gid) < 0) {
488 perror("initgroups");
491 if (setregid(run_gid, run_egid) < 0) {
495 if (setreuid(run_uid, run_euid) < 0) {
502 setreuid(run_uid, run_uid);
503 #endif /* !USE_PROCFS */
505 execv(pathname, &argv[optind]);
506 perror("strace: exec");
511 if ((tcp = alloctcb(pid)) == NULL) {
512 fprintf(stderr, "tcb table full\n");
517 if (proc_open(tcp, 0) < 0) {
518 fprintf(stderr, "trouble opening proc file\n");
522 #endif /* USE_PROCFS */
524 fake_execve(tcp, pathname, &argv[optind], environ);
525 #endif /* !USE_PROCFS */
529 else if (pflag_seen == 0)
532 sigemptyset(&empty_set);
533 sigemptyset(&blocked_set);
534 sa.sa_handler = SIG_IGN;
535 sigemptyset(&sa.sa_mask);
537 sigaction(SIGTTOU, &sa, NULL);
538 sigaction(SIGTTIN, &sa, NULL);
540 sigaddset(&blocked_set, SIGHUP);
541 sigaddset(&blocked_set, SIGINT);
542 sigaddset(&blocked_set, SIGQUIT);
543 sigaddset(&blocked_set, SIGPIPE);
544 sigaddset(&blocked_set, SIGTERM);
545 sa.sa_handler = interrupt;
547 /* POSIX signals on sunos4.1 are a little broken. */
548 sa.sa_flags = SA_INTERRUPT;
551 sigaction(SIGHUP, &sa, NULL);
552 sigaction(SIGINT, &sa, NULL);
553 sigaction(SIGQUIT, &sa, NULL);
554 sigaction(SIGPIPE, &sa, NULL);
555 sigaction(SIGTERM, &sa, NULL);
557 sa.sa_handler = reaper;
558 sigaction(SIGCHLD, &sa, NULL);
560 /* Make sure SIGCHLD has the default action so that waitpid
561 definitely works without losing track of children. The user
562 should not have given us a bogus state to inherit, but he might
563 have. Arguably we should detect SIG_IGN here and pass it on
564 to children, but probably noone really needs that. */
565 sa.sa_handler = SIG_DFL;
566 sigaction(SIGCHLD, &sa, NULL);
567 #endif /* USE_PROCFS */
579 char name[MAXPATHLEN];
582 if (outfname && followfork > 1) {
583 sprintf(name, "%s.%u", outfname, tcp->pid);
585 setreuid(geteuid(), getuid());
587 fp = fopen(name, "w");
589 setreuid(geteuid(), getuid());
607 for (i = 0; i < tcbtabsize; i++) {
609 if ((tcp->flags & TCB_INUSE) == 0) {
613 tcp->flags = TCB_INUSE | TCB_STARTUP;
614 tcp->outf = outf; /* Initialise to current out file */
615 tcp->stime.tv_sec = 0;
616 tcp->stime.tv_usec = 0;
627 proc_open(tcp, attaching)
639 #ifndef HAVE_POLLABLE_PROCFS
643 #ifdef HAVE_MP_PROCFS
644 /* Open the process pseudo-files in /proc. */
645 sprintf(proc, "/proc/%d/ctl", tcp->pid);
646 if ((tcp->pfd = open(proc, O_WRONLY|O_EXCL)) < 0) {
647 perror("strace: open(\"/proc/...\", ...)");
650 if ((arg = fcntl(tcp->pfd, F_GETFD)) < 0) {
654 if (fcntl(tcp->pfd, F_SETFD, arg|FD_CLOEXEC) < 0) {
658 sprintf(proc, "/proc/%d/status", tcp->pid);
659 if ((tcp->pfd_stat = open(proc, O_RDONLY|O_EXCL)) < 0) {
660 perror("strace: open(\"/proc/...\", ...)");
663 if ((arg = fcntl(tcp->pfd_stat, F_GETFD)) < 0) {
667 if (fcntl(tcp->pfd_stat, F_SETFD, arg|FD_CLOEXEC) < 0) {
671 sprintf(proc, "/proc/%d/as", tcp->pid);
672 if ((tcp->pfd_as = open(proc, O_RDONLY|O_EXCL)) < 0) {
673 perror("strace: open(\"/proc/...\", ...)");
676 if ((arg = fcntl(tcp->pfd_as, F_GETFD)) < 0) {
680 if (fcntl(tcp->pfd_as, F_SETFD, arg|FD_CLOEXEC) < 0) {
685 /* Open the process pseudo-file in /proc. */
687 sprintf(proc, "/proc/%d", tcp->pid);
688 if ((tcp->pfd = open(proc, O_RDWR|O_EXCL)) < 0) {
690 sprintf(proc, "/proc/%d/mem", tcp->pid);
691 if ((tcp->pfd = open(proc, O_RDWR)) < 0) {
693 perror("strace: open(\"/proc/...\", ...)");
696 if ((arg = fcntl(tcp->pfd, F_GETFD)) < 0) {
700 if (fcntl(tcp->pfd, F_SETFD, arg|FD_CLOEXEC) < 0) {
706 sprintf(proc, "/proc/%d/regs", tcp->pid);
707 if ((tcp->pfd_reg = open(proc, O_RDONLY)) < 0) {
708 perror("strace: open(\"/proc/.../regs\", ...)");
712 sprintf(proc, "/proc/%d/status", tcp->pid);
713 if ((tcp->pfd_status = open(proc, O_RDONLY)) < 0) {
714 perror("strace: open(\"/proc/.../status\", ...)");
718 tcp->pfd_status = -1;
723 * Wait for the child to pause. Because of a race
724 * condition we have to poll for the event.
727 if (IOCTL_STATUS (tcp) < 0) {
728 perror("strace: PIOCSTATUS");
731 if (tcp->status.PR_FLAGS & PR_ASLEEP)
736 /* Stop the process so that we own the stop. */
737 if (IOCTL(tcp->pfd, PIOCSTOP, (char *)NULL) < 0) {
738 perror("strace: PIOCSTOP");
743 /* Set Run-on-Last-Close. */
745 if (IOCTL(tcp->pfd, PIOCSET, &arg) < 0) {
746 perror("PIOCSET PR_RLC");
749 /* Set or Reset Inherit-on-Fork. */
751 if (IOCTL(tcp->pfd, followfork ? PIOCSET : PIOCRESET, &arg) < 0) {
752 perror("PIOC{SET,RESET} PR_FORK");
757 if (ioctl(tcp->pfd, PIOCSRLC) < 0) {
761 if (ioctl(tcp->pfd, followfork ? PIOCSFORK : PIOCRFORK) < 0) {
762 perror("PIOC{S,R}FORK");
766 /* just unset the PF_LINGER flag for the Run-on-Last-Close. */
767 if (ioctl(tcp->pfd, PIOCGFL, &arg) < 0) {
772 if (ioctl(tcp->pfd, PIOCSFL, arg) < 0) {
777 #endif /* !PIOCSET */
779 /* Enable all syscall entries we care about. */
780 premptyset(&syscalls);
781 for (i = 1; i < MAX_QUALS; ++i) {
782 if (i > (sizeof syscalls) * CHAR_BIT) break;
783 if (qual_flags [i] & QUAL_TRACE) praddset (&syscalls, i);
785 praddset (&syscalls, SYS_execve);
787 praddset (&syscalls, SYS_fork);
789 praddset (&syscalls, SYS_forkall);
792 praddset (&syscalls, SYS_fork1);
795 praddset (&syscalls, SYS_rfork1);
798 praddset (&syscalls, SYS_rforkall);
801 if (IOCTL(tcp->pfd, PIOCSENTRY, &syscalls) < 0) {
802 perror("PIOCSENTRY");
805 /* Enable the syscall exits. */
806 if (IOCTL(tcp->pfd, PIOCSEXIT, &syscalls) < 0) {
810 /* Enable signals we care about. */
811 premptyset(&signals);
812 for (i = 1; i < MAX_QUALS; ++i) {
813 if (i > (sizeof signals) * CHAR_BIT) break;
814 if (qual_flags [i] & QUAL_SIGNAL) praddset (&signals, i);
816 if (IOCTL(tcp->pfd, PIOCSTRACE, &signals) < 0) {
817 perror("PIOCSTRACE");
820 /* Enable faults we care about */
822 for (i = 1; i < MAX_QUALS; ++i) {
823 if (i > (sizeof faults) * CHAR_BIT) break;
824 if (qual_flags [i] & QUAL_FAULT) praddset (&faults, i);
826 if (IOCTL(tcp->pfd, PIOCSFAULT, &faults) < 0) {
827 perror("PIOCSFAULT");
831 /* set events flags. */
832 arg = S_SIG | S_SCE | S_SCX ;
833 if(ioctl(tcp->pfd, PIOCBIS, arg) < 0) {
841 * The SGI PRSABORT doesn't work for pause() so
842 * we send it a caught signal to wake it up.
844 kill(tcp->pid, SIGINT);
847 /* The child is in a pause(), abort it. */
849 if (IOCTL (tcp->pfd, PIOCRUN, &arg) < 0) {
856 /* wake up the child if it received the SIGSTOP */
857 kill(tcp->pid, SIGCONT);
860 /* Wait for the child to do something. */
861 if (IOCTL_WSTOP (tcp) < 0) {
865 if (tcp->status.PR_WHY == PR_SYSENTRY) {
866 tcp->flags &= ~TCB_INSYSCALL;
868 if (tcp->scno == SYS_execve)
871 /* Set it running: maybe execve will be next. */
874 if (IOCTL(tcp->pfd, PIOCRUN, &arg) < 0) {
876 if (IOCTL(tcp->pfd, PIOCRUN, 0) < 0) {
882 /* handle the case where we "opened" the child before
883 it did the kill -STOP */
884 if (tcp->status.PR_WHY == PR_SIGNALLED &&
885 tcp->status.PR_WHAT == SIGSTOP)
886 kill(tcp->pid, SIGCONT);
894 /* We are attaching to an already running process.
895 * Try to figure out the state of the process in syscalls,
896 * to handle the first event well.
897 * This is done by having a look at the "wchan" property of the
898 * process, which tells where it is stopped (if it is). */
900 char wchan[20]; /* should be enough */
902 sprintf(proc, "/proc/%d/status", tcp->pid);
903 status = fopen(proc, "r");
905 (fscanf(status, "%*s %*d %*d %*d %*d %*d,%*d %*s %*d,%*d"
906 "%*d,%*d %*d,%*d %19s", wchan) == 1) &&
907 strcmp(wchan, "nochan") && strcmp(wchan, "spread") &&
908 strcmp(wchan, "stopevent")) {
909 /* The process is asleep in the middle of a syscall.
910 Fake the syscall entry event */
911 tcp->flags &= ~(TCB_INSYSCALL|TCB_STARTUP);
912 tcp->status.PR_WHY = PR_SYSENTRY;
917 } /* otherwise it's a fork being followed */
920 #ifndef HAVE_POLLABLE_PROCFS
921 if (proc_poll_pipe[0] != -1)
922 proc_poller(tcp->pfd);
923 else if (nprocs > 1) {
925 proc_poller(last_pfd);
926 proc_poller(tcp->pfd);
929 #endif /* !HAVE_POLLABLE_PROCFS */
933 #endif /* USE_PROCFS */
942 for (i = 0; i < tcbtabsize; i++) {
944 if (pid && tcp->pid != pid)
946 if (tcp->flags & TCB_INUSE)
961 for (i = 0, tcp = tcbtab; i < tcbtabsize; i++, tcp++) {
964 if (tcp->flags & TCB_INUSE)
970 #endif /* USE_PROCFS */
982 if (tcp->pfd != -1) {
986 if (tcp->pfd_reg != -1) {
990 if (tcp->pfd_status != -1) {
991 close(tcp->pfd_status);
992 tcp->pfd_status = -1;
994 #endif /* !FREEBSD */
999 if (tcp->parent != NULL) {
1000 tcp->parent->nchildren--;
1004 if (outfname && followfork > 1 && tcp->outf)
1019 if (!(tcp->flags & TCB_SUSPENDED)) {
1020 fprintf(stderr, "PANIC: pid %u not suspended\n", tcp->pid);
1023 tcp->flags &= ~TCB_SUSPENDED;
1025 if (ptrace(PTRACE_SYSCALL, tcp->pid, (char *) 1, 0) < 0) {
1026 perror("resume: ptrace(PTRACE_SYSCALL, ...)");
1031 fprintf(stderr, "Process %u resumed\n", tcp->pid);
1035 #endif /* !USE_PROCFS */
1037 /* detach traced process; continue with sig */
1049 if (tcp->flags & TCB_BPTSET)
1054 * Linux wrongly insists the child be stopped
1055 * before detaching. Arghh. We go through hoops
1056 * to make a clean break of things.
1059 #undef PTRACE_DETACH
1060 #define PTRACE_DETACH PTRACE_SUNDETACH
1062 if ((error = ptrace(PTRACE_DETACH, tcp->pid, (char *) 1, sig)) == 0) {
1063 /* On a clear day, you can see forever. */
1065 else if (errno != ESRCH) {
1066 /* Shouldn't happen. */
1067 perror("detach: ptrace(PTRACE_DETACH, ...)");
1069 else if (kill(tcp->pid, 0) < 0) {
1071 perror("detach: checking sanity");
1073 else if (kill(tcp->pid, SIGSTOP) < 0) {
1075 perror("detach: stopping child");
1080 if (wait4(tcp->pid, &status, __WALL, NULL) < 0) {
1081 if (errno == ECHILD) /* Already gone. */
1083 if (errno != EINVAL) {
1084 perror("detach: waiting");
1088 /* No __WALL here. */
1089 if (waitpid(tcp->pid, &status, 0) < 0) {
1090 if (errno != ECHILD) {
1091 perror("detach: waiting");
1095 /* If no processes, try clones. */
1096 if (wait4(tcp->pid, &status, __WCLONE,
1098 if (errno != ECHILD)
1099 perror("detach: waiting");
1102 #endif /* __WCLONE */
1107 if (!WIFSTOPPED(status)) {
1108 /* Au revoir, mon ami. */
1111 if (WSTOPSIG(status) == SIGSTOP) {
1112 if ((error = ptrace(PTRACE_DETACH,
1113 tcp->pid, (char *) 1, sig)) < 0) {
1115 perror("detach: ptrace(PTRACE_DETACH, ...)");
1116 /* I died trying. */
1120 if ((error = ptrace(PTRACE_CONT, tcp->pid, (char *) 1,
1121 WSTOPSIG(status) == SIGTRAP ?
1122 0 : WSTOPSIG(status))) < 0) {
1124 perror("detach: ptrace(PTRACE_CONT, ...)");
1132 /* PTRACE_DETACH won't respect `sig' argument, so we post it here. */
1133 if (sig && kill(tcp->pid, sig) < 0)
1134 perror("detach: kill");
1136 if ((error = ptrace(PTRACE_DETACH, tcp->pid, (char *) 1, sig)) < 0)
1137 perror("detach: ptrace(PTRACE_DETACH, ...)");
1141 if (waiting_parent(tcp))
1142 error = resume(tcp->parent);
1143 #endif /* !USE_PROCFS */
1146 fprintf(stderr, "Process %u detached\n", tcp->pid);
1161 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
1172 #endif /* USE_PROCFS */
1180 for (i = 0; i < tcbtabsize; i++) {
1182 if (!(tcp->flags & TCB_INUSE))
1186 "cleanup: looking at pid %u\n", tcp->pid);
1188 (!outfname || followfork < 2 || tcp_last == tcp)) {
1189 tprintf(" <unfinished ...>\n");
1192 if (tcp->flags & TCB_ATTACHED)
1195 kill(tcp->pid, SIGCONT);
1196 kill(tcp->pid, SIGTERM);
1210 #ifndef HAVE_STRERROR
1212 #if !HAVE_DECL_SYS_ERRLIST
1213 extern int sys_nerr;
1214 extern char *sys_errlist[];
1215 #endif /* HAVE_DECL_SYS_ERRLIST */
1221 static char buf[64];
1223 if (errno < 1 || errno >= sys_nerr) {
1224 sprintf(buf, "Unknown error %d", errno);
1227 return sys_errlist[errno];
1230 #endif /* HAVE_STERRROR */
1232 #ifndef HAVE_STRSIGNAL
1234 #ifdef HAVE__SYS_SIGLIST
1235 #if !HAVE_DECL_SYS_SIGLIST
1236 extern char *sys_siglist[];
1237 extern char *_sys_siglist[];
1240 #endif /* SYS_SIGLIST_DECLARED */
1246 static char buf[64];
1248 if (sig < 1 || sig >= NSIG) {
1249 sprintf(buf, "Unknown signal %d", sig);
1252 #ifdef HAVE__SYS_SIGLIST
1253 return _sys_siglist[sig];
1255 return sys_siglist[sig];
1259 #endif /* HAVE_STRSIGNAL */
1271 pollv = (struct poll *) malloc(nprocs * sizeof pollv[0]);
1272 if (pollv == NULL) {
1273 fprintf(stderr, "strace: out of memory for poll vector\n");
1277 for (i = j = 0, tcp = tcbtab; i < tcbtabsize; i++, tcp++) {
1278 if (!(tcp->flags & TCB_INUSE))
1280 pollv[j].fd = tcp->pfd;
1281 pollv[j].events = POLLWANT;
1285 fprintf(stderr, "strace: proc miscount\n");
1290 #ifndef HAVE_POLLABLE_PROCFS
1298 if (pipe(proc_poll_pipe) < 0) {
1302 for (i = 0; i < 2; i++) {
1303 if ((arg = fcntl(proc_poll_pipe[i], F_GETFD)) < 0) {
1307 if (fcntl(proc_poll_pipe[i], F_SETFD, arg|FD_CLOEXEC) < 0) {
1315 proc_poll(pollv, nfds, timeout)
1316 struct pollfd *pollv;
1322 struct proc_pollfd pollinfo;
1324 if ((n = read(proc_poll_pipe[0], &pollinfo, sizeof(pollinfo))) < 0)
1326 if (n != sizeof(struct proc_pollfd)) {
1327 fprintf(stderr, "panic: short read: %d\n", n);
1330 for (i = 0; i < nprocs; i++) {
1331 if (pollv[i].fd == pollinfo.fd)
1332 pollv[i].revents = pollinfo.revents;
1334 pollv[i].revents = 0;
1336 poller_pid = pollinfo.pid;
1350 struct proc_pollfd pollinfo;
1351 struct sigaction sa;
1352 sigset_t blocked_set, empty_set;
1357 struct procfs_status pfs;
1358 #endif /* FREEBSD */
1370 sa.sa_handler = interactive ? SIG_DFL : SIG_IGN;
1372 sigemptyset(&sa.sa_mask);
1373 sigaction(SIGHUP, &sa, NULL);
1374 sigaction(SIGINT, &sa, NULL);
1375 sigaction(SIGQUIT, &sa, NULL);
1376 sigaction(SIGPIPE, &sa, NULL);
1377 sigaction(SIGTERM, &sa, NULL);
1378 sa.sa_handler = wakeup_handler;
1379 sigaction(SIGUSR1, &sa, NULL);
1380 sigemptyset(&blocked_set);
1381 sigaddset(&blocked_set, SIGUSR1);
1382 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
1383 sigemptyset(&empty_set);
1385 if (getrlimit(RLIMIT_NOFILE, &rl) < 0) {
1386 perror("getrlimit(RLIMIT_NOFILE, ...)");
1390 for (i = 0; i < n; i++) {
1391 if (i != pfd && i != proc_poll_pipe[1])
1396 pollinfo.pid = getpid();
1399 if (ioctl(pfd, PIOCWSTOP, NULL) < 0)
1401 if (ioctl(pfd, PIOCWSTOP, &pfs) < 0)
1402 #endif /* FREEBSD */
1408 pollinfo.revents = POLLERR;
1411 pollinfo.revents = POLLHUP;
1414 perror("proc_poller: PIOCWSTOP");
1416 write(proc_poll_pipe[1], &pollinfo, sizeof(pollinfo));
1419 pollinfo.revents = POLLWANT;
1420 write(proc_poll_pipe[1], &pollinfo, sizeof(pollinfo));
1421 sigsuspend(&empty_set);
1425 #endif /* !HAVE_POLLABLE_PROCFS */
1435 if (followfork < 2 &&
1436 last < nprocs && (pollv[last].revents & POLLWANT)) {
1438 * The previous process is ready to run again. We'll
1439 * let it do so if it is currently in a syscall. This
1440 * heuristic improves the readability of the trace.
1442 tcp = pfd2tcb(pollv[last].fd);
1443 if (tcp && (tcp->flags & TCB_INSYSCALL))
1444 return pollv[last].fd;
1447 for (i = 0; i < nprocs; i++) {
1448 /* Let competing children run round robin. */
1449 j = (i + last + 1) % nprocs;
1450 if (pollv[j].revents & (POLLHUP | POLLERR)) {
1451 tcp = pfd2tcb(pollv[j].fd);
1453 fprintf(stderr, "strace: lost proc\n");
1459 if (pollv[j].revents & POLLWANT) {
1464 fprintf(stderr, "strace: nothing ready\n");
1472 struct tcb *in_syscall = NULL;
1477 int ioctl_result = 0, ioctl_errno = 0;
1482 sigprocmask(SIG_SETMASK, &empty_set, NULL);
1489 #ifndef HAVE_POLLABLE_PROCFS
1490 if (proc_poll_pipe[0] == -1) {
1499 #ifndef HAVE_POLLABLE_PROCFS
1501 /* fall through ... */
1502 #endif /* !HAVE_POLLABLE_PROCFS */
1504 #ifdef HAVE_POLLABLE_PROCFS
1506 /* On some systems (e.g. UnixWare) we get too much ugly
1507 "unfinished..." stuff when multiple proceses are in
1508 syscalls. Here's a nasty hack */
1515 pv.events = POLLWANT;
1516 if ((what = poll (&pv, 1, 1)) < 0) {
1521 else if (what == 1 && pv.revents & POLLWANT) {
1527 if (poll(pollv, nprocs, INFTIM) < 0) {
1532 #else /* !HAVE_POLLABLE_PROCFS */
1533 if (proc_poll(pollv, nprocs, INFTIM) < 0) {
1538 #endif /* !HAVE_POLLABLE_PROCFS */
1545 /* Look up `pfd' in our table. */
1546 if ((tcp = pfd2tcb(pfd)) == NULL) {
1547 fprintf(stderr, "unknown pfd: %u\n", pfd);
1553 /* Get the status of the process. */
1556 ioctl_result = IOCTL_WSTOP (tcp);
1558 /* Thanks to some scheduling mystery, the first poller
1559 sometimes waits for the already processed end of fork
1560 event. Doing a non blocking poll here solves the problem. */
1561 if (proc_poll_pipe[0] != -1)
1562 ioctl_result = IOCTL_STATUS (tcp);
1564 ioctl_result = IOCTL_WSTOP (tcp);
1565 #endif /* FREEBSD */
1566 ioctl_errno = errno;
1567 #ifndef HAVE_POLLABLE_PROCFS
1568 if (proc_poll_pipe[0] != -1) {
1569 if (ioctl_result < 0)
1570 kill(poller_pid, SIGKILL);
1572 kill(poller_pid, SIGUSR1);
1574 #endif /* !HAVE_POLLABLE_PROCFS */
1580 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
1582 if (ioctl_result < 0) {
1583 /* Find out what happened if it failed. */
1584 switch (ioctl_errno) {
1595 perror("PIOCWSTOP");
1601 if ((tcp->flags & TCB_STARTUP) && (tcp->status.PR_WHY == PR_SYSEXIT)) {
1602 /* discard first event for a syscall we never entered */
1603 IOCTL (tcp->pfd, PIOCRUN, 0);
1608 /* clear the just started flag */
1609 tcp->flags &= ~TCB_STARTUP;
1611 /* set current output file */
1615 struct timeval stime;
1620 if ((len = pread(tcp->pfd_status, buf, sizeof(buf) - 1, 0)) > 0) {
1623 "%*s %*d %*d %*d %*d %*d,%*d %*s %*d,%*d %*d,%*d %ld,%ld",
1624 &stime.tv_sec, &stime.tv_usec);
1626 stime.tv_sec = stime.tv_usec = 0;
1627 #else /* !FREEBSD */
1628 stime.tv_sec = tcp->status.pr_stime.tv_sec;
1629 stime.tv_usec = tcp->status.pr_stime.tv_nsec/1000;
1630 #endif /* !FREEBSD */
1631 tv_sub(&tcp->dtime, &stime, &tcp->stime);
1634 what = tcp->status.PR_WHAT;
1635 switch (tcp->status.PR_WHY) {
1638 if (tcp->status.PR_FLAGS & PR_ASLEEP) {
1639 tcp->status.PR_WHY = PR_SYSENTRY;
1640 if (trace_syscall(tcp) < 0) {
1641 fprintf(stderr, "syscall trouble\n");
1646 #endif /* !FREEBSD */
1652 if (trace_syscall(tcp) < 0) {
1653 fprintf(stderr, "syscall trouble\n");
1658 if (!cflag && (qual_flags[what] & QUAL_SIGNAL)) {
1660 tprintf("--- %s (%s) ---",
1661 signame(what), strsignal(what));
1664 if (tcp->status.PR_INFO.si_signo == what) {
1666 tprintf(" siginfo=");
1667 printsiginfo(&tcp->status.PR_INFO, 1);
1674 if (!cflag && (qual_flags[what] & QUAL_FAULT)) {
1676 tprintf("=== FAULT %d ===", what);
1681 case 0: /* handle case we polled for nothing */
1685 fprintf(stderr, "odd stop %d\n", tcp->status.PR_WHY);
1691 if (IOCTL (tcp->pfd, PIOCRUN, &arg) < 0) {
1693 if (IOCTL (tcp->pfd, PIOCRUN, 0) < 0) {
1702 #else /* !USE_PROCFS */
1714 static int wait4_options = __WALL;
1718 while (nprocs != 0) {
1720 sigprocmask(SIG_SETMASK, &empty_set, NULL);
1723 pid = wait4(-1, &status, wait4_options, cflag ? &ru : NULL);
1724 if (pid < 0 && (wait4_options & __WALL) && errno == EINVAL) {
1725 /* this kernel does not support __WALL */
1726 wait4_options &= ~__WALL;
1728 pid = wait4(-1, &status, wait4_options,
1729 cflag ? &ru : NULL);
1731 if (pid < 0 && !(wait4_options & __WALL) && errno == ECHILD) {
1732 /* most likely a "cloned" process */
1733 pid = wait4(-1, &status, __WCLONE,
1734 cflag ? &ru : NULL);
1736 fprintf(stderr, "strace: clone wait4 "
1737 "failed: %s\n", strerror(errno));
1741 pid = wait4(-1, &status, 0, cflag ? &ru : NULL);
1745 pid = wait(&status);
1749 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
1755 switch (wait_errno) {
1760 * We would like to verify this case
1761 * but sometimes a race in Solbourne's
1762 * version of SunOS sometimes reports
1763 * ECHILD before sending us SIGCHILD.
1768 fprintf(stderr, "strace: proc miscount\n");
1774 perror("strace: wait");
1779 fprintf(stderr, " [wait(%#x) = %u]\n", status, pid);
1781 /* Look up `pid' in our table. */
1782 if ((tcp = pid2tcb(pid)) == NULL) {
1783 #if 0 /* XXX davidm */ /* WTA: disabled again */
1784 struct tcb *tcpchild;
1786 if ((tcpchild = alloctcb(pid)) == NULL) {
1787 fprintf(stderr, " [tcb table full]\n");
1788 kill(pid, SIGKILL); /* XXX */
1791 tcpchild->flags |= TCB_ATTACHED;
1795 fprintf(stderr, "Process %d attached\n", pid);
1797 fprintf(stderr, "unknown pid: %u\n", pid);
1798 if (WIFSTOPPED(status))
1799 ptrace(PTRACE_CONT, pid, (char *) 1, 0);
1803 /* set current output file */
1807 tv_sub(&tcp->dtime, &ru.ru_stime, &tcp->stime);
1808 tcp->stime = ru.ru_stime;
1812 if (tcp->flags & TCB_SUSPENDED) {
1814 * Apparently, doing any ptrace() call on a stopped
1815 * process, provokes the kernel to report the process
1816 * status again on a subsequent wait(), even if the
1817 * process has not been actually restarted.
1818 * Since we have inspected the arguments of suspended
1819 * processes we end up here testing for this case.
1823 if (WIFSIGNALED(status)) {
1825 && (qual_flags[WTERMSIG(status)] & QUAL_SIGNAL)) {
1827 tprintf("+++ killed by %s +++",
1828 signame(WTERMSIG(status)));
1834 if (WIFEXITED(status)) {
1836 fprintf(stderr, "pid %u exited\n", pid);
1837 if (tcp->flags & TCB_ATTACHED)
1839 "PANIC: attached pid %u exited\n",
1844 if (!WIFSTOPPED(status)) {
1845 fprintf(stderr, "PANIC: pid %u not stopped\n", pid);
1850 fprintf(stderr, "pid %u stopped, [%s]\n",
1851 pid, signame(WSTOPSIG(status)));
1853 if (tcp->flags & TCB_STARTUP) {
1855 * This flag is there to keep us in sync.
1856 * Next time this process stops it should
1857 * really be entering a system call.
1859 tcp->flags &= ~TCB_STARTUP;
1860 if (tcp->flags & TCB_ATTACHED) {
1862 * Interestingly, the process may stop
1863 * with STOPSIG equal to some other signal
1864 * than SIGSTOP if we happend to attach
1865 * just before the process takes a signal.
1867 if (!WIFSTOPPED(status)) {
1869 "pid %u not stopped\n", pid);
1870 detach(tcp, WSTOPSIG(status));
1876 /* A child of us stopped at exec */
1877 if (WSTOPSIG(status) == SIGTRAP && followvfork)
1881 if (tcp->flags & TCB_BPTSET) {
1882 if (clearbpt(tcp) < 0) /* Pretty fatal */ {
1891 if (WSTOPSIG(status) != SIGTRAP) {
1892 if (WSTOPSIG(status) == SIGSTOP &&
1893 (tcp->flags & TCB_SIGTRAPPED)) {
1895 * Trapped attempt to block SIGTRAP
1896 * Hope we are back in control now.
1898 tcp->flags &= ~(TCB_INSYSCALL | TCB_SIGTRAPPED);
1899 if (ptrace(PTRACE_SYSCALL,
1900 pid, (char *) 1, 0) < 0) {
1901 perror("trace: ptrace(PTRACE_SYSCALL, ...)");
1908 && (qual_flags[WSTOPSIG(status)] & QUAL_SIGNAL)) {
1909 unsigned long addr = 0, pc = 0;
1910 #ifdef PT_GETSIGINFO
1915 upeek(pid, PT_CR_IPSR, &psr);
1916 upeek(pid, PT_CR_IIP, &pc);
1918 pc += (psr >> PSR_RI) & 0x3;
1919 ptrace(PT_GETSIGINFO, pid, 0, (long) &si);
1920 addr = (unsigned long) si.si_addr;
1923 tprintf("--- %s (%s) @ %lx (%lx) ---",
1924 signame(WSTOPSIG(status)),
1925 strsignal(WSTOPSIG(status)), pc, addr);
1928 if ((tcp->flags & TCB_ATTACHED) &&
1929 !sigishandled(tcp, WSTOPSIG(status))) {
1930 detach(tcp, WSTOPSIG(status));
1933 if (ptrace(PTRACE_SYSCALL, pid, (char *) 1,
1934 WSTOPSIG(status)) < 0) {
1935 perror("trace: ptrace(PTRACE_SYSCALL, ...)");
1939 tcp->flags &= ~TCB_SUSPENDED;
1942 if (trace_syscall(tcp) < 0) {
1943 if (tcp->flags & TCB_ATTACHED)
1947 tcp->pid, (char *) 1, SIGTERM);
1952 if (tcp->flags & TCB_EXITING) {
1953 if (tcp->flags & TCB_ATTACHED)
1955 else if (ptrace(PTRACE_CONT, pid, (char *) 1, 0) < 0) {
1956 perror("strace: ptrace(PTRACE_CONT, ...)");
1962 if (tcp->flags & TCB_SUSPENDED) {
1964 fprintf(stderr, "Process %u suspended\n", pid);
1968 if (ptrace(PTRACE_SYSCALL, pid, (char *) 1, 0) < 0) {
1969 perror("trace: ptrace(PTRACE_SYSCALL, ...)");
1977 #endif /* !USE_PROCFS */
1983 #define VA_START(a, b) va_start(a, b)
1985 #include <varargs.h>
1986 #define VA_START(a, b) va_start(a)
1991 tprintf(const char *fmt, ...)
1993 tprintf(fmt, va_alist)
2000 VA_START(args, fmt);
2002 curcol += vfprintf(outf, fmt, args);
2011 if (tcp_last && (!outfname || followfork < 2 || tcp_last == tcp)) {
2012 tcp_last->flags |= TCB_REPRINT;
2013 tprintf(" <unfinished ...>\n");
2016 if ((followfork == 1 || pflag_seen > 1) && outfname)
2017 tprintf("%-5d ", tcp->pid);
2018 else if (nprocs > 1 && !outfname)
2019 tprintf("[pid %5u] ", tcp->pid);
2021 char str[sizeof("HH:MM:SS")];
2022 struct timeval tv, dtv;
2023 static struct timeval otv;
2025 gettimeofday(&tv, NULL);
2027 if (otv.tv_sec == 0)
2029 tv_sub(&dtv, &tv, &otv);
2030 tprintf("%6ld.%06ld ",
2031 (long) dtv.tv_sec, (long) dtv.tv_usec);
2034 else if (tflag > 2) {
2035 tprintf("%ld.%06ld ",
2036 (long) tv.tv_sec, (long) tv.tv_usec);
2039 time_t local = tv.tv_sec;
2040 strftime(str, sizeof(str), "%T", localtime(&local));
2042 tprintf("%s.%06ld ", str, (long) tv.tv_usec);
2044 tprintf("%s ", str);
2056 tprintf("%*s", col - curcol, "");
2067 #ifdef HAVE_MP_PROCFS
2069 int mp_ioctl (int fd, int cmd, void *arg, int size) {
2071 struct iovec iov[2];
2074 iov[0].iov_base = &cmd;
2075 iov[0].iov_len = sizeof cmd;
2078 iov[1].iov_base = arg;
2079 iov[1].iov_len = size;
2082 return writev (fd, iov, n);