xref: /freebsd/usr.bin/truss/main.c (revision f9bc005b8ef3b507a5ecbc2d7fe4411ef70eff38)
1 /*-
2  * SPDX-License-Identifier: BSD-4-Clause
3  *
4  * Copyright 1997 Sean Eric Fagan
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 3. All advertising materials mentioning features or use of this software
15  *    must display the following acknowledgement:
16  *	This product includes software developed by Sean Eric Fagan
17  * 4. Neither the name of the author may be used to endorse or promote
18  *    products derived from this software without specific prior written
19  *    permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 /*
35  * The main module for truss.  Surprisingly simple, but, then, the other
36  * files handle the bulk of the work.  And, of course, the kernel has to
37  * do a lot of the work :).
38  */
39 
40 #include <sys/capsicum.h>
41 #include <sys/event.h>
42 #include <sys/ptrace.h>
43 
44 #include <err.h>
45 #include <signal.h>
46 #include <stdbool.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <sysdecode.h>
50 #include <time.h>
51 #include <unistd.h>
52 
53 #include "truss.h"
54 #include "extern.h"
55 #include "syscall.h"
56 
57 static __dead2 void
58 usage(void)
59 {
60 	fprintf(stderr, "%s\n%s\n%s\n",
61 	    "usage: truss [-cfaedyDHS] [-o file] [-s strsize] [-t expr] -p pid",
62 	    "       truss [-cfaedyDHS] [-o file] [-s strsize] [-t expr] "
63 	    "command [args]",
64 	    "       truss -t");
65 	exit(1);
66 }
67 
68 int
69 main(int ac, char **av)
70 {
71 	struct sigaction sa;
72 	struct trussinfo *trussinfo;
73 	struct procinfo *np;
74 	char *fname;
75 	char **command;
76 	const char *errstr;
77 	pid_t pid;
78 	int c;
79 
80 	fname = NULL;
81 
82 	/* Initialize the trussinfo struct */
83 	trussinfo = (struct trussinfo *)calloc(1, sizeof(struct trussinfo));
84 	if (trussinfo == NULL)
85 		errx(1, "calloc() failed");
86 
87 	pid = 0;
88 	trussinfo->outfile = stderr;
89 	trussinfo->strsize = 32;
90 	trussinfo->curthread = NULL;
91 	LIST_INIT(&trussinfo->proclist);
92 	trussinfo->cap_mode = true;
93 
94 	/*
95 	 * The leading ':' asks getopt() to report a missing option
96 	 * argument as ':' rather than '?' so that a bare -t, which lists
97 	 * the system call groups, can be told from a malformed option.
98 	 * Diagnosing the other two cases then falls to us.
99 	 */
100 	while ((c = getopt(ac, av, ":p:o:facedyDs:t:SH")) != -1) {
101 		switch (c) {
102 		case 'p':	/* specified pid */
103 			pid = atoi(optarg);
104 			/* make sure i don't trace me */
105 			if (pid == getpid()) {
106 				errx(2, "attempt to grab self.");
107 			}
108 			break;
109 		case 'f': /* Follow fork()'s */
110 			trussinfo->flags |= FOLLOWFORKS;
111 			break;
112 		case 'a': /* Print execve() argument strings. */
113 			trussinfo->flags |= EXECVEARGS;
114 			break;
115 		case 'c': /* Count number of system calls and time. */
116 			trussinfo->flags |= (COUNTONLY | NOSIGS);
117 			break;
118 		case 'e': /* Print execve() environment strings. */
119 			trussinfo->flags |= EXECVEENVS;
120 			break;
121 		case 'd': /* Absolute timestamps */
122 			trussinfo->flags |= ABSOLUTETIMESTAMPS;
123 			break;
124 		case 'D': /* Relative timestamps */
125 			trussinfo->flags |= RELATIVETIMESTAMPS;
126 			break;
127 		case 'o':	/* Specified output file */
128 			fname = optarg;
129 			break;
130 		case 's':	/* Specified string size */
131 			trussinfo->strsize = (int)strtonum(optarg, 0, INT_MAX,
132 			    &errstr);
133 			if (errstr)
134 				errx(1, "maximum string size is %s: %s", errstr, optarg);
135 			break;
136 		case 't':	/* Select the system calls to trace */
137 			add_syscall_filter(optarg);
138 			break;
139 		case 'y':
140 			trussinfo->cap_mode = false;
141 			break;
142 		case 'S':	/* Don't trace signals */
143 			trussinfo->flags |= NOSIGS;
144 			break;
145 		case 'H':
146 			trussinfo->flags |= DISPLAYTIDS;
147 			break;
148 		case ':':
149 			if (optopt == 't') {
150 				/* A bare -t lists the system call groups. */
151 				list_syscall_groups();
152 				return (2);
153 			}
154 			warnx("option requires an argument -- %c", optopt);
155 			usage();
156 		default:
157 			warnx("illegal option -- %c", optopt);
158 			usage();
159 		}
160 	}
161 
162 	ac -= optind; av += optind;
163 	if ((pid == 0 && ac == 0) ||
164 	    (pid != 0 && ac != 0))
165 		usage();
166 
167 	if (fname != NULL) { /* Use output file */
168 		/*
169 		 * Set close-on-exec ('e'), so that the output file is not
170 		 * shared with the traced process.
171 		 */
172 		if ((trussinfo->outfile = fopen(fname, "we")) == NULL)
173 			err(1, "cannot open %s", fname);
174 	}
175 
176 	if (trussinfo->cap_mode) {
177 		trussinfo->pdkq = kqueue();
178 		if (trussinfo->pdkq == -1)
179 			err(1, "kqueue");
180 	}
181 
182 	/*
183 	 * If truss starts the process itself, it will ignore some signals --
184 	 * they should be passed off to the process, which may or may not
185 	 * exit.  If, however, we are examining an already-running process,
186 	 * then we restore the event mask on these same signals.
187 	 */
188 	if (pid == 0) {
189 		/* Start a command ourselves */
190 		command = av;
191 		setup_and_wait(trussinfo, command);
192 		signal(SIGINT, SIG_IGN);
193 		signal(SIGTERM, SIG_IGN);
194 		signal(SIGQUIT, SIG_IGN);
195 	} else {
196 		sa.sa_handler = restore_proc;
197 		sa.sa_flags = 0;
198 		sigemptyset(&sa.sa_mask);
199 		sigaction(SIGINT, &sa, NULL);
200 		sigaction(SIGQUIT, &sa, NULL);
201 		sigaction(SIGTERM, &sa, NULL);
202 		start_tracing(trussinfo, pid);
203 	}
204 
205 	/*
206 	 * At this point, if we started the process, it is stopped waiting to
207 	 * be woken up, either in exit() or in execve().
208 	 */
209 	np = LIST_FIRST(&trussinfo->proclist);
210 	if (np->abi == NULL) {
211 		/*
212 		 * If we are not able to handle this ABI, detach from the
213 		 * process and exit.  If we just created a new process to
214 		 * run a command, kill the new process rather than letting
215 		 * it run untraced.
216 		 */
217 		if (pid == 0)
218 			truss_kill(trussinfo, np, SIGKILL);
219 		truss_ptrace(trussinfo, PT_DETACH, np, NULL, 0);
220 		return (1);
221 	}
222 	truss_ptrace(trussinfo, PT_SYSCALL, np, (caddr_t)1, 0);
223 
224 	/*
225 	 * At this point, it's a simple loop, waiting for the process to
226 	 * stop, finding out why, printing out why, and then continuing it.
227 	 * All of the grunt work is done in the support routines.
228 	 */
229 	clock_gettime(CLOCK_REALTIME, &trussinfo->start_time);
230 
231 	eventloop(trussinfo);
232 
233 	if (trussinfo->flags & COUNTONLY)
234 		print_summary(trussinfo);
235 
236 	fflush(trussinfo->outfile);
237 
238 	return (0);
239 }
240