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>
81 int debug = 0, followfork = 0;
82 int dtime = 0, cflag = 0, xflag = 0, qflag = 0;
83 static int iflag = 0, interactive = 0, pflag_seen = 0, rflag = 0, tflag = 0;
85 /* Sometimes we want to print only succeeding syscalls. */
86 int not_failing_only = 0;
88 static int exit_code = 0;
89 static int strace_child = 0;
91 static char *username = NULL;
95 int acolumn = DEFAULT_ACOLUMN;
96 int max_strlen = DEFAULT_STRLEN;
97 static char *outfname = NULL;
100 unsigned int nprocs, tcbtabsize;
102 extern char **environ;
104 static int detach P((struct tcb *tcp, int sig));
105 static int trace P((void));
106 static void cleanup P((void));
107 static void interrupt P((int sig));
108 static sigset_t empty_set, blocked_set;
110 #ifdef HAVE_SIG_ATOMIC_T
111 static volatile sig_atomic_t interrupted;
112 #else /* !HAVE_SIG_ATOMIC_T */
114 static volatile int interrupted;
115 #else /* !__STDC__ */
116 static int interrupted;
117 #endif /* !__STDC__ */
118 #endif /* !HAVE_SIG_ATOMIC_T */
122 static struct tcb *pfd2tcb P((int pfd));
123 static void reaper P((int sig));
124 static void rebuild_pollv P((void));
125 static struct pollfd *pollv;
127 #ifndef HAVE_POLLABLE_PROCFS
129 static void proc_poll_open P((void));
130 static void proc_poller P((int pfd));
138 static int poller_pid;
139 static int proc_poll_pipe[2] = { -1, -1 };
141 #endif /* !HAVE_POLLABLE_PROCFS */
143 #ifdef HAVE_MP_PROCFS
144 #define POLLWANT POLLWRNORM
146 #define POLLWANT POLLPRI
148 #endif /* USE_PROCFS */
156 usage: strace [-dffhiqrtttTvVxx] [-a column] [-e expr] ... [-o file]\n\
157 [-p pid] ... [-s strsize] [-u username] [-E var=val] ...\n\
158 [command [arg ...]]\n\
159 or: strace -c [-e expr] ... [-O overhead] [-S sortby] [-E var=val] ...\n\
160 [command [arg ...]]\n\
161 -c -- count time, calls, and errors for each syscall and report summary\n\
162 -f -- follow forks, -ff -- with output into separate files\n\
163 -F -- attempt to follow vforks, -h -- print help message\n\
164 -i -- print instruction pointer at time of syscall\n\
165 -q -- suppress messages about attaching, detaching, etc.\n\
166 -r -- print relative timestamp, -t -- absolute timestamp, -tt -- with usecs\n\
167 -T -- print time spent in each syscall, -V -- print version\n\
168 -v -- verbose mode: print unabbreviated argv, stat, termio[s], etc. args\n\
169 -x -- print non-ascii strings in hex, -xx -- print all strings in hex\n\
170 -a column -- alignment COLUMN for printing syscall results (default %d)\n\
171 -e expr -- a qualifying expression: option=[!]all or option=[!]val1[,val2]...\n\
172 options: trace, abbrev, verbose, raw, signal, read, or write\n\
173 -o file -- send trace output to FILE instead of stderr\n\
174 -O overhead -- set overhead for tracing syscalls to OVERHEAD usecs\n\
175 -p pid -- trace process with process id PID, may be repeated\n\
176 -s strsize -- limit length of print strings to STRSIZE chars (default %d)\n\
177 -S sortby -- sort syscall counts by: time, calls, name, nothing (default %s)\n\
178 -u username -- run command as username handling setuid and/or setgid\n\
179 -E var=val -- put var=val in the environment for command\n\
180 -E var -- remove var from the environment for command\n\
181 " /* this is broken, so don't document it
182 -z -- print only succeeding syscalls\n\
184 , DEFAULT_ACOLUMN, DEFAULT_STRLEN, DEFAULT_SORTBY);
198 set_cloexec_flag(int fd)
202 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
204 fprintf(stderr, "%s: fcntl F_GETFD: %s\n",
205 progname, strerror(errno));
209 newflags = flags | FD_CLOEXEC;
210 if (flags == newflags)
213 if (fcntl(fd, F_SETFD, newflags) < 0)
215 fprintf(stderr, "%s: fcntl F_SETFD: %s\n",
216 progname, strerror(errno));
224 * When strace is setuid executable, we have to swap uids
225 * before and after filesystem and process management operations.
231 int euid = geteuid(), uid = getuid();
233 if (euid != uid && setreuid(euid, uid) < 0)
235 fprintf(stderr, "%s: setreuid: %s\n",
236 progname, strerror(errno));
243 # define fopen_for_output fopen64
245 # define fopen_for_output fopen
249 strace_fopen(const char *path, const char *mode)
254 if ((fp = fopen_for_output(path, mode)) == NULL)
255 fprintf(stderr, "%s: can't fopen '%s': %s\n",
256 progname, path, strerror(errno));
258 if (fp && set_cloexec_flag(fileno(fp)) < 0)
266 static int popen_pid = -1;
269 # define _PATH_BSHELL "/bin/sh"
273 * We cannot use standard popen(3) here because we have to distinguish
274 * popen child process from other processes we trace, and standard popen(3)
275 * does not export its child's pid.
278 strace_popen(const char *command)
285 fprintf(stderr, "%s: pipe: %s\n",
286 progname, strerror(errno));
291 if (set_cloexec_flag(fds[1]) < 0)
299 if ((popen_pid = fork()) == -1)
301 fprintf(stderr, "%s: fork: %s\n",
302 progname, strerror(errno));
314 return fdopen(fds[1], "w");
319 if (fds[0] && (dup2(fds[0], 0) || close(fds[0])))
321 fprintf(stderr, "%s: dup2: %s\n",
322 progname, strerror(errno));
325 execl(_PATH_BSHELL, "sh", "-c", command, NULL);
326 fprintf(stderr, "%s: execl: %s: %s\n",
327 progname, _PATH_BSHELL, strerror(errno));
333 newoutf(struct tcb *tcp)
335 if (outfname && followfork > 1) {
336 char name[MAXPATHLEN];
339 sprintf(name, "%s.%u", outfname, tcp->pid);
340 if ((fp = strace_fopen(name, "w")) == NULL)
354 * Block user interruptions as we would leave the traced
355 * process stopped (process state T) if we would terminate in
356 * between PTRACE_ATTACH and wait4 () on SIGSTOP.
357 * We rely on cleanup () from this point on.
360 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
362 for (tcbi = 0; tcbi < tcbtabsize; tcbi++) {
364 if (!(tcp->flags & TCB_INUSE) || !(tcp->flags & TCB_ATTACHED))
367 if (tcp->flags & TCB_CLONE_THREAD)
370 /* Reinitialize the output since it may have changed. */
372 if (newoutf(tcp) < 0)
376 if (proc_open(tcp, 1) < 0) {
377 fprintf(stderr, "trouble opening proc file\n");
381 #else /* !USE_PROCFS */
384 char procdir[MAXPATHLEN];
387 sprintf(procdir, "/proc/%d/task", tcp->pid);
388 dir = opendir(procdir);
390 unsigned int ntid = 0, nerr = 0;
393 while ((de = readdir(dir)) != NULL) {
394 if (de->d_fileno == 0 ||
395 de->d_name[0] == '.')
397 tid = atoi(de->d_name);
401 if (ptrace(PTRACE_ATTACH, tid,
404 else if (tid != tcbtab[tcbi]->pid) {
405 if (nprocs == tcbtabsize &&
412 tcp->flags |= TCB_ATTACHED|TCB_CLONE_THREAD|TCB_CLONE_DETACHED|TCB_FOLLOWFORK;
413 tcbtab[tcbi]->nchildren++;
414 tcbtab[tcbi]->nclone_threads++;
415 tcbtab[tcbi]->nclone_detached++;
416 tcp->parent = tcbtab[tcbi];
419 sigprocmask(SIG_SETMASK, &empty_set, NULL);
422 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
427 perror("attach: ptrace(PTRACE_ATTACH, ...)");
435 Process %u attached with %u threads - interrupt to quit\n",
439 Process %u attached - interrupt to quit\n",
446 if (ptrace(PTRACE_ATTACH, tcp->pid, (char *) 1, 0) < 0) {
447 perror("attach: ptrace(PTRACE_ATTACH, ...)");
451 /* INTERRUPTED is going to be checked at the top of TRACE. */
452 #endif /* !USE_PROCFS */
455 "Process %u attached - interrupt to quit\n",
460 sigprocmask(SIG_SETMASK, &empty_set, NULL);
464 startup_child (char **argv)
467 const char *filename;
468 char pathname[MAXPATHLEN];
473 if (strchr(filename, '/')) {
474 if (strlen(filename) > sizeof pathname - 1) {
475 errno = ENAMETOOLONG;
476 perror("strace: exec");
479 strcpy(pathname, filename);
481 #ifdef USE_DEBUGGING_EXEC
483 * Debuggers customarily check the current directory
484 * first regardless of the path but doing that gives
485 * security geeks a panic attack.
487 else if (stat(filename, &statbuf) == 0)
488 strcpy(pathname, filename);
489 #endif /* USE_DEBUGGING_EXEC */
494 for (path = getenv("PATH"); path && *path; path += m) {
495 if (strchr(path, ':')) {
496 n = strchr(path, ':') - path;
500 m = n = strlen(path);
502 if (!getcwd(pathname, MAXPATHLEN))
504 len = strlen(pathname);
506 else if (n > sizeof pathname - 1)
509 strncpy(pathname, path, n);
512 if (len && pathname[len - 1] != '/')
513 pathname[len++] = '/';
514 strcpy(pathname + len, filename);
515 if (stat(pathname, &statbuf) == 0 &&
516 /* Accept only regular files
517 with some execute bits set.
518 XXX not perfect, might still fail */
519 S_ISREG(statbuf.st_mode) &&
520 (statbuf.st_mode & 0111))
524 if (stat(pathname, &statbuf) < 0) {
525 fprintf(stderr, "%s: %s: command not found\n",
529 strace_child = pid = fork();
532 perror("strace: fork");
538 if (outf != stderr) close (fileno (outf));
540 /* Kludge for SGI, see proc_open for details. */
541 sa.sa_handler = foobar;
543 sigemptyset(&sa.sa_mask);
544 sigaction(SIGINT, &sa, NULL);
549 kill(getpid(), SIGSTOP); /* stop HERE */
551 #else /* !USE_PROCFS */
553 close(fileno (outf));
555 if (ptrace(PTRACE_TRACEME, 0, (char *) 1, 0) < 0) {
556 perror("strace: ptrace(PTRACE_TRACEME, ...)");
560 kill(getpid(), SIGSTOP);
562 if (username != NULL || geteuid() == 0) {
563 uid_t run_euid = run_uid;
564 gid_t run_egid = run_gid;
566 if (statbuf.st_mode & S_ISUID)
567 run_euid = statbuf.st_uid;
568 if (statbuf.st_mode & S_ISGID)
569 run_egid = statbuf.st_gid;
572 * It is important to set groups before we
573 * lose privileges on setuid.
575 if (username != NULL) {
576 if (initgroups(username, run_gid) < 0) {
577 perror("initgroups");
580 if (setregid(run_gid, run_egid) < 0) {
584 if (setreuid(run_uid, run_euid) < 0) {
591 setreuid(run_uid, run_uid);
594 * Induce an immediate stop so that the parent
595 * will resume us with PTRACE_SYSCALL and display
596 * this execve call normally.
598 kill(getpid(), SIGSTOP);
599 #endif /* !USE_PROCFS */
601 execv(pathname, argv);
602 perror("strace: exec");
607 if ((tcp = alloctcb(pid)) == NULL) {
612 if (proc_open(tcp, 0) < 0) {
613 fprintf(stderr, "trouble opening proc file\n");
617 #endif /* USE_PROCFS */
623 main(int argc, char *argv[])
632 static char buf[BUFSIZ];
634 progname = argv[0] ? argv[0] : "strace";
636 /* Allocate the initial tcbtab. */
637 tcbtabsize = argc; /* Surely enough for all -p args. */
638 if ((tcbtab = calloc (tcbtabsize, sizeof tcbtab[0])) == NULL) {
639 fprintf(stderr, "%s: out of memory\n", progname);
642 if ((tcbtab[0] = calloc (tcbtabsize, sizeof tcbtab[0][0])) == NULL) {
643 fprintf(stderr, "%s: out of memory\n", progname);
646 for (tcp = tcbtab[0]; tcp < &tcbtab[0][tcbtabsize]; ++tcp)
647 tcbtab[tcp - tcbtab[0]] = &tcbtab[0][tcp - tcbtab[0]];
651 set_sortby(DEFAULT_SORTBY);
652 set_personality(DEFAULT_PERSONALITY);
653 qualify("trace=all");
654 qualify("abbrev=all");
655 qualify("verbose=all");
656 qualify("signal=all");
657 while ((c = getopt(argc, argv,
658 "+cdfFhiqrtTvVxza:e:o:O:p:s:S:u:E:")) != EOF) {
696 qualify("abbrev=none");
699 printf("%s -- version %s\n", PACKAGE_NAME, VERSION);
703 not_failing_only = 1;
706 acolumn = atoi(optarg);
712 outfname = strdup(optarg);
715 set_overhead(atoi(optarg));
718 if ((pid = atoi(optarg)) <= 0) {
719 fprintf(stderr, "%s: Invalid process id: %s\n",
723 if (pid == getpid()) {
724 fprintf(stderr, "%s: I'm sorry, I can't let you do that, Dave.\n", progname);
727 if ((tcp = alloc_tcb(pid, 0)) == NULL) {
728 fprintf(stderr, "%s: out of memory\n",
732 tcp->flags |= TCB_ATTACHED;
736 max_strlen = atoi(optarg);
737 if (max_strlen < 0) {
739 "%s: invalid -s argument: %s\n",
748 username = strdup(optarg);
751 if (putenv(optarg) < 0) {
752 fprintf(stderr, "%s: out of memory\n",
763 if ((optind == argc) == !pflag_seen)
769 if (followfork > 1 && cflag) {
771 "%s: -c and -ff are mutually exclusive options\n",
776 /* See if they want to run as another user. */
777 if (username != NULL) {
780 if (getuid() != 0 || geteuid() != 0) {
782 "%s: you must be root to use the -u option\n",
786 if ((pent = getpwnam(username)) == NULL) {
787 fprintf(stderr, "%s: cannot find user `%s'\n",
791 run_uid = pent->pw_uid;
792 run_gid = pent->pw_gid;
799 /* Check if they want to redirect the output. */
801 /* See if they want to pipe the output. */
802 if (outfname[0] == '|' || outfname[0] == '!') {
804 * We can't do the <outfname>.PID funny business
805 * when using popen, so prohibit it.
807 if (followfork > 1) {
809 %s: piping the output and -ff are mutually exclusive options\n",
814 if ((outf = strace_popen(outfname + 1)) == NULL)
817 else if (followfork <= 1 &&
818 (outf = strace_fopen(outfname, "w")) == NULL)
822 if (!outfname || outfname[0] == '|' || outfname[0] == '!')
823 setvbuf(outf, buf, _IOLBF, BUFSIZ);
824 if (outfname && optind < argc) {
828 /* Valid states here:
829 optind < argc pflag_seen outfname interactive
836 /* STARTUP_CHILD must be called before the signal handlers get
837 installed below as they are inherited into the spawned process.
838 Also we do not need to be protected by them as during interruption
839 in the STARTUP_CHILD mode we kill the spawned process anyway. */
841 startup_child(&argv[optind]);
843 sigemptyset(&empty_set);
844 sigemptyset(&blocked_set);
845 sa.sa_handler = SIG_IGN;
846 sigemptyset(&sa.sa_mask);
848 sigaction(SIGTTOU, &sa, NULL);
849 sigaction(SIGTTIN, &sa, NULL);
851 sigaddset(&blocked_set, SIGHUP);
852 sigaddset(&blocked_set, SIGINT);
853 sigaddset(&blocked_set, SIGQUIT);
854 sigaddset(&blocked_set, SIGPIPE);
855 sigaddset(&blocked_set, SIGTERM);
856 sa.sa_handler = interrupt;
858 /* POSIX signals on sunos4.1 are a little broken. */
859 sa.sa_flags = SA_INTERRUPT;
862 sigaction(SIGHUP, &sa, NULL);
863 sigaction(SIGINT, &sa, NULL);
864 sigaction(SIGQUIT, &sa, NULL);
865 sigaction(SIGPIPE, &sa, NULL);
866 sigaction(SIGTERM, &sa, NULL);
868 sa.sa_handler = reaper;
869 sigaction(SIGCHLD, &sa, NULL);
871 /* Make sure SIGCHLD has the default action so that waitpid
872 definitely works without losing track of children. The user
873 should not have given us a bogus state to inherit, but he might
874 have. Arguably we should detect SIG_IGN here and pass it on
875 to children, but probably noone really needs that. */
876 sa.sa_handler = SIG_DFL;
877 sigaction(SIGCHLD, &sa, NULL);
878 #endif /* USE_PROCFS */
887 if (exit_code > 0xff) {
888 /* Child was killed by a signal, mimic that. */
890 signal(exit_code, SIG_DFL);
892 /* Paranoia - what if this signal is not fatal?
893 Exit with 128 + signo then. */
902 /* Allocate some more TCBs and expand the table.
903 We don't want to relocate the TCBs because our
904 callers have pointers and it would be a pain.
905 So tcbtab is a table of pointers. Since we never
906 free the TCBs, we allocate a single chunk of many. */
907 struct tcb **newtab = (struct tcb **)
908 realloc(tcbtab, 2 * tcbtabsize * sizeof tcbtab[0]);
909 struct tcb *newtcbs = (struct tcb *) calloc(tcbtabsize,
912 if (newtab == NULL || newtcbs == NULL) {
915 fprintf(stderr, "%s: expand_tcbtab: out of memory\n",
919 for (i = tcbtabsize; i < 2 * tcbtabsize; ++i)
920 newtab[i] = &newtcbs[i - tcbtabsize];
929 alloc_tcb(int pid, int command_options_parsed)
934 for (i = 0; i < tcbtabsize; i++) {
936 if ((tcp->flags & TCB_INUSE) == 0) {
941 #ifdef TCB_CLONE_THREAD
942 tcp->nclone_threads = tcp->nclone_detached = 0;
943 tcp->nclone_waiting = 0;
945 tcp->flags = TCB_INUSE | TCB_STARTUP;
946 tcp->outf = outf; /* Initialise to current out file */
947 tcp->stime.tv_sec = 0;
948 tcp->stime.tv_usec = 0;
951 if (command_options_parsed)
956 fprintf(stderr, "%s: alloc_tcb: tcb table full\n", progname);
962 proc_open(tcp, attaching)
974 #ifndef HAVE_POLLABLE_PROCFS
978 #ifdef HAVE_MP_PROCFS
979 /* Open the process pseudo-files in /proc. */
980 sprintf(proc, "/proc/%d/ctl", tcp->pid);
981 if ((tcp->pfd = open(proc, O_WRONLY|O_EXCL)) < 0) {
982 perror("strace: open(\"/proc/...\", ...)");
985 if (set_cloexec_flag(tcp->pfd) < 0) {
988 sprintf(proc, "/proc/%d/status", tcp->pid);
989 if ((tcp->pfd_stat = open(proc, O_RDONLY|O_EXCL)) < 0) {
990 perror("strace: open(\"/proc/...\", ...)");
993 if (set_cloexec_flag(tcp->pfd_stat) < 0) {
996 sprintf(proc, "/proc/%d/as", tcp->pid);
997 if ((tcp->pfd_as = open(proc, O_RDONLY|O_EXCL)) < 0) {
998 perror("strace: open(\"/proc/...\", ...)");
1001 if (set_cloexec_flag(tcp->pfd_as) < 0) {
1005 /* Open the process pseudo-file in /proc. */
1007 sprintf(proc, "/proc/%d", tcp->pid);
1008 if ((tcp->pfd = open(proc, O_RDWR|O_EXCL)) < 0) {
1010 sprintf(proc, "/proc/%d/mem", tcp->pid);
1011 if ((tcp->pfd = open(proc, O_RDWR)) < 0) {
1012 #endif /* FREEBSD */
1013 perror("strace: open(\"/proc/...\", ...)");
1016 if (set_cloexec_flag(tcp->pfd) < 0) {
1021 sprintf(proc, "/proc/%d/regs", tcp->pid);
1022 if ((tcp->pfd_reg = open(proc, O_RDONLY)) < 0) {
1023 perror("strace: open(\"/proc/.../regs\", ...)");
1027 sprintf(proc, "/proc/%d/status", tcp->pid);
1028 if ((tcp->pfd_status = open(proc, O_RDONLY)) < 0) {
1029 perror("strace: open(\"/proc/.../status\", ...)");
1033 tcp->pfd_status = -1;
1034 #endif /* FREEBSD */
1038 * Wait for the child to pause. Because of a race
1039 * condition we have to poll for the event.
1042 if (IOCTL_STATUS (tcp) < 0) {
1043 perror("strace: PIOCSTATUS");
1046 if (tcp->status.PR_FLAGS & PR_ASLEEP)
1051 /* Stop the process so that we own the stop. */
1052 if (IOCTL(tcp->pfd, PIOCSTOP, (char *)NULL) < 0) {
1053 perror("strace: PIOCSTOP");
1058 /* Set Run-on-Last-Close. */
1060 if (IOCTL(tcp->pfd, PIOCSET, &arg) < 0) {
1061 perror("PIOCSET PR_RLC");
1064 /* Set or Reset Inherit-on-Fork. */
1066 if (IOCTL(tcp->pfd, followfork ? PIOCSET : PIOCRESET, &arg) < 0) {
1067 perror("PIOC{SET,RESET} PR_FORK");
1070 #else /* !PIOCSET */
1072 if (ioctl(tcp->pfd, PIOCSRLC) < 0) {
1076 if (ioctl(tcp->pfd, followfork ? PIOCSFORK : PIOCRFORK) < 0) {
1077 perror("PIOC{S,R}FORK");
1081 /* just unset the PF_LINGER flag for the Run-on-Last-Close. */
1082 if (ioctl(tcp->pfd, PIOCGFL, &arg) < 0) {
1087 if (ioctl(tcp->pfd, PIOCSFL, arg) < 0) {
1091 #endif /* FREEBSD */
1092 #endif /* !PIOCSET */
1094 /* Enable all syscall entries we care about. */
1095 premptyset(&syscalls);
1096 for (i = 1; i < MAX_QUALS; ++i) {
1097 if (i > (sizeof syscalls) * CHAR_BIT) break;
1098 if (qual_flags [i] & QUAL_TRACE) praddset (&syscalls, i);
1100 praddset (&syscalls, SYS_execve);
1102 praddset (&syscalls, SYS_fork);
1104 praddset (&syscalls, SYS_forkall);
1107 praddset (&syscalls, SYS_fork1);
1110 praddset (&syscalls, SYS_rfork1);
1113 praddset (&syscalls, SYS_rforkall);
1116 if (IOCTL(tcp->pfd, PIOCSENTRY, &syscalls) < 0) {
1117 perror("PIOCSENTRY");
1120 /* Enable the syscall exits. */
1121 if (IOCTL(tcp->pfd, PIOCSEXIT, &syscalls) < 0) {
1125 /* Enable signals we care about. */
1126 premptyset(&signals);
1127 for (i = 1; i < MAX_QUALS; ++i) {
1128 if (i > (sizeof signals) * CHAR_BIT) break;
1129 if (qual_flags [i] & QUAL_SIGNAL) praddset (&signals, i);
1131 if (IOCTL(tcp->pfd, PIOCSTRACE, &signals) < 0) {
1132 perror("PIOCSTRACE");
1135 /* Enable faults we care about */
1136 premptyset(&faults);
1137 for (i = 1; i < MAX_QUALS; ++i) {
1138 if (i > (sizeof faults) * CHAR_BIT) break;
1139 if (qual_flags [i] & QUAL_FAULT) praddset (&faults, i);
1141 if (IOCTL(tcp->pfd, PIOCSFAULT, &faults) < 0) {
1142 perror("PIOCSFAULT");
1146 /* set events flags. */
1147 arg = S_SIG | S_SCE | S_SCX ;
1148 if(ioctl(tcp->pfd, PIOCBIS, arg) < 0) {
1152 #endif /* FREEBSD */
1156 * The SGI PRSABORT doesn't work for pause() so
1157 * we send it a caught signal to wake it up.
1159 kill(tcp->pid, SIGINT);
1162 /* The child is in a pause(), abort it. */
1164 if (IOCTL (tcp->pfd, PIOCRUN, &arg) < 0) {
1171 /* wake up the child if it received the SIGSTOP */
1172 kill(tcp->pid, SIGCONT);
1175 /* Wait for the child to do something. */
1176 if (IOCTL_WSTOP (tcp) < 0) {
1177 perror("PIOCWSTOP");
1180 if (tcp->status.PR_WHY == PR_SYSENTRY) {
1181 tcp->flags &= ~TCB_INSYSCALL;
1183 if (known_scno(tcp) == SYS_execve)
1186 /* Set it running: maybe execve will be next. */
1189 if (IOCTL(tcp->pfd, PIOCRUN, &arg) < 0) {
1191 if (IOCTL(tcp->pfd, PIOCRUN, 0) < 0) {
1192 #endif /* FREEBSD */
1197 /* handle the case where we "opened" the child before
1198 it did the kill -STOP */
1199 if (tcp->status.PR_WHY == PR_SIGNALLED &&
1200 tcp->status.PR_WHAT == SIGSTOP)
1201 kill(tcp->pid, SIGCONT);
1208 if (attaching < 2) {
1209 /* We are attaching to an already running process.
1210 * Try to figure out the state of the process in syscalls,
1211 * to handle the first event well.
1212 * This is done by having a look at the "wchan" property of the
1213 * process, which tells where it is stopped (if it is). */
1215 char wchan[20]; /* should be enough */
1217 sprintf(proc, "/proc/%d/status", tcp->pid);
1218 status = fopen(proc, "r");
1220 (fscanf(status, "%*s %*d %*d %*d %*d %*d,%*d %*s %*d,%*d"
1221 "%*d,%*d %*d,%*d %19s", wchan) == 1) &&
1222 strcmp(wchan, "nochan") && strcmp(wchan, "spread") &&
1223 strcmp(wchan, "stopevent")) {
1224 /* The process is asleep in the middle of a syscall.
1225 Fake the syscall entry event */
1226 tcp->flags &= ~(TCB_INSYSCALL|TCB_STARTUP);
1227 tcp->status.PR_WHY = PR_SYSENTRY;
1232 } /* otherwise it's a fork being followed */
1234 #endif /* FREEBSD */
1235 #ifndef HAVE_POLLABLE_PROCFS
1236 if (proc_poll_pipe[0] != -1)
1237 proc_poller(tcp->pfd);
1238 else if (nprocs > 1) {
1240 proc_poller(last_pfd);
1241 proc_poller(tcp->pfd);
1243 last_pfd = tcp->pfd;
1244 #endif /* !HAVE_POLLABLE_PROCFS */
1248 #endif /* USE_PROCFS */
1257 for (i = 0; i < tcbtabsize; i++) {
1259 if (pid && tcp->pid != pid)
1261 if (tcp->flags & TCB_INUSE)
1275 for (i = 0; i < tcbtabsize; i++) {
1276 struct tcb *tcp = tcbtab[i];
1277 if (tcp->pfd != pfd)
1279 if (tcp->flags & TCB_INUSE)
1285 #endif /* USE_PROCFS */
1293 #ifdef TCB_CLONE_THREAD
1294 if (tcp->nclone_threads > 0) {
1295 /* There are other threads left in this process, but this
1296 is the one whose PID represents the whole process.
1297 We need to keep this record around as a zombie until
1298 all the threads die. */
1299 tcp->flags |= TCB_EXITING;
1306 if (tcp->parent != NULL) {
1307 tcp->parent->nchildren--;
1308 #ifdef TCB_CLONE_THREAD
1309 if (tcp->flags & TCB_CLONE_DETACHED)
1310 tcp->parent->nclone_detached--;
1311 if (tcp->flags & TCB_CLONE_THREAD)
1312 tcp->parent->nclone_threads--;
1314 #ifdef TCB_CLONE_DETACHED
1315 if (!(tcp->flags & TCB_CLONE_DETACHED))
1317 tcp->parent->nzombies++;
1319 /* Update `tcp->parent->parent->nchildren' and the other fields
1320 like NCLONE_DETACHED, only for zombie group leader that has
1321 already reported and been short-circuited at the top of this
1322 function. The same condition as at the top of DETACH. */
1323 if ((tcp->flags & TCB_CLONE_THREAD) &&
1324 tcp->parent->nclone_threads == 0 &&
1325 (tcp->parent->flags & TCB_EXITING))
1326 droptcb(tcp->parent);
1332 if (tcp->pfd != -1) {
1336 if (tcp->pfd_reg != -1) {
1337 close(tcp->pfd_reg);
1340 if (tcp->pfd_status != -1) {
1341 close(tcp->pfd_status);
1342 tcp->pfd_status = -1;
1344 #endif /* !FREEBSD */
1346 rebuild_pollv(); /* Note, flags needs to be cleared by now. */
1350 if (outfname && followfork > 1 && tcp->outf)
1365 if (!(tcp->flags & TCB_SUSPENDED)) {
1366 fprintf(stderr, "PANIC: pid %u not suspended\n", tcp->pid);
1369 tcp->flags &= ~TCB_SUSPENDED;
1370 #ifdef TCB_CLONE_THREAD
1371 if (tcp->flags & TCB_CLONE_THREAD)
1372 tcp->parent->nclone_waiting--;
1375 if (ptrace_restart(PTRACE_SYSCALL, tcp, 0) < 0)
1379 fprintf(stderr, "Process %u resumed\n", tcp->pid);
1384 resume_from_tcp (struct tcb *tcp)
1389 /* XXX This won't always be quite right (but it never was).
1390 A waiter with argument 0 or < -1 is waiting for any pid in
1391 a particular pgrp, which this child might or might not be
1392 in. The waiter will only wake up if it's argument is -1
1393 or if it's waiting for tcp->pid's pgrp. It makes a
1394 difference to wake up a waiter when there might be more
1395 traced children, because it could get a false ECHILD
1396 error. OTOH, if this was the last child in the pgrp, then
1397 it ought to wake up and get ECHILD. We would have to
1398 search the system for all pid's in the pgrp to be sure.
1400 && (t->waitpid == -1 ||
1401 (t->waitpid == 0 && getpgid (tcp->pid) == getpgid (t->pid))
1402 || (t->waitpid < 0 && t->waitpid == -getpid (t->pid)))
1406 (tcp->parent->flags & TCB_SUSPENDED) &&
1407 (tcp->parent->waitpid <= 0 || tcp->parent->waitpid == tcp->pid)) {
1408 error = resume(tcp->parent);
1411 #ifdef TCB_CLONE_THREAD
1412 if (tcp->parent && tcp->parent->nclone_waiting > 0) {
1413 /* Some other threads of our parent are waiting too. */
1416 /* Resume all the threads that were waiting for this PID. */
1417 for (i = 0; i < tcbtabsize; i++) {
1418 struct tcb *t = tcbtab[i];
1419 if (t->parent == tcp->parent && t != tcp
1420 && ((t->flags & (TCB_CLONE_THREAD|TCB_SUSPENDED))
1421 == (TCB_CLONE_THREAD|TCB_SUSPENDED))
1422 && t->waitpid == tcp->pid) {
1423 error |= resume (t);
1428 /* Noone was waiting for this PID in particular,
1429 so now we might need to resume some wildcarders. */
1430 for (i = 0; i < tcbtabsize; i++) {
1431 struct tcb *t = tcbtab[i];
1432 if (t->parent == tcp->parent && t != tcp
1434 & (TCB_CLONE_THREAD|TCB_SUSPENDED))
1435 == (TCB_CLONE_THREAD|TCB_SUSPENDED))
1438 error |= resume (t);
1448 #endif /* !USE_PROCFS */
1450 /* detach traced process; continue with sig
1451 Never call DETACH twice on the same process as both unattached and
1452 attached-unstopped processes give the same ESRCH. For unattached process we
1453 would SIGSTOP it and wait for its SIGSTOP notification forever. */
1462 int status, catch_sigstop;
1463 struct tcb *zombie = NULL;
1465 /* If the group leader is lingering only because of this other
1466 thread now dying, then detach the leader as well. */
1467 if ((tcp->flags & TCB_CLONE_THREAD) &&
1468 tcp->parent->nclone_threads == 1 &&
1469 (tcp->parent->flags & TCB_EXITING))
1470 zombie = tcp->parent;
1473 if (tcp->flags & TCB_BPTSET)
1478 * Linux wrongly insists the child be stopped
1479 * before detaching. Arghh. We go through hoops
1480 * to make a clean break of things.
1483 #undef PTRACE_DETACH
1484 #define PTRACE_DETACH PTRACE_SUNDETACH
1487 * On TCB_STARTUP we did PTRACE_ATTACH but still did not get the
1488 * expected SIGSTOP. We must catch exactly one as otherwise the
1489 * detached process would be left stopped (process state T).
1491 catch_sigstop = (tcp->flags & TCB_STARTUP);
1492 if ((error = ptrace(PTRACE_DETACH, tcp->pid, (char *) 1, sig)) == 0) {
1493 /* On a clear day, you can see forever. */
1495 else if (errno != ESRCH) {
1496 /* Shouldn't happen. */
1497 perror("detach: ptrace(PTRACE_DETACH, ...)");
1499 else if (my_tgkill((tcp->flags & TCB_CLONE_THREAD ? tcp->parent->pid
1503 perror("detach: checking sanity");
1505 else if (!catch_sigstop && my_tgkill((tcp->flags & TCB_CLONE_THREAD
1506 ? tcp->parent->pid : tcp->pid),
1507 tcp->pid, SIGSTOP) < 0) {
1509 perror("detach: stopping child");
1516 if (wait4(tcp->pid, &status, __WALL, NULL) < 0) {
1517 if (errno == ECHILD) /* Already gone. */
1519 if (errno != EINVAL) {
1520 perror("detach: waiting");
1524 /* No __WALL here. */
1525 if (waitpid(tcp->pid, &status, 0) < 0) {
1526 if (errno != ECHILD) {
1527 perror("detach: waiting");
1531 /* If no processes, try clones. */
1532 if (wait4(tcp->pid, &status, __WCLONE,
1534 if (errno != ECHILD)
1535 perror("detach: waiting");
1538 #endif /* __WCLONE */
1543 if (!WIFSTOPPED(status)) {
1544 /* Au revoir, mon ami. */
1547 if (WSTOPSIG(status) == SIGSTOP) {
1548 ptrace_restart(PTRACE_DETACH, tcp, sig);
1551 error = ptrace_restart(PTRACE_CONT, tcp,
1552 WSTOPSIG(status) == SIGTRAP ? 0
1553 : WSTOPSIG(status));
1560 /* PTRACE_DETACH won't respect `sig' argument, so we post it here. */
1561 if (sig && kill(tcp->pid, sig) < 0)
1562 perror("detach: kill");
1564 error = ptrace_restart(PTRACE_DETACH, tcp, sig);
1568 error |= resume_from_tcp (tcp);
1572 fprintf(stderr, "Process %u detached\n", tcp->pid);
1577 if (zombie != NULL) {
1578 /* TCP no longer exists therefore you must not detach () it. */
1595 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
1606 #endif /* USE_PROCFS */
1614 for (i = 0; i < tcbtabsize; i++) {
1616 if (!(tcp->flags & TCB_INUSE))
1620 "cleanup: looking at pid %u\n", tcp->pid);
1622 (!outfname || followfork < 2 || tcp_last == tcp)) {
1623 tprintf(" <unfinished ...>\n");
1626 if (tcp->flags & TCB_ATTACHED)
1629 kill(tcp->pid, SIGCONT);
1630 kill(tcp->pid, SIGTERM);
1644 #ifndef HAVE_STRERROR
1646 #if !HAVE_DECL_SYS_ERRLIST
1647 extern int sys_nerr;
1648 extern char *sys_errlist[];
1649 #endif /* HAVE_DECL_SYS_ERRLIST */
1655 static char buf[64];
1657 if (errno < 1 || errno >= sys_nerr) {
1658 sprintf(buf, "Unknown error %d", errno);
1661 return sys_errlist[errno];
1664 #endif /* HAVE_STERRROR */
1666 #ifndef HAVE_STRSIGNAL
1668 #if defined HAVE_SYS_SIGLIST && !defined HAVE_DECL_SYS_SIGLIST
1669 extern char *sys_siglist[];
1671 #if defined HAVE_SYS__SIGLIST && !defined HAVE_DECL__SYS_SIGLIST
1672 extern char *_sys_siglist[];
1679 static char buf[64];
1681 if (sig < 1 || sig >= NSIG) {
1682 sprintf(buf, "Unknown signal %d", sig);
1685 #ifdef HAVE__SYS_SIGLIST
1686 return _sys_siglist[sig];
1688 return sys_siglist[sig];
1692 #endif /* HAVE_STRSIGNAL */
1703 pollv = (struct pollfd *) malloc(nprocs * sizeof pollv[0]);
1704 if (pollv == NULL) {
1705 fprintf(stderr, "%s: out of memory\n", progname);
1709 for (i = j = 0; i < tcbtabsize; i++) {
1710 struct tcb *tcp = tcbtab[i];
1711 if (!(tcp->flags & TCB_INUSE))
1713 pollv[j].fd = tcp->pfd;
1714 pollv[j].events = POLLWANT;
1718 fprintf(stderr, "strace: proc miscount\n");
1723 #ifndef HAVE_POLLABLE_PROCFS
1730 if (pipe(proc_poll_pipe) < 0) {
1734 for (i = 0; i < 2; i++) {
1735 if (set_cloexec_flag(proc_poll_pipe[i]) < 0) {
1742 proc_poll(pollv, nfds, timeout)
1743 struct pollfd *pollv;
1749 struct proc_pollfd pollinfo;
1751 if ((n = read(proc_poll_pipe[0], &pollinfo, sizeof(pollinfo))) < 0)
1753 if (n != sizeof(struct proc_pollfd)) {
1754 fprintf(stderr, "panic: short read: %d\n", n);
1757 for (i = 0; i < nprocs; i++) {
1758 if (pollv[i].fd == pollinfo.fd)
1759 pollv[i].revents = pollinfo.revents;
1761 pollv[i].revents = 0;
1763 poller_pid = pollinfo.pid;
1777 struct proc_pollfd pollinfo;
1778 struct sigaction sa;
1779 sigset_t blocked_set, empty_set;
1784 struct procfs_status pfs;
1785 #endif /* FREEBSD */
1797 sa.sa_handler = interactive ? SIG_DFL : SIG_IGN;
1799 sigemptyset(&sa.sa_mask);
1800 sigaction(SIGHUP, &sa, NULL);
1801 sigaction(SIGINT, &sa, NULL);
1802 sigaction(SIGQUIT, &sa, NULL);
1803 sigaction(SIGPIPE, &sa, NULL);
1804 sigaction(SIGTERM, &sa, NULL);
1805 sa.sa_handler = wakeup_handler;
1806 sigaction(SIGUSR1, &sa, NULL);
1807 sigemptyset(&blocked_set);
1808 sigaddset(&blocked_set, SIGUSR1);
1809 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
1810 sigemptyset(&empty_set);
1812 if (getrlimit(RLIMIT_NOFILE, &rl) < 0) {
1813 perror("getrlimit(RLIMIT_NOFILE, ...)");
1817 for (i = 0; i < n; i++) {
1818 if (i != pfd && i != proc_poll_pipe[1])
1823 pollinfo.pid = getpid();
1826 if (ioctl(pfd, PIOCWSTOP, NULL) < 0)
1828 if (ioctl(pfd, PIOCWSTOP, &pfs) < 0)
1829 #endif /* FREEBSD */
1835 pollinfo.revents = POLLERR;
1838 pollinfo.revents = POLLHUP;
1841 perror("proc_poller: PIOCWSTOP");
1843 write(proc_poll_pipe[1], &pollinfo, sizeof(pollinfo));
1846 pollinfo.revents = POLLWANT;
1847 write(proc_poll_pipe[1], &pollinfo, sizeof(pollinfo));
1848 sigsuspend(&empty_set);
1852 #endif /* !HAVE_POLLABLE_PROCFS */
1862 if (followfork < 2 &&
1863 last < nprocs && (pollv[last].revents & POLLWANT)) {
1865 * The previous process is ready to run again. We'll
1866 * let it do so if it is currently in a syscall. This
1867 * heuristic improves the readability of the trace.
1869 tcp = pfd2tcb(pollv[last].fd);
1870 if (tcp && (tcp->flags & TCB_INSYSCALL))
1871 return pollv[last].fd;
1874 for (i = 0; i < nprocs; i++) {
1875 /* Let competing children run round robin. */
1876 j = (i + last + 1) % nprocs;
1877 if (pollv[j].revents & (POLLHUP | POLLERR)) {
1878 tcp = pfd2tcb(pollv[j].fd);
1880 fprintf(stderr, "strace: lost proc\n");
1886 if (pollv[j].revents & POLLWANT) {
1891 fprintf(stderr, "strace: nothing ready\n");
1899 struct tcb *in_syscall = NULL;
1904 int ioctl_result = 0, ioctl_errno = 0;
1909 sigprocmask(SIG_SETMASK, &empty_set, NULL);
1916 #ifndef HAVE_POLLABLE_PROCFS
1917 if (proc_poll_pipe[0] == -1) {
1926 #ifndef HAVE_POLLABLE_PROCFS
1928 /* fall through ... */
1929 #endif /* !HAVE_POLLABLE_PROCFS */
1931 #ifdef HAVE_POLLABLE_PROCFS
1933 /* On some systems (e.g. UnixWare) we get too much ugly
1934 "unfinished..." stuff when multiple proceses are in
1935 syscalls. Here's a nasty hack */
1942 pv.events = POLLWANT;
1943 if ((what = poll (&pv, 1, 1)) < 0) {
1948 else if (what == 1 && pv.revents & POLLWANT) {
1954 if (poll(pollv, nprocs, INFTIM) < 0) {
1959 #else /* !HAVE_POLLABLE_PROCFS */
1960 if (proc_poll(pollv, nprocs, INFTIM) < 0) {
1965 #endif /* !HAVE_POLLABLE_PROCFS */
1972 /* Look up `pfd' in our table. */
1973 if ((tcp = pfd2tcb(pfd)) == NULL) {
1974 fprintf(stderr, "unknown pfd: %u\n", pfd);
1980 /* Get the status of the process. */
1983 ioctl_result = IOCTL_WSTOP (tcp);
1985 /* Thanks to some scheduling mystery, the first poller
1986 sometimes waits for the already processed end of fork
1987 event. Doing a non blocking poll here solves the problem. */
1988 if (proc_poll_pipe[0] != -1)
1989 ioctl_result = IOCTL_STATUS (tcp);
1991 ioctl_result = IOCTL_WSTOP (tcp);
1992 #endif /* FREEBSD */
1993 ioctl_errno = errno;
1994 #ifndef HAVE_POLLABLE_PROCFS
1995 if (proc_poll_pipe[0] != -1) {
1996 if (ioctl_result < 0)
1997 kill(poller_pid, SIGKILL);
1999 kill(poller_pid, SIGUSR1);
2001 #endif /* !HAVE_POLLABLE_PROCFS */
2007 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
2009 if (ioctl_result < 0) {
2010 /* Find out what happened if it failed. */
2011 switch (ioctl_errno) {
2022 perror("PIOCWSTOP");
2028 if ((tcp->flags & TCB_STARTUP) && (tcp->status.PR_WHY == PR_SYSEXIT)) {
2029 /* discard first event for a syscall we never entered */
2030 IOCTL (tcp->pfd, PIOCRUN, 0);
2035 /* clear the just started flag */
2036 tcp->flags &= ~TCB_STARTUP;
2038 /* set current output file */
2042 struct timeval stime;
2047 if ((len = pread(tcp->pfd_status, buf, sizeof(buf) - 1, 0)) > 0) {
2050 "%*s %*d %*d %*d %*d %*d,%*d %*s %*d,%*d %*d,%*d %ld,%ld",
2051 &stime.tv_sec, &stime.tv_usec);
2053 stime.tv_sec = stime.tv_usec = 0;
2054 #else /* !FREEBSD */
2055 stime.tv_sec = tcp->status.pr_stime.tv_sec;
2056 stime.tv_usec = tcp->status.pr_stime.tv_nsec/1000;
2057 #endif /* !FREEBSD */
2058 tv_sub(&tcp->dtime, &stime, &tcp->stime);
2061 what = tcp->status.PR_WHAT;
2062 switch (tcp->status.PR_WHY) {
2065 if (tcp->status.PR_FLAGS & PR_ASLEEP) {
2066 tcp->status.PR_WHY = PR_SYSENTRY;
2067 if (trace_syscall(tcp) < 0) {
2068 fprintf(stderr, "syscall trouble\n");
2073 #endif /* !FREEBSD */
2079 if (trace_syscall(tcp) < 0) {
2080 fprintf(stderr, "syscall trouble\n");
2085 if (!cflag && (qual_flags[what] & QUAL_SIGNAL)) {
2087 tprintf("--- %s (%s) ---",
2088 signame(what), strsignal(what));
2091 if (tcp->status.PR_INFO.si_signo == what) {
2093 tprintf(" siginfo=");
2094 printsiginfo(&tcp->status.PR_INFO, 1);
2101 if (!cflag && (qual_flags[what] & QUAL_FAULT)) {
2103 tprintf("=== FAULT %d ===", what);
2108 case 0: /* handle case we polled for nothing */
2112 fprintf(stderr, "odd stop %d\n", tcp->status.PR_WHY);
2118 if (IOCTL (tcp->pfd, PIOCRUN, &arg) < 0) {
2120 if (IOCTL (tcp->pfd, PIOCRUN, 0) < 0) {
2129 #else /* !USE_PROCFS */
2131 #ifdef TCB_GROUP_EXITING
2132 /* Handle an exit detach or death signal that is taking all the
2133 related clone threads with it. This is called in three circumstances:
2134 SIG == -1 TCP has already died (TCB_ATTACHED is clear, strace is parent).
2135 SIG == 0 Continuing TCP will perform an exit_group syscall.
2136 SIG == other Continuing TCP with SIG will kill the process.
2139 handle_group_exit(struct tcb *tcp, int sig)
2141 /* We need to locate our records of all the clone threads
2142 related to TCP, either its children or siblings. */
2143 struct tcb *leader = ((tcp->flags & TCB_CLONE_THREAD)
2145 : tcp->nclone_detached > 0
2149 if (leader != NULL && leader != tcp &&
2150 !(leader->flags & TCB_GROUP_EXITING))
2152 "PANIC: handle_group_exit: %d leader %d\n",
2153 tcp->pid, leader ? leader->pid : -1);
2154 /* TCP no longer exists therefore you must not detach () it. */
2156 resume_from_tcp (tcp);
2158 droptcb(tcp); /* Already died. */
2161 /* Mark that we are taking the process down. */
2162 tcp->flags |= TCB_EXITING | TCB_GROUP_EXITING;
2163 if (tcp->flags & TCB_ATTACHED) {
2165 if (leader != NULL && leader != tcp)
2166 leader->flags |= TCB_GROUP_EXITING;
2168 if (ptrace_restart(PTRACE_CONT, tcp, sig) < 0) {
2172 if (leader != NULL) {
2173 leader->flags |= TCB_GROUP_EXITING;
2177 /* The leader will report to us as parent now,
2178 and then we'll get to the SIG==-1 case. */
2197 static int wait4_options = __WALL;
2201 while (nprocs != 0) {
2205 sigprocmask(SIG_SETMASK, &empty_set, NULL);
2208 pid = wait4(-1, &status, wait4_options, cflag ? &ru : NULL);
2209 if (pid < 0 && (wait4_options & __WALL) && errno == EINVAL) {
2210 /* this kernel does not support __WALL */
2211 wait4_options &= ~__WALL;
2213 pid = wait4(-1, &status, wait4_options,
2214 cflag ? &ru : NULL);
2216 if (pid < 0 && !(wait4_options & __WALL) && errno == ECHILD) {
2217 /* most likely a "cloned" process */
2218 pid = wait4(-1, &status, __WCLONE,
2219 cflag ? &ru : NULL);
2221 fprintf(stderr, "strace: clone wait4 "
2222 "failed: %s\n", strerror(errno));
2226 pid = wait4(-1, &status, 0, cflag ? &ru : NULL);
2230 pid = wait(&status);
2234 sigprocmask(SIG_BLOCK, &blocked_set, NULL);
2237 switch (wait_errno) {
2242 * We would like to verify this case
2243 * but sometimes a race in Solbourne's
2244 * version of SunOS sometimes reports
2245 * ECHILD before sending us SIGCHILD.
2250 fprintf(stderr, "strace: proc miscount\n");
2256 perror("strace: wait");
2260 if (pid == popen_pid) {
2261 if (WIFEXITED(status) || WIFSIGNALED(status))
2266 fprintf(stderr, " [wait(%#x) = %u]\n", status, pid);
2268 /* Look up `pid' in our table. */
2269 if ((tcp = pid2tcb(pid)) == NULL) {
2272 /* This is needed to go with the CLONE_PTRACE
2273 changes in process.c/util.c: we might see
2274 the child's initial trap before we see the
2275 parent return from the clone syscall.
2276 Leave the child suspended until the parent
2277 returns from its system call. Only then
2278 will we have the association of parent and
2279 child so that we know how to do clearbpt
2281 if (nprocs == tcbtabsize &&
2285 tcp = alloctcb(pid);
2287 kill(pid, SIGKILL); /* XXX */
2290 tcp->flags |= TCB_ATTACHED | TCB_SUSPENDED;
2293 Process %d attached (waiting for parent)\n",
2297 /* This can happen if a clone call used
2298 CLONE_PTRACE itself. */
2301 fprintf(stderr, "unknown pid: %u\n", pid);
2302 if (WIFSTOPPED(status))
2303 ptrace(PTRACE_CONT, pid, (char *) 1, 0);
2307 /* set current output file */
2311 tv_sub(&tcp->dtime, &ru.ru_stime, &tcp->stime);
2312 tcp->stime = ru.ru_stime;
2316 if (tcp->flags & TCB_SUSPENDED) {
2318 * Apparently, doing any ptrace() call on a stopped
2319 * process, provokes the kernel to report the process
2320 * status again on a subsequent wait(), even if the
2321 * process has not been actually restarted.
2322 * Since we have inspected the arguments of suspended
2323 * processes we end up here testing for this case.
2327 if (WIFSIGNALED(status)) {
2328 if (pid == strace_child)
2329 exit_code = 0x100 | WTERMSIG(status);
2331 && (qual_flags[WTERMSIG(status)] & QUAL_SIGNAL)) {
2333 tprintf("+++ killed by %s %s+++",
2334 signame(WTERMSIG(status)),
2336 WCOREDUMP(status) ? "(core dumped) " :
2341 #ifdef TCB_GROUP_EXITING
2342 handle_group_exit(tcp, -1);
2348 if (WIFEXITED(status)) {
2349 if (pid == strace_child)
2350 exit_code = WEXITSTATUS(status);
2352 fprintf(stderr, "pid %u exited\n", pid);
2353 if ((tcp->flags & TCB_ATTACHED)
2354 #ifdef TCB_GROUP_EXITING
2355 && !(tcp->parent && (tcp->parent->flags &
2357 && !(tcp->flags & TCB_GROUP_EXITING)
2361 "PANIC: attached pid %u exited\n",
2363 if (tcp == tcp_last) {
2364 if ((tcp->flags & (TCB_INSYSCALL|TCB_REPRINT))
2366 tprintf(" <unfinished ... exit status %d>\n",
2367 WEXITSTATUS(status));
2370 #ifdef TCB_GROUP_EXITING
2371 handle_group_exit(tcp, -1);
2377 if (!WIFSTOPPED(status)) {
2378 fprintf(stderr, "PANIC: pid %u not stopped\n", pid);
2383 fprintf(stderr, "pid %u stopped, [%s]\n",
2384 pid, signame(WSTOPSIG(status)));
2387 * Interestingly, the process may stop
2388 * with STOPSIG equal to some other signal
2389 * than SIGSTOP if we happend to attach
2390 * just before the process takes a signal.
2392 if ((tcp->flags & TCB_STARTUP) && WSTOPSIG(status) == SIGSTOP) {
2394 * This flag is there to keep us in sync.
2395 * Next time this process stops it should
2396 * really be entering a system call.
2398 tcp->flags &= ~TCB_STARTUP;
2399 if (tcp->flags & TCB_BPTSET) {
2401 * One example is a breakpoint inherited from
2402 * parent through fork ().
2404 if (clearbpt(tcp) < 0) /* Pretty fatal */ {
2413 if (WSTOPSIG(status) != SIGTRAP) {
2414 if (WSTOPSIG(status) == SIGSTOP &&
2415 (tcp->flags & TCB_SIGTRAPPED)) {
2417 * Trapped attempt to block SIGTRAP
2418 * Hope we are back in control now.
2420 tcp->flags &= ~(TCB_INSYSCALL | TCB_SIGTRAPPED);
2421 if (ptrace_restart(PTRACE_SYSCALL, tcp, 0) < 0) {
2428 && (qual_flags[WSTOPSIG(status)] & QUAL_SIGNAL)) {
2429 unsigned long addr = 0;
2431 #if defined(PT_CR_IPSR) && defined(PT_CR_IIP) && defined(PT_GETSIGINFO)
2436 upeek(tcp, PT_CR_IPSR, &psr);
2437 upeek(tcp, PT_CR_IIP, &pc);
2439 pc += (psr >> PSR_RI) & 0x3;
2440 ptrace(PT_GETSIGINFO, pid, 0, (long) &si);
2441 addr = (unsigned long) si.si_addr;
2442 #elif defined PTRACE_GETSIGINFO
2443 if (WSTOPSIG(status) == SIGSEGV ||
2444 WSTOPSIG(status) == SIGBUS) {
2446 if (ptrace(PTRACE_GETSIGINFO, pid,
2448 addr = (unsigned long)
2453 tprintf("--- %s (%s) @ %lx (%lx) ---",
2454 signame(WSTOPSIG(status)),
2455 strsignal(WSTOPSIG(status)), pc, addr);
2458 if (((tcp->flags & TCB_ATTACHED) ||
2459 tcp->nclone_threads > 0) &&
2460 !sigishandled(tcp, WSTOPSIG(status))) {
2461 #ifdef TCB_GROUP_EXITING
2462 handle_group_exit(tcp, WSTOPSIG(status));
2464 detach(tcp, WSTOPSIG(status));
2468 if (ptrace_restart(PTRACE_SYSCALL, tcp, WSTOPSIG(status)) < 0) {
2472 tcp->flags &= ~TCB_SUSPENDED;
2475 /* we handled the STATUS, we are permitted to interrupt now. */
2478 if (trace_syscall(tcp) < 0 && !tcp->ptrace_errno) {
2479 if (tcp->flags & TCB_ATTACHED)
2483 tcp->pid, (char *) 1, SIGTERM);
2488 if (tcp->flags & TCB_EXITING) {
2489 #ifdef TCB_GROUP_EXITING
2490 if (tcp->flags & TCB_GROUP_EXITING) {
2491 if (handle_group_exit(tcp, 0) < 0)
2496 if (tcp->flags & TCB_ATTACHED)
2498 else if (ptrace_restart(PTRACE_CONT, tcp, 0) < 0) {
2504 if (tcp->flags & TCB_SUSPENDED) {
2506 fprintf(stderr, "Process %u suspended\n", pid);
2510 if (ptrace_restart(PTRACE_SYSCALL, tcp, 0) < 0) {
2518 #endif /* !USE_PROCFS */
2524 #define VA_START(a, b) va_start(a, b)
2526 #include <varargs.h>
2527 #define VA_START(a, b) va_start(a)
2532 tprintf(const char *fmt, ...)
2534 tprintf(fmt, va_alist)
2541 VA_START(args, fmt);
2543 int n = vfprintf(outf, fmt, args);
2544 if (n < 0 && outf != stderr)
2545 perror(outfname == NULL
2546 ? "<writing to pipe>" : outfname);
2559 if (tcp_last->ptrace_errno) {
2560 if (tcp_last->flags & TCB_INSYSCALL) {
2561 tprintf(" <unavailable>)");
2564 tprintf("= ? <unavailable>\n");
2565 tcp_last->ptrace_errno = 0;
2566 } else if (!outfname || followfork < 2 || tcp_last == tcp) {
2567 tcp_last->flags |= TCB_REPRINT;
2568 tprintf(" <unfinished ...>\n");
2572 if ((followfork == 1 || pflag_seen > 1) && outfname)
2573 tprintf("%-5d ", tcp->pid);
2574 else if (nprocs > 1 && !outfname)
2575 tprintf("[pid %5u] ", tcp->pid);
2577 char str[sizeof("HH:MM:SS")];
2578 struct timeval tv, dtv;
2579 static struct timeval otv;
2581 gettimeofday(&tv, NULL);
2583 if (otv.tv_sec == 0)
2585 tv_sub(&dtv, &tv, &otv);
2586 tprintf("%6ld.%06ld ",
2587 (long) dtv.tv_sec, (long) dtv.tv_usec);
2590 else if (tflag > 2) {
2591 tprintf("%ld.%06ld ",
2592 (long) tv.tv_sec, (long) tv.tv_usec);
2595 time_t local = tv.tv_sec;
2596 strftime(str, sizeof(str), "%T", localtime(&local));
2598 tprintf("%s.%06ld ", str, (long) tv.tv_usec);
2600 tprintf("%s ", str);
2612 tprintf("%*s", col - curcol, "");
2623 #ifdef HAVE_MP_PROCFS
2625 int mp_ioctl (int fd, int cmd, void *arg, int size) {
2627 struct iovec iov[2];
2630 iov[0].iov_base = &cmd;
2631 iov[0].iov_len = sizeof cmd;
2634 iov[1].iov_base = arg;
2635 iov[1].iov_len = size;
2638 return writev (fd, iov, n);