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