xref: /freebsd/usr.bin/truss/setup.c (revision 9aff62dee28239f84b4aa4a3429cf26dbbf770cc)
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 #include <sys/cdefs.h>
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/time.h>
43 #include <sys/wait.h>
44 
45 #include <assert.h>
46 #include <err.h>
47 #include <errno.h>
48 #include <signal.h>
49 #include <stdbool.h>
50 #include <stdint.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <string.h>
54 #include <sysdecode.h>
55 #include <time.h>
56 #include <unistd.h>
57 
58 #include "truss.h"
59 #include "syscall.h"
60 #include "extern.h"
61 
62 struct procabi_table {
63 	const char *name;
64 	struct procabi *abi;
65 };
66 
67 static sig_atomic_t detaching;
68 
69 static void	enter_syscall(struct trussinfo *, struct threadinfo *,
70 		    struct ptrace_lwpinfo *);
71 static void	new_proc(struct trussinfo *, pid_t, lwpid_t);
72 
73 
74 static struct procabi freebsd = {
75 	.type = "FreeBSD",
76 	.abi = SYSDECODE_ABI_FREEBSD,
77 	.pointer_size = sizeof(void *),
78 	.extra_syscalls = STAILQ_HEAD_INITIALIZER(freebsd.extra_syscalls),
79 	.syscalls = { NULL }
80 };
81 
82 #if !defined(__SIZEOF_POINTER__)
83 #error "Use a modern compiler."
84 #endif
85 
86 #if __SIZEOF_POINTER__ > 4
87 static struct procabi freebsd32 = {
88 	.type = "FreeBSD32",
89 	.abi = SYSDECODE_ABI_FREEBSD32,
90 	.pointer_size = sizeof(uint32_t),
91 	.compat_prefix = "freebsd32_",
92 	.extra_syscalls = STAILQ_HEAD_INITIALIZER(freebsd32.extra_syscalls),
93 	.syscalls = { NULL }
94 };
95 #endif
96 
97 static struct procabi linux = {
98 	.type = "Linux",
99 	.abi = SYSDECODE_ABI_LINUX,
100 	.pointer_size = sizeof(void *),
101 	.extra_syscalls = STAILQ_HEAD_INITIALIZER(linux.extra_syscalls),
102 	.syscalls = { NULL }
103 };
104 
105 #if __SIZEOF_POINTER__ > 4
106 static struct procabi linux32 = {
107 	.type = "Linux32",
108 	.abi = SYSDECODE_ABI_LINUX32,
109 	.pointer_size = sizeof(uint32_t),
110 	.extra_syscalls = STAILQ_HEAD_INITIALIZER(linux32.extra_syscalls),
111 	.syscalls = { NULL }
112 };
113 #endif
114 
115 static struct procabi_table abis[] = {
116 #if __SIZEOF_POINTER__ == 4
117 	{ "FreeBSD ELF32", &freebsd },
118 #elif __SIZEOF_POINTER__ == 8
119 	{ "FreeBSD ELF64", &freebsd },
120 	{ "FreeBSD ELF32", &freebsd32 },
121 #else
122 #error "Unsupported pointer size"
123 #endif
124 #if defined(__powerpc64__)
125 	{ "FreeBSD ELF64 V2", &freebsd },
126 #endif
127 #if defined(__amd64__)
128 	{ "FreeBSD a.out", &freebsd32 },
129 #endif
130 #if defined(__i386__)
131 	{ "FreeBSD a.out", &freebsd },
132 #endif
133 #if __SIZEOF_POINTER__ >= 8
134 	{ "Linux ELF64", &linux },
135 	{ "Linux ELF32", &linux32 },
136 #else
137 	{ "Linux ELF32", &linux },
138 #endif
139 };
140 
141 /*
142  * setup_and_wait() is called to start a process.  All it really does
143  * is fork(), enable tracing in the child, and then exec the given
144  * command.  At that point, the child process stops, and the parent
145  * can wake up and deal with it.
146  */
147 void
148 setup_and_wait(struct trussinfo *info, char *command[])
149 {
150 	pid_t pid;
151 
152 	pid = vfork();
153 	if (pid == -1)
154 		err(1, "fork failed");
155 	if (pid == 0) {	/* Child */
156 		ptrace(PT_TRACE_ME, 0, 0, 0);
157 		execvp(command[0], command);
158 		err(1, "execvp %s", command[0]);
159 	}
160 
161 	/* Only in the parent here */
162 	if (waitpid(pid, NULL, 0) < 0)
163 		err(1, "unexpected stop in waitpid");
164 
165 	new_proc(info, pid, 0);
166 }
167 
168 /*
169  * start_tracing is called to attach to an existing process.
170  */
171 void
172 start_tracing(struct trussinfo *info, pid_t pid)
173 {
174 	int ret, retry;
175 
176 	retry = 10;
177 	do {
178 		ret = ptrace(PT_ATTACH, pid, NULL, 0);
179 		usleep(200);
180 	} while (ret && retry-- > 0);
181 	if (ret)
182 		err(1, "Cannot attach to target process");
183 
184 	if (waitpid(pid, NULL, 0) < 0)
185 		err(1, "Unexpected stop in waitpid");
186 
187 	new_proc(info, pid, 0);
188 }
189 
190 /*
191  * Restore a process back to it's pre-truss state.
192  * Called for SIGINT, SIGTERM, SIGQUIT.  This only
193  * applies if truss was told to monitor an already-existing
194  * process.
195  */
196 void
197 restore_proc(int signo __unused)
198 {
199 
200 	detaching = 1;
201 }
202 
203 static void
204 detach_proc(pid_t pid)
205 {
206 	int sig, status;
207 
208 	/*
209 	 * Stop the child so that we can detach.  Filter out possible
210 	 * lingering SIGTRAP events buffered in the threads.
211 	 */
212 	kill(pid, SIGSTOP);
213 	for (;;) {
214 		if (waitpid(pid, &status, 0) < 0)
215 			err(1, "Unexpected error in waitpid");
216 		sig = WIFSTOPPED(status) ? WSTOPSIG(status) : 0;
217 		if (sig == SIGSTOP)
218 			break;
219 		if (sig == SIGTRAP)
220 			sig = 0;
221 		if (ptrace(PT_CONTINUE, pid, (caddr_t)1, sig) < 0)
222 			err(1, "Can not continue for detach");
223 	}
224 
225 	if (ptrace(PT_DETACH, pid, (caddr_t)1, 0) < 0)
226 		err(1, "Can not detach the process");
227 
228 	kill(pid, SIGCONT);
229 }
230 
231 /*
232  * Determine the ABI.  This is called after every exec, and when
233  * a process is first monitored.
234  */
235 static struct procabi *
236 find_abi(pid_t pid)
237 {
238 	size_t len;
239 	unsigned int i;
240 	int error;
241 	int mib[4];
242 	char progt[32];
243 
244 	len = sizeof(progt);
245 	mib[0] = CTL_KERN;
246 	mib[1] = KERN_PROC;
247 	mib[2] = KERN_PROC_SV_NAME;
248 	mib[3] = pid;
249 	error = sysctl(mib, 4, progt, &len, NULL, 0);
250 	if (error != 0)
251 		err(2, "can not get sysvec name");
252 
253 	for (i = 0; i < nitems(abis); i++) {
254 		if (strcmp(abis[i].name, progt) == 0)
255 			return (abis[i].abi);
256 	}
257 	warnx("ABI %s for pid %ld is not supported", progt, (long)pid);
258 	return (NULL);
259 }
260 
261 static struct threadinfo *
262 new_thread(struct procinfo *p, lwpid_t lwpid)
263 {
264 	struct threadinfo *nt;
265 
266 	/*
267 	 * If this happens it means there is a bug in truss.  Unfortunately
268 	 * this will kill any processes truss is attached to.
269 	 */
270 	LIST_FOREACH(nt, &p->threadlist, entries) {
271 		if (nt->tid == lwpid)
272 			errx(1, "Duplicate thread for LWP %ld", (long)lwpid);
273 	}
274 
275 	nt = calloc(1, sizeof(struct threadinfo));
276 	if (nt == NULL)
277 		err(1, "calloc() failed");
278 	nt->proc = p;
279 	nt->tid = lwpid;
280 	LIST_INSERT_HEAD(&p->threadlist, nt, entries);
281 	return (nt);
282 }
283 
284 static void
285 free_thread(struct threadinfo *t)
286 {
287 
288 	LIST_REMOVE(t, entries);
289 	free(t);
290 }
291 
292 static void
293 add_threads(struct trussinfo *info, struct procinfo *p)
294 {
295 	struct ptrace_lwpinfo pl;
296 	struct threadinfo *t;
297 	lwpid_t *lwps;
298 	int i, nlwps;
299 
300 	nlwps = ptrace(PT_GETNUMLWPS, p->pid, NULL, 0);
301 	if (nlwps == -1)
302 		err(1, "Unable to fetch number of LWPs");
303 	assert(nlwps > 0);
304 	lwps = calloc(nlwps, sizeof(*lwps));
305 	nlwps = ptrace(PT_GETLWPLIST, p->pid, (caddr_t)lwps, nlwps);
306 	if (nlwps == -1)
307 		err(1, "Unable to fetch LWP list");
308 	for (i = 0; i < nlwps; i++) {
309 		t = new_thread(p, lwps[i]);
310 		if (ptrace(PT_LWPINFO, lwps[i], (caddr_t)&pl, sizeof(pl)) == -1)
311 			err(1, "ptrace(PT_LWPINFO)");
312 		if (pl.pl_flags & PL_FLAG_SCE) {
313 			info->curthread = t;
314 			enter_syscall(info, t, &pl);
315 		}
316 	}
317 	free(lwps);
318 }
319 
320 static void
321 new_proc(struct trussinfo *info, pid_t pid, lwpid_t lwpid)
322 {
323 	struct procinfo *np;
324 
325 	/*
326 	 * If this happens it means there is a bug in truss.  Unfortunately
327 	 * this will kill any processes truss is attached to.
328 	 */
329 	LIST_FOREACH(np, &info->proclist, entries) {
330 		if (np->pid == pid)
331 			errx(1, "Duplicate process for pid %ld", (long)pid);
332 	}
333 
334 	if (info->flags & FOLLOWFORKS)
335 		if (ptrace(PT_FOLLOW_FORK, pid, NULL, 1) == -1)
336 			err(1, "Unable to follow forks for pid %ld", (long)pid);
337 	if (ptrace(PT_LWP_EVENTS, pid, NULL, 1) == -1)
338 		err(1, "Unable to enable LWP events for pid %ld", (long)pid);
339 	np = calloc(1, sizeof(struct procinfo));
340 	np->pid = pid;
341 	np->abi = find_abi(pid);
342 	LIST_INIT(&np->threadlist);
343 	LIST_INIT(&np->fdlist);
344 	LIST_INSERT_HEAD(&info->proclist, np, entries);
345 
346 	if (lwpid != 0)
347 		new_thread(np, lwpid);
348 	else
349 		add_threads(info, np);
350 }
351 
352 static void
353 free_proc(struct procinfo *p)
354 {
355 	struct threadinfo *t, *t2;
356 	struct fd_domain *f, *f2;
357 
358 	LIST_FOREACH_SAFE(t, &p->threadlist, entries, t2) {
359 		free(t);
360 	}
361 
362 	LIST_FOREACH_SAFE(f, &p->fdlist, entries, f2) {
363 		free(f);
364 	}
365 
366 	LIST_REMOVE(p, entries);
367 	free(p);
368 }
369 
370 static void
371 detach_all_procs(struct trussinfo *info)
372 {
373 	struct procinfo *p, *p2;
374 
375 	LIST_FOREACH_SAFE(p, &info->proclist, entries, p2) {
376 		detach_proc(p->pid);
377 		free_proc(p);
378 	}
379 }
380 
381 static struct procinfo *
382 find_proc(struct trussinfo *info, pid_t pid)
383 {
384 	struct procinfo *np;
385 
386 	LIST_FOREACH(np, &info->proclist, entries) {
387 		if (np->pid == pid)
388 			return (np);
389 	}
390 
391 	return (NULL);
392 }
393 
394 /*
395  * Change curthread member based on (pid, lwpid).
396  */
397 static void
398 find_thread(struct trussinfo *info, pid_t pid, lwpid_t lwpid)
399 {
400 	struct procinfo *np;
401 	struct threadinfo *nt;
402 
403 	np = find_proc(info, pid);
404 	assert(np != NULL);
405 
406 	LIST_FOREACH(nt, &np->threadlist, entries) {
407 		if (nt->tid == lwpid) {
408 			info->curthread = nt;
409 			return;
410 		}
411 	}
412 	errx(1, "could not find thread");
413 }
414 
415 /*
416  * When a process exits, it should have exactly one thread left.
417  * All of the other threads should have reported thread exit events.
418  */
419 static void
420 find_exit_thread(struct trussinfo *info, pid_t pid)
421 {
422 	struct procinfo *p;
423 
424 	p = find_proc(info, pid);
425 	assert(p != NULL);
426 
427 	info->curthread = LIST_FIRST(&p->threadlist);
428 	assert(info->curthread != NULL);
429 	assert(LIST_NEXT(info->curthread, entries) == NULL);
430 }
431 
432 static void
433 alloc_syscall(struct threadinfo *t, struct ptrace_lwpinfo *pl)
434 {
435 	u_int i;
436 
437 	assert(t->in_syscall == 0);
438 	assert(t->cs.number == 0);
439 	assert(t->cs.sc == NULL);
440 	assert(t->cs.nargs == 0);
441 	for (i = 0; i < nitems(t->cs.s_args); i++)
442 		assert(t->cs.s_args[i] == NULL);
443 	memset(t->cs.args, 0, sizeof(t->cs.args));
444 	t->cs.number = pl->pl_syscall_code;
445 	t->in_syscall = 1;
446 }
447 
448 static void
449 free_syscall(struct threadinfo *t)
450 {
451 	u_int i;
452 
453 	for (i = 0; i < t->cs.nargs; i++)
454 		free(t->cs.s_args[i]);
455 	memset(&t->cs, 0, sizeof(t->cs));
456 	t->in_syscall = 0;
457 }
458 
459 static void
460 enter_syscall(struct trussinfo *info, struct threadinfo *t,
461     struct ptrace_lwpinfo *pl)
462 {
463 	struct syscall *sc;
464 	u_int i, narg;
465 
466 	alloc_syscall(t, pl);
467 	narg = MIN(pl->pl_syscall_narg, nitems(t->cs.args));
468 	if (narg != 0 && ptrace(PT_GET_SC_ARGS, t->tid, (caddr_t)t->cs.args,
469 	    sizeof(t->cs.args)) != 0) {
470 		free_syscall(t);
471 		return;
472 	}
473 
474 	sc = get_syscall(t, t->cs.number, narg);
475 	if (sc->unknown && sc->trace)
476 		fprintf(info->outfile, "-- UNKNOWN %s SYSCALL %d --\n",
477 		    t->proc->abi->type, t->cs.number);
478 
479 	t->cs.nargs = sc->decode.nargs;
480 	assert(sc->decode.nargs <= nitems(t->cs.s_args));
481 
482 	t->cs.sc = sc;
483 
484 	/*
485 	 * A system call excluded by -t is never printed, so there is no
486 	 * point in formatting its arguments.
487 	 */
488 	if (!sc->trace) {
489 		clock_gettime(CLOCK_REALTIME, &t->before);
490 		return;
491 	}
492 
493 	/*
494 	 * At this point, we set up the system call arguments.
495 	 * We ignore any OUT ones, however -- those are arguments that
496 	 * are set by the system call, and so are probably meaningless
497 	 * now.	This doesn't currently support arguments that are
498 	 * passed in *and* out, however.
499 	 */
500 #if DEBUG
501 	fprintf(stderr, "syscall %s(", sc->name);
502 #endif
503 	for (i = 0; i < t->cs.nargs; i++) {
504 #if DEBUG
505 		fprintf(stderr, "0x%lx%s",
506 		    t->cs.args[sc->decode.args[i].offset],
507 		    i < (t->cs.nargs - 1) ? "," : "");
508 #endif
509 		if (!(sc->decode.args[i].type & OUT)) {
510 			t->cs.s_args[i] = print_arg(&sc->decode.args[i],
511 			    t->cs.args, NULL, info, &sc->decode);
512 		}
513 	}
514 #if DEBUG
515 	fprintf(stderr, ")\n");
516 #endif
517 
518 	clock_gettime(CLOCK_REALTIME, &t->before);
519 }
520 
521 /*
522  * When a thread exits voluntarily (including when a thread calls
523  * exit() to trigger a process exit), the thread's internal state
524  * holds the arguments passed to the exit system call.  When the
525  * thread's exit is reported, log that system call without a return
526  * value.
527  */
528 static void
529 thread_exit_syscall(struct trussinfo *info)
530 {
531 	struct threadinfo *t;
532 
533 	t = info->curthread;
534 	if (!t->in_syscall)
535 		return;
536 
537 	clock_gettime(CLOCK_REALTIME, &t->after);
538 
539 	print_syscall_ret(info, 0, NULL);
540 	free_syscall(t);
541 }
542 
543 static void
544 exit_syscall(struct trussinfo *info, struct ptrace_lwpinfo *pl)
545 {
546 	struct threadinfo *t;
547 	struct procinfo *p;
548 	struct syscall *sc;
549 	struct ptrace_sc_ret psr;
550 	u_int i;
551 
552 	t = info->curthread;
553 	if (!t->in_syscall)
554 		return;
555 
556 	clock_gettime(CLOCK_REALTIME, &t->after);
557 	p = t->proc;
558 	if (ptrace(PT_GET_SC_RET, t->tid, (caddr_t)&psr, sizeof(psr)) != 0) {
559 		free_syscall(t);
560 		return;
561 	}
562 
563 	sc = t->cs.sc;
564 	/*
565 	 * Here, we only look for arguments that have OUT masked in --
566 	 * otherwise, they were handled in enter_syscall().  A system call
567 	 * excluded by -t is never printed, so none of them are needed.
568 	 */
569 	for (i = 0; i < sc->decode.nargs && sc->trace; i++) {
570 		char *temp;
571 
572 		if (sc->decode.args[i].type & OUT) {
573 			/*
574 			 * If an error occurred, then don't bother
575 			 * getting the data; it may not be valid.
576 			 */
577 			if (psr.sr_error != 0) {
578 				asprintf(&temp, "0x%lx",
579 				    (long)t->cs.args[sc->decode.args[i].offset]);
580 			} else {
581 				temp = print_arg(&sc->decode.args[i],
582 				    t->cs.args, psr.sr_retval, info,
583 				    &sc->decode);
584 			}
585 			t->cs.s_args[i] = temp;
586 		}
587 	}
588 
589 	/*
590 	 * Track successfully created sockets so later syscalls using the
591 	 * returned file descriptor can be identified by socket domain.
592 	 */
593 	if (strcmp(sc->name, "socket") == 0 &&
594 	    psr.sr_error == 0) {
595 
596 		struct fd_domain *f = calloc(1, sizeof(*f));
597 
598 		f->fd = (int)psr.sr_retval[0];
599 		f->domain = (int)t->cs.args[0];
600 		f->protocol = (int)t->cs.args[2];
601 
602 		LIST_INSERT_HEAD(&p->fdlist, f, entries);
603 	}
604 
605 	if (strcmp(sc->name, "close") == 0 &&
606 	    psr.sr_error == 0) {
607 
608 		struct fd_domain *f, *f2;
609 
610 		LIST_FOREACH_SAFE(f, &p->fdlist, entries, f2) {
611 			if (f->fd == (int)t->cs.args[0]) {
612 				LIST_REMOVE(f, entries);
613 				free(f);
614 			}
615 		}
616 	}
617 
618 	print_syscall_ret(info, psr.sr_error, psr.sr_retval);
619 	free_syscall(t);
620 
621 	/*
622 	 * If the process executed a new image, check the ABI.  If the
623 	 * new ABI isn't supported, stop tracing this process.
624 	 */
625 	if (pl->pl_flags & PL_FLAG_EXEC) {
626 		assert(LIST_NEXT(LIST_FIRST(&p->threadlist), entries) == NULL);
627 		p->abi = find_abi(p->pid);
628 		if (p->abi == NULL) {
629 			if (ptrace(PT_DETACH, p->pid, (caddr_t)1, 0) < 0)
630 				err(1, "Can not detach the process");
631 			free_proc(p);
632 		}
633 	}
634 }
635 
636 int
637 print_line_prefix(struct trussinfo *info)
638 {
639 	struct timespec timediff;
640 	struct threadinfo *t;
641 	int len;
642 
643 	len = 0;
644 	t = info->curthread;
645 	if (info->flags & (FOLLOWFORKS | DISPLAYTIDS)) {
646 		if (info->flags & FOLLOWFORKS)
647 			len += fprintf(info->outfile, "%5d", t->proc->pid);
648 		if ((info->flags & (FOLLOWFORKS | DISPLAYTIDS)) ==
649 		    (FOLLOWFORKS | DISPLAYTIDS))
650 			len += fprintf(info->outfile, " ");
651 		if (info->flags & DISPLAYTIDS)
652 			len += fprintf(info->outfile, "%6d", t->tid);
653 		len += fprintf(info->outfile, ": ");
654 	}
655 	if (info->flags & ABSOLUTETIMESTAMPS) {
656 		timespecsub(&t->after, &info->start_time, &timediff);
657 		len += fprintf(info->outfile, "%jd.%09ld ",
658 		    (intmax_t)timediff.tv_sec, timediff.tv_nsec);
659 	}
660 	if (info->flags & RELATIVETIMESTAMPS) {
661 		timespecsub(&t->after, &t->before, &timediff);
662 		len += fprintf(info->outfile, "%jd.%09ld ",
663 		    (intmax_t)timediff.tv_sec, timediff.tv_nsec);
664 	}
665 	return (len);
666 }
667 
668 static void
669 report_thread_death(struct trussinfo *info)
670 {
671 	struct threadinfo *t;
672 
673 	t = info->curthread;
674 	clock_gettime(CLOCK_REALTIME, &t->after);
675 	print_line_prefix(info);
676 	fprintf(info->outfile, "<thread %ld exited>\n", (long)t->tid);
677 }
678 
679 static void
680 report_thread_birth(struct trussinfo *info)
681 {
682 	struct threadinfo *t;
683 
684 	t = info->curthread;
685 	clock_gettime(CLOCK_REALTIME, &t->after);
686 	t->before = t->after;
687 	print_line_prefix(info);
688 	fprintf(info->outfile, "<new thread %ld>\n", (long)t->tid);
689 }
690 
691 static void
692 report_exit(struct trussinfo *info, siginfo_t *si)
693 {
694 	struct threadinfo *t;
695 
696 	t = info->curthread;
697 	clock_gettime(CLOCK_REALTIME, &t->after);
698 	print_line_prefix(info);
699 	if (si->si_code == CLD_EXITED)
700 		fprintf(info->outfile, "process exit, rval = %u\n",
701 		    si->si_status);
702 	else
703 		fprintf(info->outfile, "process killed, signal = %u%s\n",
704 		    si->si_status, si->si_code == CLD_DUMPED ?
705 		    " (core dumped)" : "");
706 }
707 
708 static void
709 report_new_child(struct trussinfo *info)
710 {
711 	struct threadinfo *t;
712 
713 	t = info->curthread;
714 	clock_gettime(CLOCK_REALTIME, &t->after);
715 	t->before = t->after;
716 	print_line_prefix(info);
717 	fprintf(info->outfile, "<new process>\n");
718 }
719 
720 void
721 decode_siginfo(FILE *fp, siginfo_t *si)
722 {
723 	const char *str;
724 
725 	fprintf(fp, " code=");
726 	str = sysdecode_sigcode(si->si_signo, si->si_code);
727 	if (str == NULL)
728 		fprintf(fp, "%d", si->si_code);
729 	else
730 		fprintf(fp, "%s", str);
731 	switch (si->si_code) {
732 	case SI_NOINFO:
733 		break;
734 	case SI_QUEUE:
735 		fprintf(fp, " value=%p", si->si_value.sival_ptr);
736 		/* FALLTHROUGH */
737 	case SI_USER:
738 	case SI_LWP:
739 		fprintf(fp, " pid=%jd uid=%jd", (intmax_t)si->si_pid,
740 		    (intmax_t)si->si_uid);
741 		break;
742 	case SI_TIMER:
743 		fprintf(fp, " value=%p", si->si_value.sival_ptr);
744 		fprintf(fp, " timerid=%d", si->si_timerid);
745 		fprintf(fp, " overrun=%d", si->si_overrun);
746 		if (si->si_errno != 0)
747 			fprintf(fp, " errno=%d", si->si_errno);
748 		break;
749 	case SI_ASYNCIO:
750 		fprintf(fp, " value=%p", si->si_value.sival_ptr);
751 		break;
752 	case SI_MESGQ:
753 		fprintf(fp, " value=%p", si->si_value.sival_ptr);
754 		fprintf(fp, " mqd=%d", si->si_mqd);
755 		break;
756 	default:
757 		switch (si->si_signo) {
758 		case SIGILL:
759 		case SIGFPE:
760 		case SIGSEGV:
761 		case SIGBUS:
762 			fprintf(fp, " trapno=%d", si->si_trapno);
763 			fprintf(fp, " addr=%p", si->si_addr);
764 			break;
765 		case SIGCHLD:
766 			fprintf(fp, " pid=%jd uid=%jd", (intmax_t)si->si_pid,
767 			    (intmax_t)si->si_uid);
768 			fprintf(fp, " status=%d", si->si_status);
769 			break;
770 		}
771 	}
772 }
773 
774 static void
775 report_signal(struct trussinfo *info, siginfo_t *si, struct ptrace_lwpinfo *pl)
776 {
777 	struct threadinfo *t;
778 	const char *signame;
779 
780 	t = info->curthread;
781 	clock_gettime(CLOCK_REALTIME, &t->after);
782 	print_line_prefix(info);
783 	signame = sysdecode_signal(si->si_status);
784 	if (signame == NULL)
785 		signame = "?";
786 	fprintf(info->outfile, "SIGNAL %u (%s)", si->si_status, signame);
787 	if (pl->pl_event == PL_EVENT_SIGNAL && pl->pl_flags & PL_FLAG_SI)
788 		decode_siginfo(info->outfile, &pl->pl_siginfo);
789 	fprintf(info->outfile, "\n");
790 
791 }
792 
793 /*
794  * Wait for events until all the processes have exited or truss has been
795  * asked to stop.
796  */
797 void
798 eventloop(struct trussinfo *info)
799 {
800 	struct ptrace_lwpinfo pl;
801 	siginfo_t si;
802 	int pending_signal;
803 
804 	while (!LIST_EMPTY(&info->proclist)) {
805 		if (detaching) {
806 			detach_all_procs(info);
807 			return;
808 		}
809 
810 		if (waitid(P_ALL, 0, &si, WTRAPPED | WEXITED) == -1) {
811 			if (errno == EINTR)
812 				continue;
813 			err(1, "Unexpected error from waitid");
814 		}
815 
816 		assert(si.si_signo == SIGCHLD);
817 
818 		switch (si.si_code) {
819 		case CLD_EXITED:
820 		case CLD_KILLED:
821 		case CLD_DUMPED:
822 			find_exit_thread(info, si.si_pid);
823 			if ((info->flags & COUNTONLY) == 0) {
824 				if (si.si_code == CLD_EXITED)
825 					thread_exit_syscall(info);
826 				report_exit(info, &si);
827 			}
828 			free_proc(info->curthread->proc);
829 			info->curthread = NULL;
830 			break;
831 		case CLD_TRAPPED:
832 			if (ptrace(PT_LWPINFO, si.si_pid, (caddr_t)&pl,
833 			    sizeof(pl)) == -1)
834 				err(1, "ptrace(PT_LWPINFO)");
835 
836 			if (pl.pl_flags & PL_FLAG_CHILD) {
837 				new_proc(info, si.si_pid, pl.pl_lwpid);
838 				assert(LIST_FIRST(&info->proclist)->abi !=
839 				    NULL);
840 			} else if (pl.pl_flags & PL_FLAG_BORN)
841 				new_thread(find_proc(info, si.si_pid),
842 				    pl.pl_lwpid);
843 			find_thread(info, si.si_pid, pl.pl_lwpid);
844 
845 			if (si.si_status == SIGTRAP &&
846 			    (pl.pl_flags & (PL_FLAG_BORN|PL_FLAG_EXITED|
847 			    PL_FLAG_SCE|PL_FLAG_SCX)) != 0) {
848 				if (pl.pl_flags & PL_FLAG_BORN) {
849 					if ((info->flags & COUNTONLY) == 0)
850 						report_thread_birth(info);
851 				} else if (pl.pl_flags & PL_FLAG_EXITED) {
852 					if ((info->flags & COUNTONLY) == 0)
853 						report_thread_death(info);
854 					free_thread(info->curthread);
855 					info->curthread = NULL;
856 				} else if (pl.pl_flags & PL_FLAG_SCE)
857 					enter_syscall(info, info->curthread, &pl);
858 				else if (pl.pl_flags & PL_FLAG_SCX)
859 					exit_syscall(info, &pl);
860 				pending_signal = 0;
861 			} else if (pl.pl_flags & PL_FLAG_CHILD) {
862 				if ((info->flags & COUNTONLY) == 0)
863 					report_new_child(info);
864 				pending_signal = 0;
865 			} else {
866 				if ((info->flags & NOSIGS) == 0)
867 					report_signal(info, &si, &pl);
868 				pending_signal = si.si_status;
869 			}
870 			ptrace(PT_SYSCALL, si.si_pid, (caddr_t)1,
871 			    pending_signal);
872 			break;
873 		case CLD_STOPPED:
874 			errx(1, "waitid reported CLD_STOPPED");
875 		case CLD_CONTINUED:
876 			break;
877 		}
878 	}
879 }
880