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