main.c revision 101288
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
33static const char rcsid[] =
34  "$FreeBSD: head/usr.bin/truss/main.c 101288 2002-08-04 02:20:06Z mdodd $";
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
47#include <err.h>
48#include <errno.h>
49#include <fcntl.h>
50#include <signal.h>
51#include <stdio.h>
52#include <stdlib.h>
53#include <string.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
64int Procfd;
65
66static __inline void
67usage(void)
68{
69  fprintf(stderr, "%s\n%s\n",
70	"usage: truss [-fdDS] [-o file] -p pid",
71	"       truss [-fdDS] [-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 */
79struct 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  { 0, 0, 0 },
94};
95
96/*
97 * Set the execution type.  This is called after every exec, and when
98 * a process is first monitored.  The procfs pseudo-file "etype" has
99 * the execution module type -- see /proc/curproc/etype for an example.
100 */
101
102static struct ex_types *
103set_etype(struct trussinfo *trussinfo) {
104  struct ex_types *funcs;
105  char etype[24];
106  char progt[32];
107  int fd;
108
109  sprintf(etype, "/proc/%d/etype", trussinfo->pid);
110  if ((fd = open(etype, O_RDONLY)) == -1) {
111    strcpy(progt, "FreeBSD a.out");
112  } else {
113    int len = read(fd, progt, sizeof(progt));
114    progt[len-1] = '\0';
115    close(fd);
116  }
117
118  for (funcs = ex_types; funcs->type; funcs++)
119    if (!strcmp(funcs->type, progt))
120      break;
121
122  if (funcs->type == NULL) {
123    funcs = &ex_types[0];
124    warn("Execution type %s is not supported -- using %s\n",
125      progt, funcs->type);
126  }
127  return funcs;
128}
129
130int
131main(int ac, char **av) {
132  int c;
133  int i;
134  char **command;
135  struct procfs_status pfs;
136  struct ex_types *funcs;
137  int in_exec = 0;
138  char *fname = NULL;
139  int sigexit = 0;
140  struct trussinfo *trussinfo;
141
142  /* Initialize the trussinfo struct */
143  trussinfo = (struct trussinfo *)malloc(sizeof(struct trussinfo));
144  if (trussinfo == NULL)
145    errx(1, "malloc() failed");
146  bzero(trussinfo, sizeof(struct trussinfo));
147  trussinfo->outfile = stderr;
148
149  while ((c = getopt(ac, av, "p:o:fdDS")) != -1) {
150    switch (c) {
151    case 'p':	/* specified pid */
152      trussinfo->pid = atoi(optarg);
153      break;
154    case 'f': /* Follow fork()'s */
155      trussinfo->flags |= FOLLOWFORKS;
156      break;
157    case 'd': /* Absolute timestamps */
158      trussinfo->flags |= ABSOLUTETIMESTAMPS;
159      break;
160    case 'D': /* Relative timestamps */
161      trussinfo->flags |= RELATIVETIMESTAMPS;
162      break;
163    case 'o':	/* Specified output file */
164      fname = optarg;
165      break;
166    case 'S':	/* Don't trace signals */
167      trussinfo->flags |= NOSIGS;
168      break;
169    default:
170      usage();
171    }
172  }
173
174  ac -= optind; av += optind;
175  if ((trussinfo->pid == 0 && ac == 0) || (trussinfo->pid != 0 && ac != 0))
176    usage();
177
178  if (fname != NULL) { /* Use output file */
179    if ((trussinfo->outfile = fopen(fname, "w")) == NULL)
180      errx(1, "cannot open %s", fname);
181  }
182
183  /*
184   * If truss starts the process itself, it will ignore some signals --
185   * they should be passed off to the process, which may or may not
186   * exit.  If, however, we are examining an already-running process,
187   * then we restore the event mask on these same signals.
188   */
189
190  if (trussinfo->pid == 0) {	/* Start a command ourselves */
191    command = av;
192    trussinfo->pid = setup_and_wait(command);
193    signal(SIGINT, SIG_IGN);
194    signal(SIGTERM, SIG_IGN);
195    signal(SIGQUIT, SIG_IGN);
196  } else {
197    signal(SIGINT, restore_proc);
198    signal(SIGTERM, restore_proc);
199    signal(SIGQUIT, restore_proc);
200  }
201
202
203  /*
204   * At this point, if we started the process, it is stopped waiting to
205   * be woken up, either in exit() or in execve().
206   */
207
208START_TRACE:
209  Procfd = start_tracing(
210		trussinfo->pid, S_EXEC | S_SCE | S_SCX | S_CORE | S_EXIT |
211		((trussinfo->flags & NOSIGS) ? 0 : S_SIG),
212		((trussinfo->flags & FOLLOWFORKS) ? PF_FORK : 0));
213  if (Procfd == -1)
214    return 0;
215
216  pfs.why = 0;
217
218  funcs = set_etype(trussinfo);
219  /*
220   * At this point, it's a simple loop, waiting for the process to
221   * stop, finding out why, printing out why, and then continuing it.
222   * All of the grunt work is done in the support routines.
223   */
224
225  gettimeofday(&trussinfo->start_time, (struct timezone *)NULL);
226
227  do {
228    int val = 0;
229
230    if (ioctl(Procfd, PIOCWAIT, &pfs) == -1)
231      warn("PIOCWAIT top of loop");
232    else {
233      switch(i = pfs.why) {
234      case S_SCE:
235	funcs->enter_syscall(trussinfo, pfs.val);
236	gettimeofday(&trussinfo->before, (struct timezone *)NULL);
237	break;
238      case S_SCX:
239	gettimeofday(&trussinfo->after, (struct timezone *)NULL);
240	/*
241	 * This is so we don't get two messages for an exec -- one
242	 * for the S_EXEC, and one for the syscall exit.  It also,
243	 * conveniently, ensures that the first message printed out
244	 * isn't the return-from-syscall used to create the process.
245	 */
246
247	if (in_exec) {
248	  in_exec = 0;
249	  break;
250	}
251
252	if (trussinfo->in_fork && (trussinfo->flags & FOLLOWFORKS)) {
253	  int childpid;
254
255	  trussinfo->in_fork = 0;
256	  childpid = funcs->exit_syscall(trussinfo, pfs.val);
257
258	  /*
259	   * Fork a new copy of ourself to trace the child of the
260	   * original traced process.
261	   */
262	  if (fork() == 0) {
263	    trussinfo->pid = childpid;
264	    goto START_TRACE;
265	  }
266	  break;
267	}
268	funcs->exit_syscall(trussinfo, pfs.val);
269	break;
270      case S_SIG:
271	fprintf(trussinfo->outfile, "SIGNAL %lu\n", pfs.val);
272	sigexit = pfs.val;
273	break;
274      case S_EXIT:
275	fprintf (trussinfo->outfile, "process exit, rval = %lu\n", pfs.val);
276	break;
277      case S_EXEC:
278	funcs = set_etype(trussinfo);
279	in_exec = 1;
280	break;
281      default:
282	fprintf (trussinfo->outfile, "Process stopped because of:  %d\n", i);
283	break;
284      }
285    }
286    if (ioctl(Procfd, PIOCCONT, val) == -1) {
287      if (kill(trussinfo->pid, 0) == -1 && errno == ESRCH)
288	break;
289      else
290	warn("PIOCCONT");
291    }
292  } while (pfs.why != S_EXIT);
293  fflush(trussinfo->outfile);
294  if (sigexit) {
295    if (sigexit == SIGQUIT)
296      exit(sigexit);
297    (void) signal(sigexit, SIG_DFL);
298    (void) kill(getpid(), sigexit);
299  }
300  return 0;
301}
302