xref: /freebsd/usr.bin/truss/setup.c (revision 3416500aef140042c64bc149cb1ec6620483bc44)
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  * Various setup functions for truss.  Not the cleanest-written code,
37  * I'm afraid.
38  */
39 
40 #include <sys/ptrace.h>
41 #include <sys/sysctl.h>
42 #include <sys/wait.h>
43 
44 #include <assert.h>
45 #include <err.h>
46 #include <errno.h>
47 #include <signal.h>
48 #include <stdbool.h>
49 #include <stdint.h>
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <string.h>
53 #include <sysdecode.h>
54 #include <time.h>
55 #include <unistd.h>
56 
57 #include "truss.h"
58 #include "syscall.h"
59 #include "extern.h"
60 
61 SET_DECLARE(procabi, struct procabi);
62 
63 static sig_atomic_t detaching;
64 
65 static void	enter_syscall(struct trussinfo *, struct threadinfo *,
66 		    struct ptrace_lwpinfo *);
67 static void	new_proc(struct trussinfo *, pid_t, lwpid_t);
68 
69 /*
70  * setup_and_wait() is called to start a process.  All it really does
71  * is fork(), enable tracing in the child, and then exec the given
72  * command.  At that point, the child process stops, and the parent
73  * can wake up and deal with it.
74  */
75 void
76 setup_and_wait(struct trussinfo *info, char *command[])
77 {
78 	pid_t pid;
79 
80 	pid = vfork();
81 	if (pid == -1)
82 		err(1, "fork failed");
83 	if (pid == 0) {	/* Child */
84 		ptrace(PT_TRACE_ME, 0, 0, 0);
85 		execvp(command[0], command);
86 		err(1, "execvp %s", command[0]);
87 	}
88 
89 	/* Only in the parent here */
90 	if (waitpid(pid, NULL, 0) < 0)
91 		err(1, "unexpect stop in waitpid");
92 
93 	new_proc(info, pid, 0);
94 }
95 
96 /*
97  * start_tracing is called to attach to an existing process.
98  */
99 void
100 start_tracing(struct trussinfo *info, pid_t pid)
101 {
102 	int ret, retry;
103 
104 	retry = 10;
105 	do {
106 		ret = ptrace(PT_ATTACH, pid, NULL, 0);
107 		usleep(200);
108 	} while (ret && retry-- > 0);
109 	if (ret)
110 		err(1, "can not attach to target process");
111 
112 	if (waitpid(pid, NULL, 0) < 0)
113 		err(1, "Unexpect stop in waitpid");
114 
115 	new_proc(info, pid, 0);
116 }
117 
118 /*
119  * Restore a process back to it's pre-truss state.
120  * Called for SIGINT, SIGTERM, SIGQUIT.  This only
121  * applies if truss was told to monitor an already-existing
122  * process.
123  */
124 void
125 restore_proc(int signo __unused)
126 {
127 
128 	detaching = 1;
129 }
130 
131 static void
132 detach_proc(pid_t pid)
133 {
134 
135 	/* stop the child so that we can detach */
136 	kill(pid, SIGSTOP);
137 	if (waitpid(pid, NULL, 0) < 0)
138 		err(1, "Unexpected stop in waitpid");
139 
140 	if (ptrace(PT_DETACH, pid, (caddr_t)1, 0) < 0)
141 		err(1, "Can not detach the process");
142 
143 	kill(pid, SIGCONT);
144 }
145 
146 /*
147  * Determine the ABI.  This is called after every exec, and when
148  * a process is first monitored.
149  */
150 static struct procabi *
151 find_abi(pid_t pid)
152 {
153 	struct procabi **pabi;
154 	size_t len;
155 	int error;
156 	int mib[4];
157 	char progt[32];
158 
159 	len = sizeof(progt);
160 	mib[0] = CTL_KERN;
161 	mib[1] = KERN_PROC;
162 	mib[2] = KERN_PROC_SV_NAME;
163 	mib[3] = pid;
164 	error = sysctl(mib, 4, progt, &len, NULL, 0);
165 	if (error != 0)
166 		err(2, "can not get sysvec name");
167 
168 	SET_FOREACH(pabi, procabi) {
169 		if (strcmp((*pabi)->type, progt) == 0)
170 			return (*pabi);
171 	}
172 	warnx("ABI %s for pid %ld is not supported", progt, (long)pid);
173 	return (NULL);
174 }
175 
176 static struct threadinfo *
177 new_thread(struct procinfo *p, lwpid_t lwpid)
178 {
179 	struct threadinfo *nt;
180 
181 	/*
182 	 * If this happens it means there is a bug in truss.  Unfortunately
183 	 * this will kill any processes truss is attached to.
184 	 */
185 	LIST_FOREACH(nt, &p->threadlist, entries) {
186 		if (nt->tid == lwpid)
187 			errx(1, "Duplicate thread for LWP %ld", (long)lwpid);
188 	}
189 
190 	nt = calloc(1, sizeof(struct threadinfo));
191 	if (nt == NULL)
192 		err(1, "calloc() failed");
193 	nt->proc = p;
194 	nt->tid = lwpid;
195 	LIST_INSERT_HEAD(&p->threadlist, nt, entries);
196 	return (nt);
197 }
198 
199 static void
200 free_thread(struct threadinfo *t)
201 {
202 
203 	LIST_REMOVE(t, entries);
204 	free(t);
205 }
206 
207 static void
208 add_threads(struct trussinfo *info, struct procinfo *p)
209 {
210 	struct ptrace_lwpinfo pl;
211 	struct threadinfo *t;
212 	lwpid_t *lwps;
213 	int i, nlwps;
214 
215 	nlwps = ptrace(PT_GETNUMLWPS, p->pid, NULL, 0);
216 	if (nlwps == -1)
217 		err(1, "Unable to fetch number of LWPs");
218 	assert(nlwps > 0);
219 	lwps = calloc(nlwps, sizeof(*lwps));
220 	nlwps = ptrace(PT_GETLWPLIST, p->pid, (caddr_t)lwps, nlwps);
221 	if (nlwps == -1)
222 		err(1, "Unable to fetch LWP list");
223 	for (i = 0; i < nlwps; i++) {
224 		t = new_thread(p, lwps[i]);
225 		if (ptrace(PT_LWPINFO, lwps[i], (caddr_t)&pl, sizeof(pl)) == -1)
226 			err(1, "ptrace(PT_LWPINFO)");
227 		if (pl.pl_flags & PL_FLAG_SCE) {
228 			info->curthread = t;
229 			enter_syscall(info, t, &pl);
230 		}
231 	}
232 	free(lwps);
233 }
234 
235 static void
236 new_proc(struct trussinfo *info, pid_t pid, lwpid_t lwpid)
237 {
238 	struct procinfo *np;
239 
240 	/*
241 	 * If this happens it means there is a bug in truss.  Unfortunately
242 	 * this will kill any processes truss is attached to.
243 	 */
244 	LIST_FOREACH(np, &info->proclist, entries) {
245 		if (np->pid == pid)
246 			errx(1, "Duplicate process for pid %ld", (long)pid);
247 	}
248 
249 	if (info->flags & FOLLOWFORKS)
250 		if (ptrace(PT_FOLLOW_FORK, pid, NULL, 1) == -1)
251 			err(1, "Unable to follow forks for pid %ld", (long)pid);
252 	if (ptrace(PT_LWP_EVENTS, pid, NULL, 1) == -1)
253 		err(1, "Unable to enable LWP events for pid %ld", (long)pid);
254 	np = calloc(1, sizeof(struct procinfo));
255 	np->pid = pid;
256 	np->abi = find_abi(pid);
257 	LIST_INIT(&np->threadlist);
258 	LIST_INSERT_HEAD(&info->proclist, np, entries);
259 
260 	if (lwpid != 0)
261 		new_thread(np, lwpid);
262 	else
263 		add_threads(info, np);
264 }
265 
266 static void
267 free_proc(struct procinfo *p)
268 {
269 	struct threadinfo *t, *t2;
270 
271 	LIST_FOREACH_SAFE(t, &p->threadlist, entries, t2) {
272 		free(t);
273 	}
274 	LIST_REMOVE(p, entries);
275 	free(p);
276 }
277 
278 static void
279 detach_all_procs(struct trussinfo *info)
280 {
281 	struct procinfo *p, *p2;
282 
283 	LIST_FOREACH_SAFE(p, &info->proclist, entries, p2) {
284 		detach_proc(p->pid);
285 		free_proc(p);
286 	}
287 }
288 
289 static struct procinfo *
290 find_proc(struct trussinfo *info, pid_t pid)
291 {
292 	struct procinfo *np;
293 
294 	LIST_FOREACH(np, &info->proclist, entries) {
295 		if (np->pid == pid)
296 			return (np);
297 	}
298 
299 	return (NULL);
300 }
301 
302 /*
303  * Change curthread member based on (pid, lwpid).
304  */
305 static void
306 find_thread(struct trussinfo *info, pid_t pid, lwpid_t lwpid)
307 {
308 	struct procinfo *np;
309 	struct threadinfo *nt;
310 
311 	np = find_proc(info, pid);
312 	assert(np != NULL);
313 
314 	LIST_FOREACH(nt, &np->threadlist, entries) {
315 		if (nt->tid == lwpid) {
316 			info->curthread = nt;
317 			return;
318 		}
319 	}
320 	errx(1, "could not find thread");
321 }
322 
323 /*
324  * When a process exits, it should have exactly one thread left.
325  * All of the other threads should have reported thread exit events.
326  */
327 static void
328 find_exit_thread(struct trussinfo *info, pid_t pid)
329 {
330 	struct procinfo *p;
331 
332 	p = find_proc(info, pid);
333 	assert(p != NULL);
334 
335 	info->curthread = LIST_FIRST(&p->threadlist);
336 	assert(info->curthread != NULL);
337 	assert(LIST_NEXT(info->curthread, entries) == NULL);
338 }
339 
340 static void
341 alloc_syscall(struct threadinfo *t, struct ptrace_lwpinfo *pl)
342 {
343 	u_int i;
344 
345 	assert(t->in_syscall == 0);
346 	assert(t->cs.number == 0);
347 	assert(t->cs.sc == NULL);
348 	assert(t->cs.nargs == 0);
349 	for (i = 0; i < nitems(t->cs.s_args); i++)
350 		assert(t->cs.s_args[i] == NULL);
351 	memset(t->cs.args, 0, sizeof(t->cs.args));
352 	t->cs.number = pl->pl_syscall_code;
353 	t->in_syscall = 1;
354 }
355 
356 static void
357 free_syscall(struct threadinfo *t)
358 {
359 	u_int i;
360 
361 	for (i = 0; i < t->cs.nargs; i++)
362 		free(t->cs.s_args[i]);
363 	memset(&t->cs, 0, sizeof(t->cs));
364 	t->in_syscall = 0;
365 }
366 
367 static void
368 enter_syscall(struct trussinfo *info, struct threadinfo *t,
369     struct ptrace_lwpinfo *pl)
370 {
371 	struct syscall *sc;
372 	u_int i, narg;
373 
374 	alloc_syscall(t, pl);
375 	narg = MIN(pl->pl_syscall_narg, nitems(t->cs.args));
376 	if (narg != 0 && t->proc->abi->fetch_args(info, narg) != 0) {
377 		free_syscall(t);
378 		return;
379 	}
380 
381 	sc = get_syscall(t, t->cs.number, narg);
382 	if (sc->unknown)
383 		fprintf(info->outfile, "-- UNKNOWN %s SYSCALL %d --\n",
384 		    t->proc->abi->type, t->cs.number);
385 
386 	t->cs.nargs = sc->nargs;
387 	assert(sc->nargs <= nitems(t->cs.s_args));
388 
389 	t->cs.sc = sc;
390 
391 	/*
392 	 * At this point, we set up the system call arguments.
393 	 * We ignore any OUT ones, however -- those are arguments that
394 	 * are set by the system call, and so are probably meaningless
395 	 * now.	This doesn't currently support arguments that are
396 	 * passed in *and* out, however.
397 	 */
398 #if DEBUG
399 	fprintf(stderr, "syscall %s(", sc->name);
400 #endif
401 	for (i = 0; i < t->cs.nargs; i++) {
402 #if DEBUG
403 		fprintf(stderr, "0x%lx%s", t->cs.args[sc->args[i].offset],
404 		    i < (t->cs.nargs - 1) ? "," : "");
405 #endif
406 		if (!(sc->args[i].type & OUT)) {
407 			t->cs.s_args[i] = print_arg(&sc->args[i],
408 			    t->cs.args, 0, info);
409 		}
410 	}
411 #if DEBUG
412 	fprintf(stderr, ")\n");
413 #endif
414 
415 	clock_gettime(CLOCK_REALTIME, &t->before);
416 }
417 
418 /*
419  * When a thread exits voluntarily (including when a thread calls
420  * exit() to trigger a process exit), the thread's internal state
421  * holds the arguments passed to the exit system call.  When the
422  * thread's exit is reported, log that system call without a return
423  * value.
424  */
425 static void
426 thread_exit_syscall(struct trussinfo *info)
427 {
428 	struct threadinfo *t;
429 
430 	t = info->curthread;
431 	if (!t->in_syscall)
432 		return;
433 
434 	clock_gettime(CLOCK_REALTIME, &t->after);
435 
436 	print_syscall_ret(info, 0, NULL);
437 	free_syscall(t);
438 }
439 
440 static void
441 exit_syscall(struct trussinfo *info, struct ptrace_lwpinfo *pl)
442 {
443 	struct threadinfo *t;
444 	struct procinfo *p;
445 	struct syscall *sc;
446 	long retval[2];
447 	u_int i;
448 	int errorp;
449 
450 	t = info->curthread;
451 	if (!t->in_syscall)
452 		return;
453 
454 	clock_gettime(CLOCK_REALTIME, &t->after);
455 	p = t->proc;
456 	if (p->abi->fetch_retval(info, retval, &errorp) < 0) {
457 		free_syscall(t);
458 		return;
459 	}
460 
461 	sc = t->cs.sc;
462 	/*
463 	 * Here, we only look for arguments that have OUT masked in --
464 	 * otherwise, they were handled in enter_syscall().
465 	 */
466 	for (i = 0; i < sc->nargs; i++) {
467 		char *temp;
468 
469 		if (sc->args[i].type & OUT) {
470 			/*
471 			 * If an error occurred, then don't bother
472 			 * getting the data; it may not be valid.
473 			 */
474 			if (errorp) {
475 				asprintf(&temp, "0x%lx",
476 				    t->cs.args[sc->args[i].offset]);
477 			} else {
478 				temp = print_arg(&sc->args[i],
479 				    t->cs.args, retval, info);
480 			}
481 			t->cs.s_args[i] = temp;
482 		}
483 	}
484 
485 	print_syscall_ret(info, errorp, retval);
486 	free_syscall(t);
487 
488 	/*
489 	 * If the process executed a new image, check the ABI.  If the
490 	 * new ABI isn't supported, stop tracing this process.
491 	 */
492 	if (pl->pl_flags & PL_FLAG_EXEC) {
493 		assert(LIST_NEXT(LIST_FIRST(&p->threadlist), entries) == NULL);
494 		p->abi = find_abi(p->pid);
495 		if (p->abi == NULL) {
496 			if (ptrace(PT_DETACH, p->pid, (caddr_t)1, 0) < 0)
497 				err(1, "Can not detach the process");
498 			free_proc(p);
499 		}
500 	}
501 }
502 
503 int
504 print_line_prefix(struct trussinfo *info)
505 {
506 	struct timespec timediff;
507 	struct threadinfo *t;
508 	int len;
509 
510 	len = 0;
511 	t = info->curthread;
512 	if (info->flags & (FOLLOWFORKS | DISPLAYTIDS)) {
513 		if (info->flags & FOLLOWFORKS)
514 			len += fprintf(info->outfile, "%5d", t->proc->pid);
515 		if ((info->flags & (FOLLOWFORKS | DISPLAYTIDS)) ==
516 		    (FOLLOWFORKS | DISPLAYTIDS))
517 			len += fprintf(info->outfile, " ");
518 		if (info->flags & DISPLAYTIDS)
519 			len += fprintf(info->outfile, "%6d", t->tid);
520 		len += fprintf(info->outfile, ": ");
521 	}
522 	if (info->flags & ABSOLUTETIMESTAMPS) {
523 		timespecsubt(&t->after, &info->start_time, &timediff);
524 		len += fprintf(info->outfile, "%jd.%09ld ",
525 		    (intmax_t)timediff.tv_sec, timediff.tv_nsec);
526 	}
527 	if (info->flags & RELATIVETIMESTAMPS) {
528 		timespecsubt(&t->after, &t->before, &timediff);
529 		len += fprintf(info->outfile, "%jd.%09ld ",
530 		    (intmax_t)timediff.tv_sec, timediff.tv_nsec);
531 	}
532 	return (len);
533 }
534 
535 static void
536 report_thread_death(struct trussinfo *info)
537 {
538 	struct threadinfo *t;
539 
540 	t = info->curthread;
541 	clock_gettime(CLOCK_REALTIME, &t->after);
542 	print_line_prefix(info);
543 	fprintf(info->outfile, "<thread %ld exited>\n", (long)t->tid);
544 }
545 
546 static void
547 report_thread_birth(struct trussinfo *info)
548 {
549 	struct threadinfo *t;
550 
551 	t = info->curthread;
552 	clock_gettime(CLOCK_REALTIME, &t->after);
553 	t->before = t->after;
554 	print_line_prefix(info);
555 	fprintf(info->outfile, "<new thread %ld>\n", (long)t->tid);
556 }
557 
558 static void
559 report_exit(struct trussinfo *info, siginfo_t *si)
560 {
561 	struct threadinfo *t;
562 
563 	t = info->curthread;
564 	clock_gettime(CLOCK_REALTIME, &t->after);
565 	print_line_prefix(info);
566 	if (si->si_code == CLD_EXITED)
567 		fprintf(info->outfile, "process exit, rval = %u\n",
568 		    si->si_status);
569 	else
570 		fprintf(info->outfile, "process killed, signal = %u%s\n",
571 		    si->si_status, si->si_code == CLD_DUMPED ?
572 		    " (core dumped)" : "");
573 }
574 
575 static void
576 report_new_child(struct trussinfo *info)
577 {
578 	struct threadinfo *t;
579 
580 	t = info->curthread;
581 	clock_gettime(CLOCK_REALTIME, &t->after);
582 	t->before = t->after;
583 	print_line_prefix(info);
584 	fprintf(info->outfile, "<new process>\n");
585 }
586 
587 static void
588 report_signal(struct trussinfo *info, siginfo_t *si)
589 {
590 	struct threadinfo *t;
591 	const char *signame;
592 
593 	t = info->curthread;
594 	clock_gettime(CLOCK_REALTIME, &t->after);
595 	print_line_prefix(info);
596 	signame = sysdecode_signal(si->si_status);
597 	if (signame == NULL)
598 		signame = "?";
599 	fprintf(info->outfile, "SIGNAL %u (%s)\n", si->si_status, signame);
600 }
601 
602 /*
603  * Wait for events until all the processes have exited or truss has been
604  * asked to stop.
605  */
606 void
607 eventloop(struct trussinfo *info)
608 {
609 	struct ptrace_lwpinfo pl;
610 	siginfo_t si;
611 	int pending_signal;
612 
613 	while (!LIST_EMPTY(&info->proclist)) {
614 		if (detaching) {
615 			detach_all_procs(info);
616 			return;
617 		}
618 
619 		if (waitid(P_ALL, 0, &si, WTRAPPED | WEXITED) == -1) {
620 			if (errno == EINTR)
621 				continue;
622 			err(1, "Unexpected error from waitid");
623 		}
624 
625 		assert(si.si_signo == SIGCHLD);
626 
627 		switch (si.si_code) {
628 		case CLD_EXITED:
629 		case CLD_KILLED:
630 		case CLD_DUMPED:
631 			find_exit_thread(info, si.si_pid);
632 			if ((info->flags & COUNTONLY) == 0) {
633 				if (si.si_code == CLD_EXITED)
634 					thread_exit_syscall(info);
635 				report_exit(info, &si);
636 			}
637 			free_proc(info->curthread->proc);
638 			info->curthread = NULL;
639 			break;
640 		case CLD_TRAPPED:
641 			if (ptrace(PT_LWPINFO, si.si_pid, (caddr_t)&pl,
642 			    sizeof(pl)) == -1)
643 				err(1, "ptrace(PT_LWPINFO)");
644 
645 			if (pl.pl_flags & PL_FLAG_CHILD) {
646 				new_proc(info, si.si_pid, pl.pl_lwpid);
647 				assert(LIST_FIRST(&info->proclist)->abi !=
648 				    NULL);
649 			} else if (pl.pl_flags & PL_FLAG_BORN)
650 				new_thread(find_proc(info, si.si_pid),
651 				    pl.pl_lwpid);
652 			find_thread(info, si.si_pid, pl.pl_lwpid);
653 
654 			if (si.si_status == SIGTRAP &&
655 			    (pl.pl_flags & (PL_FLAG_BORN|PL_FLAG_EXITED|
656 			    PL_FLAG_SCE|PL_FLAG_SCX)) != 0) {
657 				if (pl.pl_flags & PL_FLAG_BORN) {
658 					if ((info->flags & COUNTONLY) == 0)
659 						report_thread_birth(info);
660 				} else if (pl.pl_flags & PL_FLAG_EXITED) {
661 					if ((info->flags & COUNTONLY) == 0)
662 						report_thread_death(info);
663 					free_thread(info->curthread);
664 					info->curthread = NULL;
665 				} else if (pl.pl_flags & PL_FLAG_SCE)
666 					enter_syscall(info, info->curthread, &pl);
667 				else if (pl.pl_flags & PL_FLAG_SCX)
668 					exit_syscall(info, &pl);
669 				pending_signal = 0;
670 			} else if (pl.pl_flags & PL_FLAG_CHILD) {
671 				if ((info->flags & COUNTONLY) == 0)
672 					report_new_child(info);
673 				pending_signal = 0;
674 			} else {
675 				if ((info->flags & NOSIGS) == 0)
676 					report_signal(info, &si);
677 				pending_signal = si.si_status;
678 			}
679 			ptrace(PT_SYSCALL, si.si_pid, (caddr_t)1,
680 			    pending_signal);
681 			break;
682 		case CLD_STOPPED:
683 			errx(1, "waitid reported CLD_STOPPED");
684 		case CLD_CONTINUED:
685 			break;
686 		}
687 	}
688 }
689