xref: /freebsd/usr.bin/truss/main.c (revision 7660b554bc59a07be0431c17e0e33815818baa69)
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 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
34 
35 /*
36  * The main module for truss.  Suprisingly simple, but, then, the other
37  * files handle the bulk of the work.  And, of course, the kernel has to
38  * do a lot of the work :).
39  */
40 
41 #include <sys/param.h>
42 #include <sys/ioctl.h>
43 #include <sys/pioctl.h>
44 #include <sys/time.h>
45 
46 #include <err.h>
47 #include <errno.h>
48 #include <fcntl.h>
49 #include <signal.h>
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <string.h>
53 #include <time.h>
54 #include <unistd.h>
55 
56 #include "truss.h"
57 #include "extern.h"
58 
59 /*
60  * It's difficult to parameterize this because it must be
61  * accessible in a signal handler.
62  */
63 
64 int Procfd;
65 
66 static __inline void
67 usage(void)
68 {
69   fprintf(stderr, "%s\n%s\n",
70 	"usage: truss [-faedDS] [-o file] -p pid",
71 	"       truss [-faedDS] [-o file] command [args]");
72   exit(1);
73 }
74 
75 /*
76  * WARNING! "FreeBSD a.out" must be first, or set_etype will not
77  * work correctly.
78  */
79 struct ex_types {
80   const char *type;
81   void (*enter_syscall)(struct trussinfo *, int);
82   int (*exit_syscall)(struct trussinfo *, int);
83 } ex_types[] = {
84 #ifdef __alpha__
85   { "FreeBSD ELF", alpha_syscall_entry, alpha_syscall_exit },
86 #endif
87 #ifdef __i386__
88   { "FreeBSD a.out", i386_syscall_entry, i386_syscall_exit },
89   { "FreeBSD ELF", i386_syscall_entry, i386_syscall_exit },
90   { "FreeBSD ELF32", i386_syscall_entry, i386_syscall_exit },
91   { "Linux ELF", i386_linux_syscall_entry, i386_linux_syscall_exit },
92 #endif
93 #ifdef __ia64__
94   { "FreeBSD ELF64", ia64_syscall_entry, ia64_syscall_exit },
95 #endif
96 #ifdef __sparc64__
97   { "FreeBSD ELF64", sparc64_syscall_entry, sparc64_syscall_exit },
98 #endif
99   { 0, 0, 0 },
100 };
101 
102 /*
103  * Set the execution type.  This is called after every exec, and when
104  * a process is first monitored.  The procfs pseudo-file "etype" has
105  * the execution module type -- see /proc/curproc/etype for an example.
106  */
107 
108 static struct ex_types *
109 set_etype(struct trussinfo *trussinfo) {
110   struct ex_types *funcs;
111   char etype[24];
112   char progt[32];
113   int fd;
114 
115   sprintf(etype, "/proc/%d/etype", trussinfo->pid);
116   if ((fd = open(etype, O_RDONLY)) == -1) {
117     strcpy(progt, "FreeBSD a.out");
118   } else {
119     int len = read(fd, progt, sizeof(progt));
120     progt[len-1] = '\0';
121     close(fd);
122   }
123 
124   for (funcs = ex_types; funcs->type; funcs++)
125     if (!strcmp(funcs->type, progt))
126       break;
127 
128   if (funcs->type == NULL) {
129     funcs = &ex_types[0];
130     warn("execution type %s is not supported -- using %s",
131       progt, funcs->type);
132   }
133   return funcs;
134 }
135 
136 int
137 main(int ac, char **av) {
138   int c;
139   int i;
140   char **command;
141   struct procfs_status pfs;
142   struct ex_types *funcs;
143   int in_exec = 0;
144   char *fname = NULL;
145   int sigexit = 0;
146   struct trussinfo *trussinfo;
147 
148   /* Initialize the trussinfo struct */
149   trussinfo = (struct trussinfo *)malloc(sizeof(struct trussinfo));
150   if (trussinfo == NULL)
151     errx(1, "malloc() failed");
152   bzero(trussinfo, sizeof(struct trussinfo));
153   trussinfo->outfile = stderr;
154 
155   while ((c = getopt(ac, av, "p:o:faedDS")) != -1) {
156     switch (c) {
157     case 'p':	/* specified pid */
158       trussinfo->pid = atoi(optarg);
159       break;
160     case 'f': /* Follow fork()'s */
161       trussinfo->flags |= FOLLOWFORKS;
162       break;
163     case 'a': /* Print execve() argument strings. */
164       trussinfo->flags |= EXECVEARGS;
165       break;
166     case 'e': /* Print execve() environment strings. */
167       trussinfo->flags |= EXECVEENVS;
168       break;
169     case 'd': /* Absolute timestamps */
170       trussinfo->flags |= ABSOLUTETIMESTAMPS;
171       break;
172     case 'D': /* Relative timestamps */
173       trussinfo->flags |= RELATIVETIMESTAMPS;
174       break;
175     case 'o':	/* Specified output file */
176       fname = optarg;
177       break;
178     case 'S':	/* Don't trace signals */
179       trussinfo->flags |= NOSIGS;
180       break;
181     default:
182       usage();
183     }
184   }
185 
186   ac -= optind; av += optind;
187   if ((trussinfo->pid == 0 && ac == 0) || (trussinfo->pid != 0 && ac != 0))
188     usage();
189 
190   if (fname != NULL) { /* Use output file */
191     if ((trussinfo->outfile = fopen(fname, "w")) == NULL)
192       errx(1, "cannot open %s", fname);
193   }
194 
195   /*
196    * If truss starts the process itself, it will ignore some signals --
197    * they should be passed off to the process, which may or may not
198    * exit.  If, however, we are examining an already-running process,
199    * then we restore the event mask on these same signals.
200    */
201 
202   if (trussinfo->pid == 0) {	/* Start a command ourselves */
203     command = av;
204     trussinfo->pid = setup_and_wait(command);
205     signal(SIGINT, SIG_IGN);
206     signal(SIGTERM, SIG_IGN);
207     signal(SIGQUIT, SIG_IGN);
208   } else {
209     signal(SIGINT, restore_proc);
210     signal(SIGTERM, restore_proc);
211     signal(SIGQUIT, restore_proc);
212   }
213 
214 
215   /*
216    * At this point, if we started the process, it is stopped waiting to
217    * be woken up, either in exit() or in execve().
218    */
219 
220 START_TRACE:
221   Procfd = start_tracing(
222 		trussinfo->pid, S_EXEC | S_SCE | S_SCX | S_CORE | S_EXIT |
223 		((trussinfo->flags & NOSIGS) ? 0 : S_SIG),
224 		((trussinfo->flags & FOLLOWFORKS) ? PF_FORK : 0));
225   if (Procfd == -1)
226     return 0;
227 
228   pfs.why = 0;
229 
230   funcs = set_etype(trussinfo);
231   /*
232    * At this point, it's a simple loop, waiting for the process to
233    * stop, finding out why, printing out why, and then continuing it.
234    * All of the grunt work is done in the support routines.
235    */
236 
237   clock_gettime(CLOCK_REALTIME, &trussinfo->start_time);
238 
239   do {
240     int val = 0;
241 
242     if (ioctl(Procfd, PIOCWAIT, &pfs) == -1)
243       warn("PIOCWAIT top of loop");
244     else {
245       switch(i = pfs.why) {
246       case S_SCE:
247 	funcs->enter_syscall(trussinfo, pfs.val);
248 	clock_gettime(CLOCK_REALTIME, &trussinfo->before);
249 	break;
250       case S_SCX:
251 	clock_gettime(CLOCK_REALTIME, &trussinfo->after);
252 	/*
253 	 * This is so we don't get two messages for an exec -- one
254 	 * for the S_EXEC, and one for the syscall exit.  It also,
255 	 * conveniently, ensures that the first message printed out
256 	 * isn't the return-from-syscall used to create the process.
257 	 */
258 
259 	if (in_exec) {
260 	  in_exec = 0;
261 	  break;
262 	}
263 
264 	if (trussinfo->in_fork && (trussinfo->flags & FOLLOWFORKS)) {
265 	  int childpid;
266 
267 	  trussinfo->in_fork = 0;
268 	  childpid = funcs->exit_syscall(trussinfo, pfs.val);
269 
270 	  /*
271 	   * Fork a new copy of ourself to trace the child of the
272 	   * original traced process.
273 	   */
274 	  if (fork() == 0) {
275 	    trussinfo->pid = childpid;
276 	    goto START_TRACE;
277 	  }
278 	  break;
279 	}
280 	funcs->exit_syscall(trussinfo, pfs.val);
281 	break;
282       case S_SIG:
283 	fprintf(trussinfo->outfile, "SIGNAL %lu\n", pfs.val);
284 	sigexit = pfs.val;
285 	break;
286       case S_EXIT:
287 	fprintf (trussinfo->outfile, "process exit, rval = %lu\n", pfs.val);
288 	break;
289       case S_EXEC:
290 	funcs = set_etype(trussinfo);
291 	in_exec = 1;
292 	break;
293       default:
294 	fprintf (trussinfo->outfile, "Process stopped because of:  %d\n", i);
295 	break;
296       }
297     }
298     if (ioctl(Procfd, PIOCCONT, val) == -1) {
299       if (kill(trussinfo->pid, 0) == -1 && errno == ESRCH)
300 	break;
301       else
302 	warn("PIOCCONT");
303     }
304   } while (pfs.why != S_EXIT);
305   fflush(trussinfo->outfile);
306   if (sigexit) {
307     if (sigexit == SIGQUIT)
308       exit(sigexit);
309     (void) signal(sigexit, SIG_DFL);
310     (void) kill(getpid(), sigexit);
311   }
312   return 0;
313 }
314