]> granicus.if.org Git - strace/blob - strace.c
Catching up on my mail-backlog, see ChangeLog for details
[strace] / strace.c
1 /*
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  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. The name of the author may not be used to endorse or promote products
16  *    derived from this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  *
29  *      $Id$
30  */
31
32 #include "defs.h"
33
34 #include <signal.h>
35 #include <errno.h>
36 #include <sys/param.h>
37 #include <fcntl.h>
38 #include <sys/resource.h>
39 #include <sys/wait.h>
40 #include <sys/stat.h>
41 #include <pwd.h>
42 #include <grp.h>
43 #include <string.h>
44
45 #ifdef SVR4
46 #include <sys/stropts.h>
47 #include <poll.h>
48 #ifdef SVR4_MP
49 #include <sys/uio.h>
50 #endif
51 #endif
52
53 int debug = 0, followfork = 0, followvfork = 0, interactive = 0;
54 int rflag = 0, tflag = 0, dtime = 0, cflag = 0;
55 int iflag = 0, xflag = 0, qflag = 0;
56 int pflag_seen = 0;
57
58 char *username = NULL;
59 uid_t run_uid;
60 gid_t run_gid;
61
62 int acolumn = DEFAULT_ACOLUMN;
63 int max_strlen = DEFAULT_STRLEN;
64 char *outfname = NULL;
65 FILE *outf;
66 struct tcb tcbtab[MAX_PROCS];
67 int nprocs;
68 char *progname;
69 extern char version[];
70 extern char **environ;
71
72 static struct tcb *pid2tcb P((int pid));
73 static int trace P((void));
74 static void cleanup P((void));
75 static void interrupt P((int sig));
76 static sigset_t empty_set, blocked_set;
77
78 #ifdef HAVE_SIG_ATOMIC_T
79 static volatile sig_atomic_t interrupted;
80 #else /* !HAVE_SIG_ATOMIC_T */
81 #ifdef __STDC__
82 static volatile int interrupted;
83 #else /* !__STDC__ */
84 static int interrupted;
85 #endif /* !__STDC__ */
86 #endif /* !HAVE_SIG_ATOMIC_T */
87
88 #ifdef SVR4
89
90 static struct tcb *pfd2tcb P((int pfd));
91 static void reaper P((int sig));
92 static void rebuild_pollv P((void));
93 struct pollfd pollv[MAX_PROCS];
94
95 #ifndef HAVE_POLLABLE_PROCFS
96
97 static void proc_poll_open P((void));
98 static void proc_poller P((int pfd));
99
100 struct proc_pollfd {
101         int fd;
102         int revents;
103         int pid;
104 };
105
106 static int poller_pid;
107 static int proc_poll_pipe[2] = { -1, -1 };
108
109 #endif /* !HAVE_POLLABLE_PROCFS */
110
111 #ifdef SVR4_MP
112 #define POLLWANT        POLLWRNORM
113 #else
114 #define POLLWANT        POLLPRI
115 #endif
116 #endif /* SVR4 */
117
118 static void
119 usage(ofp, exitval)
120 FILE *ofp;
121 int exitval;
122 {
123         fprintf(ofp, "\
124 usage: strace [-dffhiqrtttTvVxx] [-a column] [-e expr] ... [-o file]\n\
125               [-p pid] ... [-s strsize] [-u username] [command [arg ...]]\n\
126    or: strace -c [-e expr] ... [-O overhead] [-S sortby] [command [arg ...]]\n\
127 -c -- count time, calls, and errors for each syscall and report summary\n\
128 -f -- follow forks, -ff -- with output into separate files\n\
129 -F -- attempt to follow vforks, -h -- print help message\n\
130 -i -- print instruction pointer at time of syscall\n\
131 -q -- suppress messages about attaching, detaching, etc.\n\
132 -r -- print relative timestamp, -t -- absolute timestamp, -tt -- with usecs\n\
133 -T -- print time spent in each syscall, -V -- print version\n\
134 -v -- verbose mode: print unabbreviated argv, stat, termio[s], etc. args\n\
135 -x -- print non-ascii strings in hex, -xx -- print all strings in hex\n\
136 -a column -- alignment COLUMN for printing syscall results (default %d)\n\
137 -e expr -- a qualifying expression: option=[!]all or option=[!]val1[,val2]...\n\
138    options: trace, abbrev, verbose, raw, signal, read, or write\n\
139 -o file -- send trace output to FILE instead of stderr\n\
140 -O overhead -- set overhead for tracing syscalls to OVERHEAD usecs\n\
141 -p pid -- trace process with process id PID, may be repeated\n\
142 -s strsize -- limit length of print strings to STRSIZE chars (default %d)\n\
143 -S sortby -- sort syscall counts by: time, calls, name, nothing (default %s)\n\
144 -u username -- run command as username handling setuid and/or setgid\n\
145 ", DEFAULT_ACOLUMN, DEFAULT_STRLEN, DEFAULT_SORTBY);
146         exit(exitval);
147 }
148
149 #ifdef SVR4
150 #ifdef MIPS
151 void
152 foobar()
153 {
154 }
155 #endif /* MIPS */
156 #endif /* SVR4 */
157
158 int
159 main(argc, argv)
160 int argc;
161 char *argv[];
162 {
163         extern int optind;
164         extern char *optarg;
165         struct tcb *tcp;
166         int c, pid = 0;
167         struct sigaction sa;
168
169         static char buf[BUFSIZ];
170
171         progname = argv[0];
172         outf = stderr;
173         interactive = 1;
174         qualify("trace=all");
175         qualify("abbrev=all");
176         qualify("verbose=all");
177         qualify("signal=all");
178         set_sortby(DEFAULT_SORTBY);
179         set_personality(DEFAULT_PERSONALITY);
180         while ((c = getopt(argc, argv,
181                 "+cdfFhiqrtTvVxa:e:o:O:p:s:S:u:")) != EOF) {
182                 switch (c) {
183                 case 'c':
184                         cflag++;
185                         dtime++;
186                         break;
187                 case 'd':
188                         debug++;
189                         break;
190                 case 'f':
191                         followfork++;
192                         break;
193                 case 'F':
194                         followvfork++;
195                         break;
196                 case 'h':
197                         usage(stdout, 0);
198                         break;
199                 case 'i':
200                         iflag++;
201                         break;
202                 case 'q':
203                         qflag++;
204                         break;
205                 case 'r':
206                         rflag++;
207                         tflag++;
208                         break;
209                 case 't':
210                         tflag++;
211                         break;
212                 case 'T':
213                         dtime++;
214                         break;
215                 case 'x':
216                         xflag++;
217                         break;
218                 case 'v':
219                         qualify("abbrev=none");
220                         break;
221                 case 'V':
222                         printf("%s\n", version);
223                         exit(0);
224                         break;
225                 case 'a':
226                         acolumn = atoi(optarg);
227                         break;
228                 case 'e':
229                         qualify(optarg);
230                         break;
231                 case 'o':
232                         outfname = strdup(optarg);
233                         break;
234                 case 'O':
235                         set_overhead(atoi(optarg));
236                         break;
237                 case 'p':
238                         if ((pid = atoi(optarg)) == 0) {
239                                 fprintf(stderr, "%s: Invalid process id: %s\n",
240                                         progname, optarg);
241                                 break;
242                         }
243                         if (pid == getpid()) {
244                                 fprintf(stderr, "%s: I'm sorry, I can't let you do that, Dave.", progname);
245                                 break;
246                         }
247                         if ((tcp = alloctcb(pid)) == NULL) {
248                                 fprintf(stderr, "%s: tcb table full, please recompile strace\n",
249                                         progname);
250                                 exit(1);
251                         }
252                         tcp->flags |= TCB_ATTACHED;
253                         pflag_seen++;
254                         break;
255                 case 's':
256                         max_strlen = atoi(optarg);
257                         break;
258                 case 'S':
259                         set_sortby(optarg);
260                         break;
261                 case 'u':
262                         username = strdup(optarg);
263                         break;
264                 default:
265                         usage(stderr, 1);
266                         break;
267                 }
268         }
269
270         /* See if they want to run as another user. */
271         if (username != NULL) {
272                 struct passwd *pent;
273
274                 if (getuid() != 0 || geteuid() != 0) {
275                         fprintf(stderr,
276                                 "%s: you must be root to use the -u option\n",
277                                 progname);
278                         exit(1);
279                 }
280                 if ((pent = getpwnam(username)) == NULL) {
281                         fprintf(stderr, "%s: cannot find user `%s'\n",
282                                 progname, optarg);
283                         exit(1);
284                 }
285                 run_uid = pent->pw_uid;
286                 run_gid = pent->pw_gid;
287         }
288         else {
289                 run_uid = getuid();
290                 run_gid = getgid();
291         }
292
293 #ifndef SVR4
294         setreuid(geteuid(), getuid());
295 #endif
296
297         /* See if they want to pipe the output. */
298         if (outfname && (outfname[0] == '|' || outfname[0] == '!')) {
299                 if ((outf = popen(outfname + 1, "w")) == NULL) {
300                         fprintf(stderr, "%s: can't popen '%s': %s\n",
301                                 progname, outfname + 1, strerror(errno));
302                         exit(1);
303                 }
304                 free(outfname);
305                 outfname = NULL;
306         }
307
308         /* Check if they want to redirect the output. */
309         if (outfname) {
310                 if ((outf = fopen(outfname, "w")) == NULL) {
311                         fprintf(stderr, "%s: can't fopen '%s': %s\n",
312                                 progname, outfname, strerror(errno));
313                         exit(1);
314                 }
315         }
316
317 #ifndef SVR4
318         setreuid(geteuid(), getuid());
319 #endif
320
321         if (!outfname) {
322                 qflag = 1;
323                 setvbuf(outf, buf, _IOLBF, BUFSIZ);
324         }
325         else if (optind < argc)
326                 interactive = 0;
327         else
328                 qflag = 1;
329
330         for (c = 0, tcp = tcbtab; c < MAX_PROCS; c++, tcp++) {
331                 /* Reinitialize the output since it may have changed. */
332                 tcp->outf = outf;
333                 if (!(tcp->flags & TCB_INUSE) || !(tcp->flags & TCB_ATTACHED))
334                         continue;
335 #ifdef SVR4
336                 if (proc_open(tcp, 1) < 0) {
337                         fprintf(stderr, "trouble opening proc file\n");
338                         droptcb(tcp);
339                         continue;
340                 }
341 #else /* !SVR4 */
342                 if (ptrace(PTRACE_ATTACH, tcp->pid, (char *) 1, 0) < 0) {
343                         perror("attach: ptrace(PTRACE_ATTACH, ...)");
344                         droptcb(tcp);
345                         continue;
346                 }
347 #endif /* !SVR4 */
348                 if (!qflag)
349                         fprintf(stderr,
350                                 "Process %u attached - interrupt to quit\n",
351                                 pid);
352         }
353
354         if (optind < argc) {
355                 struct stat statbuf;
356                 char *filename;
357                 char pathname[MAXPATHLEN];
358
359                 filename = argv[optind];
360                 if (strchr(filename, '/'))
361                         strcpy(pathname, filename);
362 #ifdef USE_DEBUGGING_EXEC
363                 /*
364                  * Debuggers customarily check the current directory
365                  * first regardless of the path but doing that gives
366                  * security geeks a panic attack.
367                  */
368                 else if (stat(filename, &statbuf) == 0)
369                         strcpy(pathname, filename);
370 #endif /* USE_DEBUGGING_EXEC */
371                 else {
372                         char *path;
373                         int m, n, len;
374
375                         for (path = getenv("PATH"); path && *path; path += m) {
376                                 if (strchr(path, ':')) {
377                                         n = strchr(path, ':') - path;
378                                         m = n + 1;
379                                 }
380                                 else
381                                         m = n = strlen(path);
382                                 if (n == 0) {
383                                         getcwd(pathname, MAXPATHLEN);
384                                         len = strlen(pathname);
385                                 }
386                                 else {
387                                         strncpy(pathname, path, n);
388                                         len = n;
389                                 }
390                                 if (len && pathname[len - 1] != '/')
391                                         pathname[len++] = '/';
392                                 strcpy(pathname + len, filename);
393                                 if (stat(pathname, &statbuf) == 0)
394                                         break;
395                         }
396                 }
397                 if (stat(pathname, &statbuf) < 0) {
398                         fprintf(stderr, "%s: %s: command not found\n",
399                                 progname, filename);
400                         exit(1);
401                 }
402                 switch (pid = fork()) {
403                 case -1:
404                         perror("strace: fork");
405                         cleanup();
406                         exit(1);
407                         break;
408                 case 0: {
409 #ifdef SVR4
410                         if (outf != stderr) close (fileno (outf));
411 #ifdef MIPS
412                         /* Kludge for SGI, see proc_open for details. */
413                         sa.sa_handler = foobar;
414                         sa.sa_flags = 0;
415                         sigemptyset(&sa.sa_mask);
416                         sigaction(SIGINT, &sa, NULL);
417 #endif /* MIPS */
418                         pause();
419 #else /* !SVR4 */
420                         if (ptrace(PTRACE_TRACEME, 0, (char *) 1, 0) < 0) {
421                                 perror("strace: ptrace(PTRACE_TRACEME, ...)");
422                                 return -1;
423                         }
424                         if (debug)
425                                 kill(getpid(), SIGSTOP);
426
427                         if (username != NULL || geteuid() == 0) {
428                                 uid_t run_euid = run_uid;
429                                 gid_t run_egid = run_gid;
430
431                                 if (statbuf.st_mode & S_ISUID)
432                                         run_euid = statbuf.st_uid;
433                                 if (statbuf.st_mode & S_ISGID)
434                                         run_egid = statbuf.st_gid;
435
436                                 /*
437                                  * It is important to set groups before we
438                                  * lose privileges on setuid.
439                                  */
440                                 if (username != NULL
441                                     && initgroups(username, run_gid) < 0) {
442                                         perror("initgroups");
443                                         exit(1);
444                                 }
445                                 if (setregid(run_gid, run_egid) < 0) {
446                                         perror("setregid");
447                                         exit(1);
448                                 }
449                                 if (setreuid(run_uid, run_euid) < 0) {
450                                         perror("setreuid");
451                                         exit(1);
452                                 }
453                         }
454                         else
455                                 setreuid(run_uid, run_uid);
456 #endif /* !SVR4 */
457
458                         execv(pathname, &argv[optind]);
459                         perror("strace: exec");
460                         _exit(1);
461                         break;
462                 }
463                 default:
464                         if ((tcp = alloctcb(pid)) == NULL) {
465                                 fprintf(stderr, "tcb table full\n");
466                                 cleanup();
467                                 exit(1);
468                         }
469 #ifdef SVR4
470                         if (proc_open(tcp, 0) < 0) {
471                                 fprintf(stderr, "trouble opening proc file\n");
472                                 cleanup();
473                                 exit(1);
474                         }
475 #endif /* SVR4 */
476 #ifndef SVR4
477                         fake_execve(tcp, pathname, &argv[optind], environ);
478 #endif
479                         break;
480                 }
481         }
482         else if (pflag_seen == 0)
483                 usage(stderr, 1);
484
485         sigemptyset(&empty_set);
486         sigemptyset(&blocked_set);
487         sa.sa_handler = SIG_IGN;
488         sigemptyset(&sa.sa_mask);
489         sa.sa_flags = 0;
490         sigaction(SIGTTOU, &sa, NULL);
491         sigaction(SIGTTIN, &sa, NULL);
492         if (interactive) {
493                 sigaddset(&blocked_set, SIGHUP);
494                 sigaddset(&blocked_set, SIGINT);
495                 sigaddset(&blocked_set, SIGQUIT);
496                 sigaddset(&blocked_set, SIGPIPE);
497                 sigaddset(&blocked_set, SIGTERM);
498                 sa.sa_handler = interrupt;
499 #ifdef SUNOS4
500                 /* POSIX signals on sunos4.1 are a little broken. */
501                 sa.sa_flags = SA_INTERRUPT;
502 #endif /* SUNOS4 */
503         }
504         sigaction(SIGHUP, &sa, NULL);
505         sigaction(SIGINT, &sa, NULL);
506         sigaction(SIGQUIT, &sa, NULL);
507         sigaction(SIGPIPE, &sa, NULL);
508         sigaction(SIGTERM, &sa, NULL);
509 #ifdef SVR4
510         sa.sa_handler = reaper;
511         sigaction(SIGCHLD, &sa, NULL);
512 #endif /* SVR4 */
513
514         if (trace() < 0)
515                 exit(1);
516         cleanup();
517         exit(0);
518 }
519
520 void
521 newoutf(tcp)
522 struct tcb *tcp;
523 {
524         char name[MAXPATHLEN];
525         FILE *fp;
526
527         if (outfname && followfork > 1) {
528                 sprintf(name, "%s.%u", outfname, tcp->pid);
529 #ifndef SVR4
530                 setreuid(geteuid(), getuid());
531 #endif
532                 fp = fopen(name, "w");
533 #ifndef SVR4
534                 setreuid(geteuid(), getuid());
535 #endif
536                 if (fp == NULL) {
537                         perror("fopen");
538                         return;
539                 }
540                 tcp->outf = fp;
541         }
542         return;
543 }
544
545 struct tcb *
546 alloctcb(pid)
547 int pid;
548 {
549         int i;
550         struct tcb *tcp;
551
552         for (i = 0, tcp = tcbtab; i < MAX_PROCS; i++, tcp++) {
553                 if ((tcp->flags & TCB_INUSE) == 0) {
554                         tcp->pid = pid;
555                         tcp->parent = NULL;
556                         tcp->nchildren = 0;
557                         tcp->flags = TCB_INUSE | TCB_STARTUP;
558                         tcp->outf = outf; /* Initialise to current out file */
559                         tcp->stime.tv_sec = 0;
560                         tcp->stime.tv_usec = 0;
561                         tcp->pfd = -1;
562                         nprocs++;
563                         return tcp;
564                 }
565         }
566         return NULL;
567 }
568
569 #ifdef SVR4
570 int
571 proc_open(tcp, attaching)
572 struct tcb *tcp;
573 int attaching;
574 {
575         char proc[32];
576         long arg;
577         sysset_t sc_enter, sc_exit;
578         sigset_t signals;
579         fltset_t faults;
580 #ifndef HAVE_POLLABLE_PROCFS
581         static int last_pfd;
582 #endif
583
584 #ifdef SVR4_MP
585         /* Open the process pseudo-files in /proc. */
586         sprintf(proc, "/proc/%d/ctl", tcp->pid);
587         if ((tcp->pfd = open(proc, O_WRONLY|O_EXCL)) < 0) {
588                 perror("strace: open(\"/proc/...\", ...)");
589                 return -1;
590         }
591         if ((arg = fcntl(tcp->pfd, F_GETFD)) < 0) {
592                 perror("F_GETFD");
593                 return -1;
594         }
595         if (fcntl(tcp->pfd, F_SETFD, arg|FD_CLOEXEC) < 0) {
596                 perror("F_SETFD");
597                 return -1;
598         }
599         sprintf(proc, "/proc/%d/status", tcp->pid);
600         if ((tcp->pfd_stat = open(proc, O_RDONLY|O_EXCL)) < 0) {
601                 perror("strace: open(\"/proc/...\", ...)");
602                 return -1;
603         }
604         if ((arg = fcntl(tcp->pfd_stat, F_GETFD)) < 0) {
605                 perror("F_GETFD");
606                 return -1;
607         }
608         if (fcntl(tcp->pfd_stat, F_SETFD, arg|FD_CLOEXEC) < 0) {
609                 perror("F_SETFD");
610                 return -1;
611         }
612         sprintf(proc, "/proc/%d/as", tcp->pid);
613         if ((tcp->pfd_as = open(proc, O_RDONLY|O_EXCL)) < 0) {
614                 perror("strace: open(\"/proc/...\", ...)");
615                 return -1;
616         }
617         if ((arg = fcntl(tcp->pfd_as, F_GETFD)) < 0) {
618                 perror("F_GETFD");
619                 return -1;
620         }
621         if (fcntl(tcp->pfd_as, F_SETFD, arg|FD_CLOEXEC) < 0) {
622                 perror("F_SETFD");
623                 return -1;
624         }
625 #else
626         /* Open the process pseudo-file in /proc. */
627         sprintf(proc, "/proc/%d", tcp->pid);
628         if ((tcp->pfd = open(proc, O_RDWR|O_EXCL)) < 0) {
629                 perror("strace: open(\"/proc/...\", ...)");
630                 return -1;
631         }
632         if ((arg = fcntl(tcp->pfd, F_GETFD)) < 0) {
633                 perror("F_GETFD");
634                 return -1;
635         }
636         if (fcntl(tcp->pfd, F_SETFD, arg|FD_CLOEXEC) < 0) {
637                 perror("F_SETFD");
638                 return -1;
639         }
640 #endif
641         rebuild_pollv();
642         if (!attaching) {
643                 /*
644                  * Wait for the child to pause.  Because of a race
645                  * condition we have to poll for the event.
646                  */
647                 for (;;) {
648                         if (IOCTL_STATUS (tcp) < 0) {
649                                 perror("strace: PIOCSTATUS");
650                                 return -1;
651                         }
652                         if (tcp->status.PR_FLAGS & PR_ASLEEP)
653                                 break;
654                 }
655         }
656         /* Stop the process so that we own the stop. */
657         if (IOCTL(tcp->pfd, PIOCSTOP, NULL) < 0) {
658                 perror("strace: PIOCSTOP");
659                 return -1;
660         }
661 #ifdef PIOCSET
662         /* Set Run-on-Last-Close. */
663         arg = PR_RLC;
664         if (IOCTL(tcp->pfd, PIOCSET, &arg) < 0) {
665                 perror("PIOCSET PR_RLC");
666                 return -1;
667         }
668         /* Set or Reset Inherit-on-Fork. */
669         arg = PR_FORK;
670         if (IOCTL(tcp->pfd, followfork ? PIOCSET : PIOCRESET, &arg) < 0) {
671                 perror("PIOC{SET,RESET} PR_FORK");
672                 return -1;
673         }
674 #else  /* !PIOCSET */
675         if (ioctl(tcp->pfd, PIOCSRLC) < 0) {
676                 perror("PIOCSRLC");
677                 return -1;
678         }
679         if (ioctl(tcp->pfd, followfork ? PIOCSFORK : PIOCRFORK) < 0) {
680                 perror("PIOC{S,R}FORK");
681                 return -1;
682         }
683 #endif /* !PIOCSET */
684         /* Enable all syscall entries. */
685         prfillset(&sc_enter);
686         if (IOCTL(tcp->pfd, PIOCSENTRY, &sc_enter) < 0) {
687                 perror("PIOCSENTRY");
688                 return -1;
689         }
690         /* Enable all syscall exits. */
691         prfillset(&sc_exit);
692         if (IOCTL(tcp->pfd, PIOCSEXIT, &sc_exit) < 0) {
693                 perror("PIOSEXIT");
694                 return -1;
695         }
696         /* Enable all signals. */
697         prfillset(&signals);
698         if (IOCTL(tcp->pfd, PIOCSTRACE, &signals) < 0) {
699                 perror("PIOCSTRACE");
700                 return -1;
701         }
702         /* Enable all faults. */
703         prfillset(&faults);
704         if (IOCTL(tcp->pfd, PIOCSFAULT, &faults) < 0) {
705                 perror("PIOCSFAULT");
706                 return -1;
707         }
708         if (!attaching) {
709 #ifdef MIPS
710                 /*
711                  * The SGI PRSABORT doesn't work for pause() so
712                  * we send it a caught signal to wake it up.
713                  */
714                 kill(tcp->pid, SIGINT);
715 #else /* !MIPS */
716                 /* The child is in a pause(), abort it. */
717                 arg = PRSABORT;
718                 if (IOCTL (tcp->pfd, PIOCRUN, &arg) < 0) {
719                         perror("PIOCRUN");
720                         return -1;
721                 }
722 #endif /* !MIPS */
723                 for (;;) {
724                         /* Wait for the child to do something. */
725                         if (IOCTL_WSTOP (tcp) < 0) {
726                                 perror("PIOCWSTOP");
727                                 return -1;
728                         }
729                         if (tcp->status.PR_WHY == PR_SYSENTRY) {
730 #ifdef HAVE_PR_SYSCALL
731                                 int scno = tcp->status.pr_syscall;
732 #else /* !HAVE_PR_SYSCALL */
733                                 int scno = tcp->status.PR_WHAT;
734 #endif /* !HAVE_PR_SYSCALL */
735                                 if (scno == SYS_execve)
736                                         break;
737                         }
738                         /* Set it running: maybe execve will be next. */
739                         arg = 0;
740                         if (IOCTL(tcp->pfd, PIOCRUN, &arg) < 0) {
741                                 perror("PIOCRUN");
742                                 return -1;
743                         }
744                 }
745         }
746 #ifndef HAVE_POLLABLE_PROCFS
747         if (proc_poll_pipe[0] != -1)
748                 proc_poller(tcp->pfd);
749         else if (nprocs > 1) {
750                 proc_poll_open();
751                 proc_poller(last_pfd);
752                 proc_poller(tcp->pfd);
753         }
754         last_pfd = tcp->pfd;
755 #endif /* !HAVE_POLLABLE_PROCFS */
756         return 0;
757 }
758
759 #endif /* SVR4 */
760
761 static struct tcb *
762 pid2tcb(pid)
763 int pid;
764 {
765         int i;
766         struct tcb *tcp;
767
768         for (i = 0, tcp = tcbtab; i < MAX_PROCS; i++, tcp++) {
769                 if (pid && tcp->pid != pid)
770                         continue;
771                 if (tcp->flags & TCB_INUSE)
772                         return tcp;
773         }
774         return NULL;
775 }
776
777 #ifdef SVR4
778
779 static struct tcb *
780 pfd2tcb(pfd)
781 int pfd;
782 {
783         int i;
784         struct tcb *tcp;
785
786         for (i = 0, tcp = tcbtab; i < MAX_PROCS; i++, tcp++) {
787                 if (tcp->pfd != pfd)
788                         continue;
789                 if (tcp->flags & TCB_INUSE)
790                         return tcp;
791         }
792         return NULL;
793 }
794
795 #endif /* SVR4 */
796
797 void
798 droptcb(tcp)
799 struct tcb *tcp;
800 {
801         if (tcp->pid == 0)
802                 return;
803         nprocs--;
804         tcp->pid = 0;
805         tcp->flags = 0;
806         if (tcp->pfd != -1) {
807                 close(tcp->pfd);
808                 tcp->pfd = -1;
809 #ifdef SVR4
810                 rebuild_pollv();
811 #endif
812         }
813         if (tcp->parent != NULL) {
814                 tcp->parent->nchildren--;
815                 tcp->parent = NULL;
816         }
817 #if 0
818         if (tcp->outf != stderr)
819                 fclose(tcp->outf);
820 #endif
821         tcp->outf = 0;
822 }
823
824 #ifndef SVR4
825
826 static int
827 resume(tcp)
828 struct tcb *tcp;
829 {
830         if (tcp == NULL)
831                 return -1;
832
833         if (!(tcp->flags & TCB_SUSPENDED)) {
834                 fprintf(stderr, "PANIC: pid %u not suspended\n", tcp->pid);
835                 return -1;
836         }
837         tcp->flags &= ~TCB_SUSPENDED;
838
839         if (ptrace(PTRACE_SYSCALL, tcp->pid, (char *) 1, 0) < 0) {
840                 perror("resume: ptrace(PTRACE_SYSCALL, ...)");
841                 return -1;
842         }
843
844         if (!qflag)
845                 fprintf(stderr, "Process %u resumed\n", tcp->pid);
846         return 0;
847 }
848
849 #endif /* !SVR4 */
850
851 /* detach traced process; continue with sig */
852
853 static int
854 detach(tcp, sig)
855 struct tcb *tcp;
856 int sig;
857 {
858         int error = 0;
859 #ifdef LINUX
860         int status;
861 #endif
862
863         if (tcp->flags & TCB_BPTSET)
864                 sig = SIGKILL;
865
866 #ifdef LINUX
867         /*
868          * Linux wrongly insists the child be stopped
869          * before detaching.  Arghh.  We go through hoops
870          * to make a clean break of things.
871          */
872 #if defined(SPARC)
873 #undef PTRACE_DETACH
874 #define PTRACE_DETACH PTRACE_SUNDETACH
875 #endif
876         if ((error = ptrace(PTRACE_DETACH, tcp->pid, (char *) 1, sig)) == 0) {
877                 /* On a clear day, you can see forever. */
878         }
879         else if (errno != ESRCH) {
880                 /* Shouldn't happen. */
881                 perror("detach: ptrace(PTRACE_DETACH, ...)");
882         }
883         else if (kill(tcp->pid, 0) < 0) {
884                 if (errno != ESRCH)
885                         perror("detach: checking sanity");
886         }
887         else if (kill(tcp->pid, SIGSTOP) < 0) {
888                 if (errno != ESRCH)
889                         perror("detach: stopping child");
890         }
891         else {
892                 for (;;) {
893                         if (waitpid(tcp->pid, &status, 0) < 0) {
894                                 if (errno != ECHILD)
895                                         perror("detach: waiting");
896                                 break;
897                         }
898                         if (!WIFSTOPPED(status)) {
899                                 /* Au revoir, mon ami. */
900                                 break;
901                         }
902                         if (WSTOPSIG(status) == SIGSTOP) {
903                                 if ((error = ptrace(PTRACE_DETACH,
904                                     tcp->pid, (char *) 1, sig)) < 0) {
905                                         if (errno != ESRCH)
906                                                 perror("detach: ptrace(PTRACE_DETACH, ...)");
907                                         /* I died trying. */
908                                 }
909                                 break;
910                         }
911                         if ((error = ptrace(PTRACE_CONT, tcp->pid, (char *) 1,
912                             WSTOPSIG(status) == SIGTRAP ?
913                             0 : WSTOPSIG(status))) < 0) {
914                                 if (errno != ESRCH)
915                                         perror("detach: ptrace(PTRACE_CONT, ...)");
916                                 break;
917                         }
918                 }
919         }
920 #endif /* LINUX */
921
922 #if defined(SUNOS4)
923         /* PTRACE_DETACH won't respect `sig' argument, so we post it here. */
924         if (sig && kill(tcp->pid, sig) < 0)
925                 perror("detach: kill");
926         sig = 0;
927         if ((error = ptrace(PTRACE_DETACH, tcp->pid, (char *) 1, sig)) < 0)
928                 perror("detach: ptrace(PTRACE_DETACH, ...)");
929 #endif /* SUNOS4 */
930
931 #ifndef SVR4
932         if (waiting_parent(tcp))
933                 error = resume(tcp->parent);
934 #endif /* !SVR4 */
935
936         if (!qflag)
937                 fprintf(stderr, "Process %u detached\n", tcp->pid);
938
939         droptcb(tcp);
940         return error;
941 }
942
943 #ifdef SVR4
944
945 static void
946 reaper(sig)
947 int sig;
948 {
949         int pid;
950         int status;
951
952         while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
953 #if 0
954                 struct tcb *tcp;
955
956                 tcp = pid2tcb(pid);
957                 if (tcp)
958                         droptcb(tcp);
959 #endif
960         }
961 }
962
963 #endif /* SVR4 */
964
965 static void
966 cleanup()
967 {
968         int i;
969         struct tcb *tcp;
970
971         for (i = 0, tcp = tcbtab; i < MAX_PROCS; i++, tcp++) {
972                 if (!(tcp->flags & TCB_INUSE))
973                         continue;
974                 if (debug)
975                         fprintf(stderr,
976                                 "cleanup: looking at pid %u\n", tcp->pid);
977                 if (tcp_last &&
978                     (!outfname || followfork < 2 || tcp_last == tcp)) {
979                         tprintf(" <unfinished ...>\n");
980                         tcp_last = NULL;
981                 }
982                 if (tcp->flags & TCB_ATTACHED)
983                         detach(tcp, 0);
984                 else {
985                         kill(tcp->pid, SIGCONT);
986                         kill(tcp->pid, SIGTERM);
987                 }
988         }
989         if (cflag)
990                 call_summary(outf);
991 }
992
993 static void
994 interrupt(sig)
995 int sig;
996 {
997         interrupted = 1;
998 }
999
1000 #ifndef HAVE_STRERROR
1001
1002 #ifndef SYS_ERRLIST_DECLARED
1003 extern int sys_nerr;
1004 extern char *sys_errlist[];
1005 #endif /* SYS_ERRLIST_DECLARED */
1006
1007 const char *
1008 strerror(errno)
1009 int errno;
1010 {
1011         static char buf[64];
1012
1013         if (errno < 1 || errno >= sys_nerr) {
1014                 sprintf(buf, "Unknown error %d", errno);
1015                 return buf;
1016         }
1017         return sys_errlist[errno];
1018 }
1019
1020 #endif /* HAVE_STERRROR */
1021
1022 #ifndef HAVE_STRSIGNAL
1023
1024 #ifndef SYS_SIGLIST_DECLARED
1025 #ifdef HAVE__SYS_SIGLIST
1026         extern char *_sys_siglist[];
1027 #else
1028         extern char *sys_siglist[];
1029 #endif
1030 #endif /* SYS_SIGLIST_DECLARED */
1031
1032 const char *
1033 strsignal(sig)
1034 int sig;
1035 {
1036         static char buf[64];
1037
1038         if (sig < 1 || sig >= NSIG) {
1039                 sprintf(buf, "Unknown signal %d", sig);
1040                 return buf;
1041         }
1042 #ifdef HAVE__SYS_SIGLIST
1043         return _sys_siglist[sig];
1044 #else
1045         return sys_siglist[sig];
1046 #endif
1047 }
1048
1049 #endif /* HAVE_STRSIGNAL */
1050
1051 #ifdef SVR4
1052
1053 static void
1054 rebuild_pollv()
1055 {
1056         int i, j;
1057         struct tcb *tcp;
1058
1059         for (i = j = 0, tcp = tcbtab; i < MAX_PROCS; i++, tcp++) {
1060                 if (!(tcp->flags & TCB_INUSE))
1061                         continue;
1062                 pollv[j].fd = tcp->pfd;
1063                 pollv[j].events = POLLWANT;
1064                 j++;
1065         }
1066         if (j != nprocs) {
1067                 fprintf(stderr, "strace: proc miscount\n");
1068                 exit(1);
1069         }
1070 }
1071
1072 #ifndef HAVE_POLLABLE_PROCFS
1073
1074 static void
1075 proc_poll_open()
1076 {
1077         int arg;
1078         int i;
1079
1080         if (pipe(proc_poll_pipe) < 0) {
1081                 perror("pipe");
1082                 exit(1);
1083         }
1084         for (i = 0; i < 2; i++) {
1085                 if ((arg = fcntl(proc_poll_pipe[i], F_GETFD)) < 0) {
1086                         perror("F_GETFD");
1087                         exit(1);
1088                 }
1089                 if (fcntl(proc_poll_pipe[i], F_SETFD, arg|FD_CLOEXEC) < 0) {
1090                         perror("F_SETFD");
1091                         exit(1);
1092                 }
1093         }
1094 }
1095
1096 static int
1097 proc_poll(pollv, nfds, timeout)
1098 struct pollfd *pollv;
1099 int nfds;
1100 int timeout;
1101 {
1102         int i;
1103         int n;
1104         struct proc_pollfd pollinfo;
1105
1106         if ((n = read(proc_poll_pipe[0], &pollinfo, sizeof(pollinfo))) < 0)
1107                 return n;
1108         if (n != sizeof(struct proc_pollfd)) {
1109                 fprintf(stderr, "panic: short read: %d\n", n);
1110                 exit(1);
1111         }
1112         for (i = 0; i < nprocs; i++) {
1113                 if (pollv[i].fd == pollinfo.fd)
1114                         pollv[i].revents = pollinfo.revents;
1115                 else
1116                         pollv[i].revents = 0;
1117         }
1118         poller_pid = pollinfo.pid;
1119         return 1;
1120 }
1121
1122 static void
1123 wakeup_handler(sig)
1124 int sig;
1125 {
1126 }
1127
1128 static void
1129 proc_poller(pfd)
1130 int pfd;
1131 {
1132         struct proc_pollfd pollinfo;
1133         struct sigaction sa;
1134         sigset_t blocked_set, empty_set;
1135         int i;
1136         int n;
1137         struct rlimit rl;
1138
1139         switch (fork()) {
1140         case -1:
1141                 perror("fork");
1142                 _exit(0);
1143         case 0:
1144                 break;
1145         default:
1146                 return;
1147         }
1148
1149         sa.sa_handler = interactive ? SIG_DFL : SIG_IGN;
1150         sa.sa_flags = 0;
1151         sigemptyset(&sa.sa_mask);
1152         sigaction(SIGHUP, &sa, NULL);
1153         sigaction(SIGINT, &sa, NULL);
1154         sigaction(SIGQUIT, &sa, NULL);
1155         sigaction(SIGPIPE, &sa, NULL);
1156         sigaction(SIGTERM, &sa, NULL);
1157         sa.sa_handler = wakeup_handler;
1158         sigaction(SIGUSR1, &sa, NULL);
1159         sigemptyset(&blocked_set);
1160         sigaddset(&blocked_set, SIGUSR1);
1161         sigprocmask(SIG_BLOCK, &blocked_set, NULL);
1162         sigemptyset(&empty_set);
1163
1164         if (getrlimit(RLIMIT_NOFILE, &rl) < 0) {
1165                 perror("getrlimit(RLIMIT_NOFILE, ...)");
1166                 _exit(0);
1167         }
1168         n = rl.rlim_cur;
1169         for (i = 0; i < n; i++) {
1170                 if (i != pfd && i != proc_poll_pipe[1])
1171                         close(i);
1172         }
1173
1174         pollinfo.fd = pfd;
1175         pollinfo.pid = getpid();
1176         for (;;) {
1177                 if (ioctl(pfd, PIOCWSTOP, NULL) < 0)
1178                 {
1179                         switch (errno) {
1180                         case EINTR:
1181                                 continue;
1182                         case EBADF:
1183                                 pollinfo.revents = POLLERR;
1184                                 break;
1185                         case ENOENT:
1186                                 pollinfo.revents = POLLHUP;
1187                                 break;
1188                         default:
1189                                 perror("proc_poller: PIOCWSTOP");
1190                         }
1191                         write(proc_poll_pipe[1], &pollinfo, sizeof(pollinfo));
1192                         _exit(0);
1193                 }
1194                 pollinfo.revents = POLLWANT;
1195                 write(proc_poll_pipe[1], &pollinfo, sizeof(pollinfo));
1196                 sigsuspend(&empty_set);
1197         }
1198 }
1199
1200 #endif /* !HAVE_POLLABLE_PROCFS */
1201
1202 static int
1203 choose_pfd()
1204 {
1205         int i, j;
1206         struct tcb *tcp;
1207
1208         static int last;
1209
1210         if (followfork < 2 &&
1211             last < nprocs && (pollv[last].revents & POLLWANT)) {
1212                 /*
1213                  * The previous process is ready to run again.  We'll
1214                  * let it do so if it is currently in a syscall.  This
1215                  * heuristic improves the readability of the trace.
1216                  */
1217                 tcp = pfd2tcb(pollv[last].fd);
1218                 if (tcp && (tcp->flags & TCB_INSYSCALL))
1219                         return pollv[last].fd;
1220         }
1221
1222         for (i = 0; i < nprocs; i++) {
1223                 /* Let competing children run round robin. */
1224                 j = (i + last + 1) % nprocs;
1225                 if (pollv[j].revents & (POLLHUP | POLLERR)) {
1226                         tcp = pfd2tcb(pollv[j].fd);
1227                         if (!tcp) {
1228                                 fprintf(stderr, "strace: lost proc\n");
1229                                 exit(1);
1230                         }
1231                         droptcb(tcp);
1232                         return -1;
1233                 }
1234                 if (pollv[j].revents & POLLWANT) {
1235                         last = j;
1236                         return pollv[j].fd;
1237                 }
1238         }
1239         fprintf(stderr, "strace: nothing ready\n");
1240         exit(1);
1241 }
1242
1243 static int
1244 trace()
1245 {
1246         struct tcb *tcp;
1247         int pfd;
1248         int what;
1249         int ioctl_result = 0, ioctl_errno = 0;
1250         long arg;
1251
1252         for (;;) {
1253                 if (interactive)
1254                         sigprocmask(SIG_SETMASK, &empty_set, NULL);
1255
1256                 if (nprocs == 0)
1257                         break;
1258
1259                 switch (nprocs) {
1260                 case 1:
1261 #ifndef HAVE_POLLABLE_PROCFS
1262                         if (proc_poll_pipe[0] == -1) {
1263 #endif
1264                                 tcp = pid2tcb(0);
1265                                 if (!tcp)
1266                                         continue;
1267                                 pfd = tcp->pfd;
1268                                 if (pfd == -1)
1269                                         continue;
1270                                 break;
1271 #ifndef HAVE_POLLABLE_PROCFS
1272                         }
1273                         /* fall through ... */
1274 #endif /* !HAVE_POLLABLE_PROCFS */
1275                 default:
1276 #ifdef HAVE_POLLABLE_PROCFS
1277                         if (poll(pollv, nprocs, INFTIM) < 0) {
1278                                 if (interrupted)
1279                                         return 0;
1280                                 continue;
1281                         }
1282 #else /* !HAVE_POLLABLE_PROCFS */
1283                         if (proc_poll(pollv, nprocs, INFTIM) < 0) {
1284                                 if (interrupted)
1285                                         return 0;
1286                                 continue;
1287                         }
1288 #endif /* !HAVE_POLLABLE_PROCFS */
1289                         pfd = choose_pfd();
1290                         if (pfd == -1)
1291                                 continue;
1292                         break;
1293                 }
1294
1295                 /* Look up `pfd' in our table. */
1296                 if ((tcp = pfd2tcb(pfd)) == NULL) {
1297                         fprintf(stderr, "unknown pfd: %u\n", pfd);
1298                         exit(1);
1299                 }
1300                 /* Get the status of the process. */
1301                 if (!interrupted) {
1302                         ioctl_result = IOCTL_WSTOP (tcp);
1303                         ioctl_errno = errno;
1304 #ifndef HAVE_POLLABLE_PROCFS
1305                         if (proc_poll_pipe[0] != -1) {
1306                                 if (ioctl_result < 0)
1307                                         kill(poller_pid, SIGKILL);
1308                                 else
1309                                         kill(poller_pid, SIGUSR1);
1310                         }
1311 #endif /* !HAVE_POLLABLE_PROCFS */
1312                 }
1313                 if (interrupted)
1314                         return 0;
1315
1316                 if (interactive)
1317                         sigprocmask(SIG_BLOCK, &blocked_set, NULL);
1318
1319                 if (ioctl_result < 0) {
1320                         /* Find out what happened if it failed. */
1321                         switch (ioctl_errno) {
1322                         case EINTR:
1323                         case EBADF:
1324                                 continue;
1325                         case ENOENT:
1326                                 droptcb(tcp);
1327                                 continue;
1328                         default:
1329                                 perror("PIOCWSTOP");
1330                                 exit(1);
1331                         }
1332                 }
1333
1334                 /* clear the just started flag */
1335                 tcp->flags &= ~TCB_STARTUP;
1336
1337                 /* set current output file */
1338                 outf = tcp->outf;
1339
1340                 if (cflag) {
1341                         struct timeval stime;
1342
1343                         stime.tv_sec = tcp->status.pr_stime.tv_sec;
1344                         stime.tv_usec = tcp->status.pr_stime.tv_nsec/1000;
1345                         tv_sub(&tcp->dtime, &stime, &tcp->stime);
1346                         tcp->stime = stime;
1347                 }
1348
1349                 what = tcp->status.PR_WHAT;
1350                 switch (tcp->status.PR_WHY) {
1351                 case PR_REQUESTED:
1352                         if (tcp->status.PR_FLAGS & PR_ASLEEP) {
1353                                 tcp->status.PR_WHY = PR_SYSENTRY;
1354                                 if (trace_syscall(tcp) < 0) {
1355                                         fprintf(stderr, "syscall trouble\n");
1356                                         exit(1);
1357                                 }
1358                         }
1359                         break;
1360                 case PR_SYSENTRY:
1361                 case PR_SYSEXIT:
1362                         if (trace_syscall(tcp) < 0) {
1363                                 fprintf(stderr, "syscall trouble\n");
1364                                 exit(1);
1365                         }
1366                         break;
1367                 case PR_SIGNALLED:
1368                         if (!cflag && (qual_flags[what] & QUAL_SIGNAL)) {
1369                                 printleader(tcp);
1370                                 tprintf("--- %s (%s) ---",
1371                                         signame(what), strsignal(what));
1372                                 printtrailer(tcp);
1373                         }
1374                         break;
1375                 case PR_FAULTED:
1376                         if (!cflag && (qual_flags[what] & QUAL_FAULT)) {
1377                                 printleader(tcp);
1378                                 tprintf("=== FAULT %d ===", what);
1379                                 printtrailer(tcp);
1380                         }
1381                         break;
1382                 default:
1383                         fprintf(stderr, "odd stop %d\n", tcp->status.PR_WHY);
1384                         exit(1);
1385                         break;
1386                 }
1387                 arg = 0;
1388                 if (IOCTL (tcp->pfd, PIOCRUN, &arg) < 0) {
1389                         perror("PIOCRUN");
1390                         exit(1);
1391                 }
1392         }
1393         return 0;
1394 }
1395
1396 #else /* !SVR4 */
1397
1398 static int
1399 trace()
1400 {
1401         int pid;
1402         int wait_errno;
1403         int status;
1404         struct tcb *tcp;
1405 #ifdef LINUX
1406         struct rusage ru;
1407 #endif /* LINUX */
1408
1409         while (nprocs != 0) {
1410                 if (interactive)
1411                         sigprocmask(SIG_SETMASK, &empty_set, NULL);
1412 #ifdef LINUX
1413                 pid = wait4(-1, &status, 0, cflag ? &ru : NULL);
1414 #endif /* LINUX */
1415 #ifdef SUNOS4
1416                 pid = wait(&status);
1417 #endif /* SUNOS4 */
1418                 wait_errno = errno;
1419                 if (interactive)
1420                         sigprocmask(SIG_BLOCK, &blocked_set, NULL);
1421
1422                 if (interrupted)
1423                         return 0;
1424
1425                 if (pid == -1) {
1426                         switch (wait_errno) {
1427                         case EINTR:
1428                                 continue;
1429                         case ECHILD:
1430                                 /*
1431                                  * We would like to verify this case
1432                                  * but sometimes a race in Solbourne's
1433                                  * version of SunOS sometimes reports
1434                                  * ECHILD before sending us SIGCHILD.
1435                                  */
1436 #if 0
1437                                 if (nprocs == 0)
1438                                         return 0;
1439                                 fprintf(stderr, "strace: proc miscount\n");
1440                                 exit(1);
1441 #endif
1442                                 return 0;
1443                         default:
1444                                 errno = wait_errno;
1445                                 perror("strace: wait");
1446                                 return -1;
1447                         }
1448                 }
1449                 if (debug)
1450                         fprintf(stderr, " [wait(%#x) = %u]\n", status, pid);
1451
1452                 /* Look up `pid' in our table. */
1453                 if ((tcp = pid2tcb(pid)) == NULL) {
1454                         fprintf(stderr, "unknown pid: %u\n", pid);
1455                         if (WIFSTOPPED(status))
1456                                 ptrace(PTRACE_CONT, pid, (char *) 1, 0);
1457                         exit(1);
1458                 }
1459                 /* set current output file */
1460                 outf = tcp->outf;
1461                 if (cflag) {
1462 #ifdef LINUX
1463                         tv_sub(&tcp->dtime, &ru.ru_stime, &tcp->stime);
1464                         tcp->stime = ru.ru_stime;
1465 #endif /* !LINUX */
1466                 }
1467
1468                 if (tcp->flags & TCB_SUSPENDED) {
1469                         /*
1470                          * Apparently, doing any ptrace() call on a stopped
1471                          * process, provokes the kernel to report the process
1472                          * status again on a subsequent wait(), even if the
1473                          * process has not been actually restarted.
1474                          * Since we have inspected the arguments of suspended
1475                          * processes we end up here testing for this case.
1476                          */
1477                         continue;
1478                 }
1479                 if (WIFSIGNALED(status)) {
1480                         if (!cflag
1481                             && (qual_flags[WTERMSIG(status)] & QUAL_SIGNAL)) {
1482                                 printleader(tcp);
1483                                 tprintf("+++ killed by %s +++",
1484                                         signame(WTERMSIG(status)));
1485                                 printtrailer(tcp);
1486                         }
1487                         droptcb(tcp);
1488                         continue;
1489                 }
1490                 if (WIFEXITED(status)) {
1491                         if (debug)
1492                                 fprintf(stderr, "pid %u exited\n", pid);
1493                         if (tcp->flags & TCB_ATTACHED)
1494                                 fprintf(stderr,
1495                                         "PANIC: attached pid %u exited\n",
1496                                         pid);
1497                         droptcb(tcp);
1498                         continue;
1499                 }
1500                 if (!WIFSTOPPED(status)) {
1501                         fprintf(stderr, "PANIC: pid %u not stopped\n", pid);
1502                         droptcb(tcp);
1503                         continue;
1504                 }
1505                 if (debug)
1506                         fprintf(stderr, "pid %u stopped, [%s]\n",
1507                                 pid, signame(WSTOPSIG(status)));
1508
1509                 if (tcp->flags & TCB_STARTUP) {
1510                         /*
1511                          * This flag is there to keep us in sync.
1512                          * Next time this process stops it should
1513                          * really be entering a system call.
1514                          */
1515                         tcp->flags &= ~TCB_STARTUP;
1516                         if (tcp->flags & TCB_ATTACHED) {
1517                                 /*
1518                                  * Interestingly, the process may stop
1519                                  * with STOPSIG equal to some other signal
1520                                  * than SIGSTOP if we happend to attach
1521                                  * just before the process takes a signal.
1522                                  */
1523                                 if (!WIFSTOPPED(status)) {
1524                                         fprintf(stderr,
1525                                                 "pid %u not stopped\n", pid);
1526                                         detach(tcp, WSTOPSIG(status));
1527                                         continue;
1528                                 }
1529                         }
1530                         else {
1531 #ifdef SUNOS4
1532                                 /* A child of us stopped at exec */
1533                                 if (WSTOPSIG(status) == SIGTRAP && followvfork)
1534                                         fixvfork(tcp);
1535 #endif /* SUNOS4 */
1536                         }
1537                         if (tcp->flags & TCB_BPTSET) {
1538                                 if (clearbpt(tcp) < 0) /* Pretty fatal */ {
1539                                         droptcb(tcp);
1540                                         cleanup();
1541                                         return -1;
1542                                 }
1543                         }
1544                         goto tracing;
1545                 }
1546
1547                 if (WSTOPSIG(status) != SIGTRAP) {
1548                         if (WSTOPSIG(status) == SIGSTOP &&
1549                                         (tcp->flags & TCB_SIGTRAPPED)) {
1550                                 /*
1551                                  * Trapped attempt to block SIGTRAP
1552                                  * Hope we are back in control now.
1553                                  */
1554                                 tcp->flags &= ~(TCB_INSYSCALL | TCB_SIGTRAPPED);
1555                                 if (ptrace(PTRACE_SYSCALL,
1556                                                 pid, (char *) 1, 0) < 0) {
1557                                         perror("trace: ptrace(PTRACE_SYSCALL, ...)");
1558                                         cleanup();
1559                                         return -1;
1560                                 }
1561                                 continue;
1562                         }
1563                         if (!cflag
1564                             && (qual_flags[WSTOPSIG(status)] & QUAL_SIGNAL)) {
1565                                 printleader(tcp);
1566                                 tprintf("--- %s (%s) ---",
1567                                         signame(WSTOPSIG(status)),
1568                                         strsignal(WSTOPSIG(status)));
1569                                 printtrailer(tcp);
1570                         }
1571                         if ((tcp->flags & TCB_ATTACHED) &&
1572                                 !sigishandled(tcp, WSTOPSIG(status))) {
1573                                 detach(tcp, WSTOPSIG(status));
1574                                 continue;
1575                         }
1576                         if (ptrace(PTRACE_SYSCALL, pid, (char *) 1,
1577                                    WSTOPSIG(status)) < 0) {
1578                                 perror("trace: ptrace(PTRACE_SYSCALL, ...)");
1579                                 cleanup();
1580                                 return -1;
1581                         }
1582                         tcp->flags &= ~TCB_SUSPENDED;
1583                         continue;
1584                 }
1585                 if (trace_syscall(tcp) < 0) {
1586                         if (tcp->flags & TCB_ATTACHED)
1587                                 detach(tcp, 0);
1588                         else {
1589                                 ptrace(PTRACE_KILL,
1590                                         tcp->pid, (char *) 1, SIGTERM);
1591                                 droptcb(tcp);
1592                         }
1593                         continue;
1594                 }
1595                 if (tcp->flags & TCB_EXITING) {
1596                         if (tcp->flags & TCB_ATTACHED)
1597                                 detach(tcp, 0);
1598                         else if (ptrace(PTRACE_CONT, pid, (char *) 1, 0) < 0) {
1599                                 perror("strace: ptrace(PTRACE_CONT, ...)");
1600                                 cleanup();
1601                                 return -1;
1602                         }
1603                         continue;
1604                 }
1605                 if (tcp->flags & TCB_SUSPENDED) {
1606                         if (!qflag)
1607                                 fprintf(stderr, "Process %u suspended\n", pid);
1608                         continue;
1609                 }
1610         tracing:
1611                 if (ptrace(PTRACE_SYSCALL, pid, (char *) 1, 0) < 0) {
1612                         perror("trace: ptrace(PTRACE_SYSCALL, ...)");
1613                         cleanup();
1614                         return -1;
1615                 }
1616         }
1617         return 0;
1618 }
1619
1620 #endif /* !SVR4 */
1621
1622 static int curcol;
1623
1624 #ifdef __STDC__
1625 #include <stdarg.h>
1626 #define VA_START(a, b) va_start(a, b)
1627 #else
1628 #include <varargs.h>
1629 #define VA_START(a, b) va_start(a)
1630 #endif
1631
1632 void
1633 #ifdef __STDC__
1634 tprintf(const char *fmt, ...)
1635 #else
1636 tprintf(fmt, va_alist)
1637 char *fmt;
1638 va_dcl
1639 #endif
1640 {
1641         va_list args;
1642
1643         VA_START(args, fmt);
1644         if (outf)
1645                 curcol += vfprintf(outf, fmt, args);
1646         va_end(args);
1647         return;
1648 }
1649
1650 void
1651 printleader(tcp)
1652 struct tcb *tcp;
1653 {
1654         if (tcp_last && (!outfname || followfork < 2 || tcp_last == tcp)) {
1655                 tcp_last->flags |= TCB_REPRINT;
1656                 tprintf(" <unfinished ...>\n");
1657         }
1658         curcol = 0;
1659         if ((followfork == 1 || pflag_seen > 1) && outfname)
1660                 tprintf("%-5d ", tcp->pid);
1661         else if (nprocs > 1 && !outfname)
1662                 tprintf("[pid %5u] ", tcp->pid);
1663         if (tflag) {
1664                 char str[sizeof("HH:MM:SS")];
1665                 struct timeval tv, dtv;
1666                 static struct timeval otv;
1667
1668                 gettimeofday(&tv, NULL);
1669                 if (rflag) {
1670                         if (otv.tv_sec == 0)
1671                                 otv = tv;
1672                         tv_sub(&dtv, &tv, &otv);
1673                         tprintf("%6ld.%06ld ",
1674                                 (long) dtv.tv_sec, (long) dtv.tv_usec);
1675                         otv = tv;
1676                 }
1677                 else if (tflag > 2) {
1678                         tprintf("%ld.%06ld ",
1679                                 (long) tv.tv_sec, (long) tv.tv_usec);
1680                 }
1681                 else {
1682                         time_t local = tv.tv_sec;
1683                         strftime(str, sizeof(str), "%T", localtime(&local));
1684                         if (tflag > 1)
1685                                 tprintf("%s.%06ld ", str, (long) tv.tv_usec);
1686                         else
1687                                 tprintf("%s ", str);
1688                 }
1689         }
1690         if (iflag)
1691                 printcall(tcp);
1692 }
1693
1694 void
1695 tabto(col)
1696 int col;
1697 {
1698         if (curcol < col)
1699                 tprintf("%*s", col - curcol, "");
1700 }
1701
1702 void
1703 printtrailer(tcp)
1704 struct tcb *tcp;
1705 {
1706         tprintf("\n");
1707         tcp_last = NULL;
1708 }
1709
1710 #ifdef SVR4_MP
1711
1712 int mp_ioctl (int fd, int cmd, void *arg, int size) {
1713
1714         struct iovec iov[2];
1715         int n = 1;
1716         
1717         iov[0].iov_base = &cmd;
1718         iov[0].iov_len = sizeof cmd;
1719         if (arg) {
1720                 ++n;
1721                 iov[1].iov_base = arg;
1722                 iov[1].iov_len = size;
1723         }
1724         
1725         return writev (fd, iov, n);
1726 }
1727
1728 #endif