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