main.c revision 240005
1/*-
2 * Copyright 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 240005 2012-09-02 11:03:18Z zont $");
34
35/*
36 * The main module for truss.  Surprisingly 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/types.h>
43#include <sys/time.h>
44#include <sys/resource.h>
45#include <sys/sysctl.h>
46#include <sys/wait.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#include "syscall.h"
61
62#define	MAXARGS	6
63
64static void
65usage(void)
66{
67	fprintf(stderr, "%s\n%s\n",
68	    "usage: truss [-cfaedDS] [-o file] [-s strsize] -p pid",
69	    "       truss [-cfaedDS] [-o file] [-s strsize] command [args]");
70	exit(1);
71}
72
73/*
74 * WARNING! "FreeBSD a.out" must be first, or set_etype will not
75 * work correctly.
76 */
77static struct ex_types {
78	const char *type;
79	void (*enter_syscall)(struct trussinfo *, int);
80	long (*exit_syscall)(struct trussinfo *, int);
81} ex_types[] = {
82#ifdef __amd64__
83	{ "FreeBSD ELF64", amd64_syscall_entry, amd64_syscall_exit },
84	{ "FreeBSD ELF32", amd64_fbsd32_syscall_entry, amd64_fbsd32_syscall_exit },
85	{ "Linux ELF32", amd64_linux32_syscall_entry, amd64_linux32_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 __powerpc__
97	{ "FreeBSD ELF", powerpc_syscall_entry, powerpc_syscall_exit },
98	{ "FreeBSD ELF32", powerpc_syscall_entry, powerpc_syscall_exit },
99#ifdef __powerpc64__
100	{ "FreeBSD ELF64", powerpc64_syscall_entry, powerpc64_syscall_exit },
101#endif
102#endif
103#ifdef __sparc64__
104	{ "FreeBSD ELF64", sparc64_syscall_entry, sparc64_syscall_exit },
105#endif
106#ifdef __mips__
107	{ "FreeBSD ELF", mips_syscall_entry, mips_syscall_exit },
108	{ "FreeBSD ELF32", mips_syscall_entry, mips_syscall_exit },
109	{ "FreeBSD ELF64", mips_syscall_entry, mips_syscall_exit }, // XXX
110#endif
111	{ 0, 0, 0 },
112};
113
114/*
115 * Set the execution type.  This is called after every exec, and when
116 * a process is first monitored.
117 */
118
119static struct ex_types *
120set_etype(struct trussinfo *trussinfo)
121{
122	struct ex_types *funcs;
123	size_t len;
124	int error;
125	int mib[4];
126	char progt[32];
127
128	len = sizeof(progt);
129	mib[0] = CTL_KERN;
130	mib[1] = KERN_PROC;
131	mib[2] = KERN_PROC_SV_NAME;
132	mib[3] = trussinfo->pid;
133	error = sysctl(mib, 4, progt, &len, NULL, 0);
134	if (error != 0)
135		err(2, "can not get etype");
136
137	for (funcs = ex_types; funcs->type; funcs++)
138		if (strcmp(funcs->type, progt) == 0)
139			break;
140
141	if (funcs->type == NULL) {
142		funcs = &ex_types[0];
143		warn("execution type %s is not supported -- using %s",
144		    progt, funcs->type);
145	}
146	return (funcs);
147}
148
149char *
150strsig(int sig)
151{
152	char *ret;
153
154	ret = NULL;
155	if (sig > 0 && sig < NSIG) {
156		asprintf(&ret, "SIG%s", sys_signame[sig]);
157		if (ret == NULL)
158			return (NULL);
159	}
160	return (ret);
161}
162
163int
164main(int ac, char **av)
165{
166	struct ex_types *funcs;
167	struct trussinfo *trussinfo;
168	char *fname;
169	char *signame;
170	char **command;
171	pid_t childpid;
172	int c, i, initial_open, status;
173
174	fname = NULL;
175	initial_open = 1;
176
177	/* Initialize the trussinfo struct */
178	trussinfo = (struct trussinfo *)calloc(1, sizeof(struct trussinfo));
179	if (trussinfo == NULL)
180		errx(1, "calloc() failed");
181
182	trussinfo->outfile = stderr;
183	trussinfo->strsize = 32;
184	trussinfo->pr_why = S_NONE;
185	trussinfo->curthread = NULL;
186	SLIST_INIT(&trussinfo->threadlist);
187	while ((c = getopt(ac, av, "p:o:facedDs:S")) != -1) {
188		switch (c) {
189		case 'p':	/* specified pid */
190			trussinfo->pid = atoi(optarg);
191			/* make sure i don't trace me */
192			if (trussinfo->pid == getpid()) {
193				fprintf(stderr, "attempt to grab self.\n");
194				exit(2);
195			}
196			break;
197		case 'f': /* Follow fork()'s */
198			trussinfo->flags |= FOLLOWFORKS;
199			break;
200		case 'a': /* Print execve() argument strings. */
201			trussinfo->flags |= EXECVEARGS;
202			break;
203		case 'c': /* Count number of system calls and time. */
204			trussinfo->flags |= COUNTONLY;
205			break;
206		case 'e': /* Print execve() environment strings. */
207			trussinfo->flags |= EXECVEENVS;
208			break;
209		case 'd': /* Absolute timestamps */
210			trussinfo->flags |= ABSOLUTETIMESTAMPS;
211			break;
212		case 'D': /* Relative timestamps */
213			trussinfo->flags |= RELATIVETIMESTAMPS;
214			break;
215		case 'o':	/* Specified output file */
216			fname = optarg;
217			break;
218		case 's':	/* Specified string size */
219			trussinfo->strsize = atoi(optarg);
220			break;
221		case 'S':	/* Don't trace signals */
222			trussinfo->flags |= NOSIGS;
223			break;
224		default:
225			usage();
226		}
227	}
228
229	ac -= optind; av += optind;
230	if ((trussinfo->pid == 0 && ac == 0) ||
231	    (trussinfo->pid != 0 && ac != 0))
232		usage();
233
234	if (fname != NULL) { /* Use output file */
235		if ((trussinfo->outfile = fopen(fname, "w")) == NULL)
236			errx(1, "cannot open %s", fname);
237		/*
238		 * Set FD_CLOEXEC, so that the output file is not shared with
239		 * the traced process.
240		 */
241		if (fcntl(fileno(trussinfo->outfile), F_SETFD, FD_CLOEXEC) ==
242		    -1)
243			warn("fcntl()");
244	}
245
246	/*
247	 * If truss starts the process itself, it will ignore some signals --
248	 * they should be passed off to the process, which may or may not
249	 * exit.  If, however, we are examining an already-running process,
250	 * then we restore the event mask on these same signals.
251	 */
252
253	if (trussinfo->pid == 0) {	/* Start a command ourselves */
254		command = av;
255		trussinfo->pid = setup_and_wait(command);
256		signal(SIGINT, SIG_IGN);
257		signal(SIGTERM, SIG_IGN);
258		signal(SIGQUIT, SIG_IGN);
259	} else {
260		start_tracing(trussinfo->pid);
261		signal(SIGINT, restore_proc);
262		signal(SIGTERM, restore_proc);
263		signal(SIGQUIT, restore_proc);
264	}
265
266
267	/*
268	 * At this point, if we started the process, it is stopped waiting to
269	 * be woken up, either in exit() or in execve().
270	 */
271
272START_TRACE:
273	funcs = set_etype(trussinfo);
274
275	initial_open = 0;
276	/*
277	 * At this point, it's a simple loop, waiting for the process to
278	 * stop, finding out why, printing out why, and then continuing it.
279	 * All of the grunt work is done in the support routines.
280	 */
281
282	clock_gettime(CLOCK_REALTIME, &trussinfo->start_time);
283
284	do {
285		struct timespec timediff;
286		waitevent(trussinfo);
287
288		switch (i = trussinfo->pr_why) {
289		case S_SCE:
290			funcs->enter_syscall(trussinfo, MAXARGS);
291			clock_gettime(CLOCK_REALTIME,
292			    &trussinfo->before);
293			break;
294		case S_SCX:
295			clock_gettime(CLOCK_REALTIME,
296			    &trussinfo->after);
297
298			if (trussinfo->curthread->in_fork &&
299			    (trussinfo->flags & FOLLOWFORKS)) {
300				trussinfo->curthread->in_fork = 0;
301				childpid = funcs->exit_syscall(trussinfo,
302				    trussinfo->pr_data);
303
304				/*
305				 * Fork a new copy of ourself to trace
306				 * the child of the original traced
307				 * process.
308				 */
309				if (fork() == 0) {
310					trussinfo->pid = childpid;
311					start_tracing(trussinfo->pid);
312					goto START_TRACE;
313				}
314				break;
315			}
316			funcs->exit_syscall(trussinfo, MAXARGS);
317			break;
318		case S_SIG:
319			if (trussinfo->flags & NOSIGS)
320				break;
321			if (trussinfo->flags & FOLLOWFORKS)
322				fprintf(trussinfo->outfile, "%5d: ",
323				    trussinfo->pid);
324			if (trussinfo->flags & ABSOLUTETIMESTAMPS) {
325				timespecsubt(&trussinfo->after,
326				    &trussinfo->start_time, &timediff);
327				fprintf(trussinfo->outfile, "%ld.%09ld ",
328				    (long)timediff.tv_sec,
329				    timediff.tv_nsec);
330			}
331			if (trussinfo->flags & RELATIVETIMESTAMPS) {
332				timespecsubt(&trussinfo->after,
333				    &trussinfo->before, &timediff);
334				fprintf(trussinfo->outfile, "%ld.%09ld ",
335				    (long)timediff.tv_sec,
336				    timediff.tv_nsec);
337			}
338			signame = strsig(trussinfo->pr_data);
339			fprintf(trussinfo->outfile,
340			    "SIGNAL %u (%s)\n", trussinfo->pr_data,
341			    signame == NULL ? "?" : signame);
342			free(signame);
343			break;
344		case S_EXIT:
345			if (trussinfo->flags & COUNTONLY)
346				break;
347			if (trussinfo->flags & FOLLOWFORKS)
348				fprintf(trussinfo->outfile, "%5d: ",
349				    trussinfo->pid);
350			if (trussinfo->flags & ABSOLUTETIMESTAMPS) {
351				timespecsubt(&trussinfo->after,
352				    &trussinfo->start_time, &timediff);
353				fprintf(trussinfo->outfile, "%ld.%09ld ",
354				    (long)timediff.tv_sec,
355				    timediff.tv_nsec);
356			}
357			if (trussinfo->flags & RELATIVETIMESTAMPS) {
358				timespecsubt(&trussinfo->after,
359				    &trussinfo->before, &timediff);
360				fprintf(trussinfo->outfile, "%ld.%09ld ",
361				    (long)timediff.tv_sec, timediff.tv_nsec);
362			}
363			fprintf(trussinfo->outfile,
364			    "process exit, rval = %u\n", trussinfo->pr_data);
365			break;
366		default:
367			break;
368		}
369	} while (trussinfo->pr_why != S_EXIT);
370
371	if (trussinfo->flags & FOLLOWFORKS) {
372		do {
373			childpid = wait(&status);
374		} while (childpid != -1);
375	}
376
377	if (trussinfo->flags & COUNTONLY)
378		print_summary(trussinfo);
379
380	fflush(trussinfo->outfile);
381
382	return (0);
383}
384