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