xref: /freebsd/usr.bin/truss/main.c (revision a3e8fd0b7f663db7eafff527d5c3ca3bcfa8a537)
1 /*
2  * Copryight 1997 Sean Eric Fagan
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  * 3. All advertising materials mentioning features or use of this software
13  *    must display the following acknowledgement:
14  *	This product includes software developed by Sean Eric Fagan
15  * 4. Neither the name of the author may be used to endorse or promote
16  *    products derived from this software without specific prior written
17  *    permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #ifndef lint
33 static const char rcsid[] =
34   "$FreeBSD$";
35 #endif /* not lint */
36 
37 /*
38  * The main module for truss.  Suprisingly simple, but, then, the other
39  * files handle the bulk of the work.  And, of course, the kernel has to
40  * do a lot of the work :).
41  */
42 
43 #include <sys/param.h>
44 #include <sys/ioctl.h>
45 #include <sys/pioctl.h>
46 #include <sys/time.h>
47 
48 #include <err.h>
49 #include <errno.h>
50 #include <fcntl.h>
51 #include <signal.h>
52 #include <stdio.h>
53 #include <stdlib.h>
54 #include <string.h>
55 #include <time.h>
56 #include <unistd.h>
57 
58 #include "truss.h"
59 #include "extern.h"
60 
61 /*
62  * It's difficult to parameterize this because it must be
63  * accessible in a signal handler.
64  */
65 
66 int Procfd;
67 
68 static __inline void
69 usage(void)
70 {
71   fprintf(stderr, "%s\n%s\n",
72 	"usage: truss [-faedDS] [-o file] -p pid",
73 	"       truss [-faedDS] [-o file] command [args]");
74   exit(1);
75 }
76 
77 /*
78  * WARNING! "FreeBSD a.out" must be first, or set_etype will not
79  * work correctly.
80  */
81 struct ex_types {
82   const char *type;
83   void (*enter_syscall)(struct trussinfo *, int);
84   int (*exit_syscall)(struct trussinfo *, int);
85 } ex_types[] = {
86 #ifdef __alpha__
87   { "FreeBSD ELF", alpha_syscall_entry, alpha_syscall_exit },
88 #endif
89 #ifdef __i386__
90   { "FreeBSD a.out", i386_syscall_entry, i386_syscall_exit },
91   { "FreeBSD ELF", i386_syscall_entry, i386_syscall_exit },
92   { "FreeBSD ELF32", i386_syscall_entry, i386_syscall_exit },
93   { "Linux ELF", i386_linux_syscall_entry, i386_linux_syscall_exit },
94 #endif
95 #ifdef __sparc64__
96   { "FreeBSD ELF64", sparc64_syscall_entry, sparc64_syscall_exit },
97 #endif
98   { 0, 0, 0 },
99 };
100 
101 /*
102  * Set the execution type.  This is called after every exec, and when
103  * a process is first monitored.  The procfs pseudo-file "etype" has
104  * the execution module type -- see /proc/curproc/etype for an example.
105  */
106 
107 static struct ex_types *
108 set_etype(struct trussinfo *trussinfo) {
109   struct ex_types *funcs;
110   char etype[24];
111   char progt[32];
112   int fd;
113 
114   sprintf(etype, "/proc/%d/etype", trussinfo->pid);
115   if ((fd = open(etype, O_RDONLY)) == -1) {
116     strcpy(progt, "FreeBSD a.out");
117   } else {
118     int len = read(fd, progt, sizeof(progt));
119     progt[len-1] = '\0';
120     close(fd);
121   }
122 
123   for (funcs = ex_types; funcs->type; funcs++)
124     if (!strcmp(funcs->type, progt))
125       break;
126 
127   if (funcs->type == NULL) {
128     funcs = &ex_types[0];
129     warn("Execution type %s is not supported -- using %s\n",
130       progt, funcs->type);
131   }
132   return funcs;
133 }
134 
135 int
136 main(int ac, char **av) {
137   int c;
138   int i;
139   char **command;
140   struct procfs_status pfs;
141   struct ex_types *funcs;
142   int in_exec = 0;
143   char *fname = NULL;
144   int sigexit = 0;
145   struct trussinfo *trussinfo;
146 
147   /* Initialize the trussinfo struct */
148   trussinfo = (struct trussinfo *)malloc(sizeof(struct trussinfo));
149   if (trussinfo == NULL)
150     errx(1, "malloc() failed");
151   bzero(trussinfo, sizeof(struct trussinfo));
152   trussinfo->outfile = stderr;
153 
154   while ((c = getopt(ac, av, "p:o:faedDS")) != -1) {
155     switch (c) {
156     case 'p':	/* specified pid */
157       trussinfo->pid = atoi(optarg);
158       break;
159     case 'f': /* Follow fork()'s */
160       trussinfo->flags |= FOLLOWFORKS;
161       break;
162     case 'a': /* Print execve() argument strings. */
163       trussinfo->flags |= EXECVEARGS;
164       break;
165     case 'e': /* Print execve() environment strings. */
166       trussinfo->flags |= EXECVEENVS;
167       break;
168     case 'd': /* Absolute timestamps */
169       trussinfo->flags |= ABSOLUTETIMESTAMPS;
170       break;
171     case 'D': /* Relative timestamps */
172       trussinfo->flags |= RELATIVETIMESTAMPS;
173       break;
174     case 'o':	/* Specified output file */
175       fname = optarg;
176       break;
177     case 'S':	/* Don't trace signals */
178       trussinfo->flags |= NOSIGS;
179       break;
180     default:
181       usage();
182     }
183   }
184 
185   ac -= optind; av += optind;
186   if ((trussinfo->pid == 0 && ac == 0) || (trussinfo->pid != 0 && ac != 0))
187     usage();
188 
189   if (fname != NULL) { /* Use output file */
190     if ((trussinfo->outfile = fopen(fname, "w")) == NULL)
191       errx(1, "cannot open %s", fname);
192   }
193 
194   /*
195    * If truss starts the process itself, it will ignore some signals --
196    * they should be passed off to the process, which may or may not
197    * exit.  If, however, we are examining an already-running process,
198    * then we restore the event mask on these same signals.
199    */
200 
201   if (trussinfo->pid == 0) {	/* Start a command ourselves */
202     command = av;
203     trussinfo->pid = setup_and_wait(command);
204     signal(SIGINT, SIG_IGN);
205     signal(SIGTERM, SIG_IGN);
206     signal(SIGQUIT, SIG_IGN);
207   } else {
208     signal(SIGINT, restore_proc);
209     signal(SIGTERM, restore_proc);
210     signal(SIGQUIT, restore_proc);
211   }
212 
213 
214   /*
215    * At this point, if we started the process, it is stopped waiting to
216    * be woken up, either in exit() or in execve().
217    */
218 
219 START_TRACE:
220   Procfd = start_tracing(
221 		trussinfo->pid, S_EXEC | S_SCE | S_SCX | S_CORE | S_EXIT |
222 		((trussinfo->flags & NOSIGS) ? 0 : S_SIG),
223 		((trussinfo->flags & FOLLOWFORKS) ? PF_FORK : 0));
224   if (Procfd == -1)
225     return 0;
226 
227   pfs.why = 0;
228 
229   funcs = set_etype(trussinfo);
230   /*
231    * At this point, it's a simple loop, waiting for the process to
232    * stop, finding out why, printing out why, and then continuing it.
233    * All of the grunt work is done in the support routines.
234    */
235 
236   clock_gettime(CLOCK_REALTIME, &trussinfo->start_time);
237 
238   do {
239     int val = 0;
240 
241     if (ioctl(Procfd, PIOCWAIT, &pfs) == -1)
242       warn("PIOCWAIT top of loop");
243     else {
244       switch(i = pfs.why) {
245       case S_SCE:
246 	funcs->enter_syscall(trussinfo, pfs.val);
247 	clock_gettime(CLOCK_REALTIME, &trussinfo->before);
248 	break;
249       case S_SCX:
250 	clock_gettime(CLOCK_REALTIME, &trussinfo->after);
251 	/*
252 	 * This is so we don't get two messages for an exec -- one
253 	 * for the S_EXEC, and one for the syscall exit.  It also,
254 	 * conveniently, ensures that the first message printed out
255 	 * isn't the return-from-syscall used to create the process.
256 	 */
257 
258 	if (in_exec) {
259 	  in_exec = 0;
260 	  break;
261 	}
262 
263 	if (trussinfo->in_fork && (trussinfo->flags & FOLLOWFORKS)) {
264 	  int childpid;
265 
266 	  trussinfo->in_fork = 0;
267 	  childpid = funcs->exit_syscall(trussinfo, pfs.val);
268 
269 	  /*
270 	   * Fork a new copy of ourself to trace the child of the
271 	   * original traced process.
272 	   */
273 	  if (fork() == 0) {
274 	    trussinfo->pid = childpid;
275 	    goto START_TRACE;
276 	  }
277 	  break;
278 	}
279 	funcs->exit_syscall(trussinfo, pfs.val);
280 	break;
281       case S_SIG:
282 	fprintf(trussinfo->outfile, "SIGNAL %lu\n", pfs.val);
283 	sigexit = pfs.val;
284 	break;
285       case S_EXIT:
286 	fprintf (trussinfo->outfile, "process exit, rval = %lu\n", pfs.val);
287 	break;
288       case S_EXEC:
289 	funcs = set_etype(trussinfo);
290 	in_exec = 1;
291 	break;
292       default:
293 	fprintf (trussinfo->outfile, "Process stopped because of:  %d\n", i);
294 	break;
295       }
296     }
297     if (ioctl(Procfd, PIOCCONT, val) == -1) {
298       if (kill(trussinfo->pid, 0) == -1 && errno == ESRCH)
299 	break;
300       else
301 	warn("PIOCCONT");
302     }
303   } while (pfs.why != S_EXIT);
304   fflush(trussinfo->outfile);
305   if (sigexit) {
306     if (sigexit == SIGQUIT)
307       exit(sigexit);
308     (void) signal(sigexit, SIG_DFL);
309     (void) kill(getpid(), sigexit);
310   }
311   return 0;
312 }
313