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