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