xref: /netbsd-src/usr.bin/kdump/kdump.c (revision 7330f729ccf0bd976a06f95fad452fe774fc7fd1)
1 /*	$NetBSD: kdump.c,v 1.132 2019/07/23 01:54:51 nonaka Exp $	*/
2 
3 /*-
4  * Copyright (c) 1988, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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 #ifndef lint
34 __COPYRIGHT("@(#) Copyright (c) 1988, 1993\
35  The Regents of the University of California.  All rights reserved.");
36 #endif /* not lint */
37 
38 #ifndef lint
39 #if 0
40 static char sccsid[] = "@(#)kdump.c	8.4 (Berkeley) 4/28/95";
41 #else
42 __RCSID("$NetBSD: kdump.c,v 1.132 2019/07/23 01:54:51 nonaka Exp $");
43 #endif
44 #endif /* not lint */
45 
46 #include <sys/param.h>
47 #include <sys/file.h>
48 #define _KMEMUSER        /* To get the pseudo errors defined */
49 #include <sys/errno.h>
50 #undef _KMEMUSER
51 #include <sys/mman.h>
52 #include <sys/time.h>
53 #include <sys/uio.h>
54 #include <sys/ktrace.h>
55 #include <sys/ioctl.h>
56 #include <sys/ptrace.h>
57 #include <sys/socket.h>
58 
59 #include <ctype.h>
60 #include <err.h>
61 #include <signal.h>
62 #include <stddef.h>
63 #include <stdio.h>
64 #include <stdlib.h>
65 #include <string.h>
66 #include <unistd.h>
67 #include <vis.h>
68 #include <util.h>
69 
70 #include "ktrace.h"
71 #include "setemul.h"
72 
73 #include <sys/syscall.h>
74 
75 #define TIMESTAMP_NONE		0x0
76 #define TIMESTAMP_ABSOLUTE	0x1
77 #define TIMESTAMP_ELAPSED	0x2
78 #define TIMESTAMP_RELATIVE	0x4
79 
80 static int timestamp, decimal, plain, tail, maxdata = -1, numeric;
81 static int word_size = 0;
82 static pid_t do_pid = -1;
83 static const char *tracefile = NULL;
84 static struct ktr_header ktr_header;
85 static int emul_changed = 0;
86 
87 #define eqs(s1, s2)	(strcmp((s1), (s2)) == 0)
88 #define small(v)	(((long)(v) >= 0) && ((long)(v) < 10))
89 
90 static const char * const ptrace_ops[] = {
91 	PT_STRINGS
92 };
93 
94 #ifdef PT_MACHDEP_STRINGS
95 static const char * const ptrace_machdep_ops[] = { PT_MACHDEP_STRINGS };
96 #endif
97 
98 static const char * const linux_ptrace_ops[] = {
99 	"PTRACE_TRACEME",
100 	"PTRACE_PEEKTEXT", "PTRACE_PEEKDATA", "PTRACE_PEEKUSER",
101 	"PTRACE_POKETEXT", "PTRACE_POKEDATA", "PTRACE_POKEUSER",
102 	"PTRACE_CONT", "PTRACE_KILL", "PTRACE_SINGLESTEP",
103 	NULL, NULL,
104 	"PTRACE_GETREGS", "PTRACE_SETREGS", "PTRACE_GETFPREGS",
105 	"PTRACE_SETFPREGS", "PTRACE_ATTACH", "PTRACE_DETACH",
106 	NULL, NULL, NULL, NULL, NULL, NULL,
107 	"PTRACE_SYSCALL",
108 };
109 
110 static int	fread_tail(void *, size_t, size_t);
111 static int	dumpheader(struct ktr_header *);
112 static int	output_ts(const struct timespec *);
113 static void	output_long(u_long, int);
114 static void	ioctldecode(u_long);
115 static void	ktrsyscall(struct ktr_syscall *);
116 static void	ktrsysret(struct ktr_sysret *, int);
117 static void	ktrnamei(char *, int);
118 static void	ktremul(char *, size_t, size_t);
119 static void	ktrgenio(struct ktr_genio *, int);
120 static void	ktrpsig(void *, int);
121 static void	ktrcsw(struct ktr_csw *);
122 static void	ktruser(struct ktr_user *, int);
123 static void	ktrmib(int *, int);
124 static void	ktrexecfd(struct ktr_execfd *);
125 static void	usage(void) __dead;
126 static void	eprint(int);
127 static void	rprint(register_t);
128 static const char *signame(long, int);
129 static void hexdump_buf(const void *, int, int);
130 static void visdump_buf(const void *, int, int);
131 
132 int
133 main(int argc, char **argv)
134 {
135 	unsigned int ktrlen, size;
136 	int ch;
137 	void *m;
138 	int trpoints = 0;
139 	int trset = 0;
140 	const char *emul_name = "netbsd";
141 	int col;
142 	char *cp;
143 
144 	setprogname(argv[0]);
145 
146 	if (strcmp(getprogname(), "ioctlname") == 0) {
147 		int i;
148 
149 		while ((ch = getopt(argc, argv, "e:")) != -1)
150 			switch (ch) {
151 			case 'e':
152 				emul_name = optarg;
153 				break;
154 			default:
155 				usage();
156 				break;
157 			}
158 		setemul(emul_name, 0, 0);
159 		argv += optind;
160 		argc -= optind;
161 
162 		if (argc < 1)
163 			usage();
164 
165 		for (i = 0; i < argc; i++) {
166 			ioctldecode(strtoul(argv[i], NULL, 0));
167 			(void)putchar('\n');
168 		}
169 		return 0;
170 	}
171 
172 	timestamp = TIMESTAMP_NONE;
173 
174 	while ((ch = getopt(argc, argv, "Ee:f:dlm:Nnp:RTt:xX:")) != -1) {
175 		switch (ch) {
176 		case 'E':
177 			timestamp |= TIMESTAMP_ELAPSED;
178 			break;
179 		case 'e':
180 			emul_name = strdup(optarg); /* it's safer to copy it */
181 			break;
182 		case 'f':
183 			tracefile = optarg;
184 			break;
185 		case 'd':
186 			decimal = 1;
187 			break;
188 		case 'l':
189 			tail = 1;
190 			break;
191 		case 'p':
192 			do_pid = strtoul(optarg, &cp, 0);
193 			if (*cp != 0)
194 				errx(1,"invalid number %s", optarg);
195 			break;
196 		case 'm':
197 			maxdata = strtoul(optarg, &cp, 0);
198 			if (*cp != 0)
199 				errx(1,"invalid number %s", optarg);
200 			break;
201 		case 'N':
202 			numeric++;
203 			break;
204 		case 'n':
205 			plain++;
206 			break;
207 		case 'R':
208 			timestamp |= TIMESTAMP_RELATIVE;
209 			break;
210 		case 'T':
211 			timestamp |= TIMESTAMP_ABSOLUTE;
212 			break;
213 		case 't':
214 			trset = 1;
215 			trpoints = getpoints(trpoints, optarg);
216 			if (trpoints < 0)
217 				errx(1, "unknown trace point in %s", optarg);
218 			break;
219 		case 'x':
220 			word_size = 1;
221 			break;
222 		case 'X':
223 			word_size = strtoul(optarg, &cp, 0);
224 			if (*cp != 0 || word_size & (word_size - 1) ||
225 			    word_size > 16 || word_size <= 0)
226 				errx(1, "argument to -X must be "
227 				    "1, 2, 4, 8 or 16");
228 			break;
229 		default:
230 			usage();
231 		}
232 	}
233 	argv += optind;
234 	argc -= optind;
235 
236 	if (!trset)
237 		trpoints = ALL_POINTS;
238 
239 	if (tracefile == NULL) {
240 		if (argc == 1) {
241 			tracefile = argv[0];
242 			argv++;
243 			argc--;
244 		} else
245 			tracefile = DEF_TRACEFILE;
246 	}
247 
248 	if (argc > 0)
249 		usage();
250 
251 	setemul(emul_name, 0, 0);
252 
253 	m = malloc(size = 1024);
254 	if (m == NULL)
255 		errx(1, "malloc: %s", strerror(ENOMEM));
256 	if (!freopen(tracefile, "r", stdin))
257 		err(1, "%s", tracefile);
258 	while (fread_tail(&ktr_header, sizeof(struct ktr_header), 1)) {
259 		if (trpoints & (1 << ktr_header.ktr_type) &&
260 		    (do_pid == -1 || ktr_header.ktr_pid == do_pid))
261 			col = dumpheader(&ktr_header);
262 		else
263 			col = -1;
264 		if ((ktrlen = ktr_header.ktr_len) > INT_MAX)
265 			errx(1, "bogus length 0x%x", ktrlen);
266 		if (ktrlen > size) {
267 			while (ktrlen > size)
268 				size *= 2;
269 			m = realloc(m, size);
270 			if (m == NULL)
271 				errx(1, "realloc: %s", strerror(ENOMEM));
272 		}
273 		if (ktrlen && fread_tail(m, ktrlen, 1) == 0)
274 			errx(1, "data too short");
275 		if (col == -1)
276 			continue;
277 
278 		/* update context to match currently processed record */
279 		ectx_sanify(ktr_header.ktr_pid);
280 
281 		switch (ktr_header.ktr_type) {
282 		case KTR_SYSCALL:
283 			ktrsyscall(m);
284 			break;
285 		case KTR_SYSRET:
286 			ktrsysret(m, ktrlen);
287 			break;
288 		case KTR_NAMEI:
289 			ktrnamei(m, ktrlen);
290 			break;
291 		case KTR_GENIO:
292 			ktrgenio(m, ktrlen);
293 			break;
294 		case KTR_PSIG:
295 			ktrpsig(m, ktrlen);
296 			break;
297 		case KTR_CSW:
298 			ktrcsw(m);
299 			break;
300 		case KTR_EMUL:
301 			ktremul(m, ktrlen, size);
302 			break;
303 		case KTR_USER:
304 			ktruser(m, ktrlen);
305 			break;
306 		case KTR_EXEC_ARG:
307 		case KTR_EXEC_ENV:
308 			visdump_buf(m, ktrlen, col);
309 			break;
310 		case KTR_EXEC_FD:
311 			ktrexecfd(m);
312 			break;
313 		case KTR_MIB:
314 			ktrmib(m, ktrlen);
315 			break;
316 		default:
317 			putchar('\n');
318 			hexdump_buf(m, ktrlen, word_size ? word_size : 1);
319 		}
320 		if (tail)
321 			(void)fflush(stdout);
322 	}
323 	return (0);
324 }
325 
326 static int
327 fread_tail(void *buf, size_t num, size_t size)
328 {
329 	int i;
330 
331 	while ((i = fread(buf, size, num, stdin)) == 0 && tail) {
332 		(void)sleep(1);
333 		clearerr(stdin);
334 	}
335 	return (i);
336 }
337 
338 static int
339 dumpheader(struct ktr_header *kth)
340 {
341 	char unknown[64];
342 	const char *type;
343 	static struct timespec starttime, prevtime;
344 	struct timespec temp;
345 	int col;
346 
347 	if (__predict_false(kth->ktr_version != KTRFAC_VERSION(KTRFACv2)))
348 		errx(EXIT_FAILURE, "Unsupported ktrace version %x",
349 		     kth->ktr_version);
350 
351 	switch (kth->ktr_type) {
352 	case KTR_SYSCALL:
353 		type = "CALL";
354 		break;
355 	case KTR_SYSRET:
356 		type = "RET ";
357 		break;
358 	case KTR_NAMEI:
359 		type = "NAMI";
360 		break;
361 	case KTR_GENIO:
362 		type = "GIO ";
363 		break;
364 	case KTR_PSIG:
365 		type = "PSIG";
366 		break;
367 	case KTR_CSW:
368 		type = "CSW ";
369 		break;
370 	case KTR_EMUL:
371 		type = "EMUL";
372 		break;
373 	case KTR_USER:
374 		type = "MISC";
375 		break;
376 	case KTR_EXEC_ENV:
377 		type = "ENV";
378 		break;
379 	case KTR_EXEC_ARG:
380 		type = "ARG";
381 		break;
382 	case KTR_EXEC_FD:
383 		type = "FD";
384 		break;
385 	case KTR_SAUPCALL:
386 		type = "SAU";
387 		break;
388 	case KTR_MIB:
389 		type = "MIB";
390 		break;
391 	default:
392 		(void)snprintf(unknown, sizeof(unknown), "UNKNOWN(%d)",
393 		    kth->ktr_type);
394 		type = unknown;
395 	}
396 
397 	col = printf("%6d %6d ", kth->ktr_pid, kth->ktr_lid);
398 	col += printf("%-8.*s ", MAXCOMLEN, kth->ktr_comm);
399 	if (timestamp) {
400 		if (timestamp & TIMESTAMP_ABSOLUTE) {
401 			temp.tv_sec = kth->ktr_ts.tv_sec;
402 			temp.tv_nsec = kth->ktr_ts.tv_nsec;
403 			col += output_ts(&temp);
404 		}
405 
406 		if (timestamp & TIMESTAMP_ELAPSED) {
407 			if (starttime.tv_sec == 0) {
408 				starttime.tv_sec = kth->ktr_ts.tv_sec;
409 				starttime.tv_nsec = kth->ktr_ts.tv_nsec;
410 				temp.tv_sec = temp.tv_nsec = 0;
411 			} else
412 				timespecsub(&kth->ktr_ts, &starttime, &temp);
413 			col += output_ts(&temp);
414 		}
415 
416 		if (timestamp & TIMESTAMP_RELATIVE) {
417 			if (prevtime.tv_sec == 0)
418 				temp.tv_sec = temp.tv_nsec = 0;
419 			else
420 				timespecsub(&kth->ktr_ts, &prevtime, &temp);
421 			prevtime.tv_sec = kth->ktr_ts.tv_sec;
422 			prevtime.tv_nsec = kth->ktr_ts.tv_nsec;
423 			col += output_ts(&temp);
424 		}
425 	}
426 	col += printf("%-4s  ", type);
427 	return col;
428 }
429 
430 static int
431 output_ts(const struct timespec *ts)
432 {
433 	int col;
434 
435 	if (__predict_true(ts->tv_sec >= 0))
436 	    col = printf("%lld.%09ld ",
437 			 (long long)ts->tv_sec, (long)ts->tv_nsec);
438 	else {
439 	    /*
440 	     * The time represented by a timespec object ts is always
441 	     *
442 	     *   ts.tv_sec + ts.tv_nsec * 1e-9
443 	     *
444 	     * where ts.tv_sec may be negative but ts.tv_nsec is
445 	     * always in [0, 1e9).  So, for example, -1/4 second is
446 	     * represented by the struct timespec object
447 	     *
448 	     *   { .tv_sec = -1, .tv_nsec = 750000000 }
449 	     */
450 	    const struct timespec zero_ts = { 0, 0 };
451 	    struct timespec abs_ts;
452 	    timespecsub(&zero_ts, ts, &abs_ts);
453 	    col = printf("-%lld.%09ld ",
454 			 (long long)abs_ts.tv_sec, (long)abs_ts.tv_nsec);
455 	}
456 	return col;
457 }
458 
459 static void
460 output_long(u_long it, int as_x)
461 {
462 	if (cur_emul->flags & EMUL_FLAG_NETBSD32)
463 		printf(as_x ? "%#x" : "%d", (u_int)it);
464 	else
465 		printf(as_x ? "%#lx" : "%ld", it);
466 }
467 
468 static const char *
469 fcntlname(u_long cmd)
470 {
471 #define	FCNTLCASE(a)	case a:	return # a
472 	switch (cmd) {
473 	FCNTLCASE(F_DUPFD);
474 	FCNTLCASE(F_GETFD);
475 	FCNTLCASE(F_SETFD);
476 	FCNTLCASE(F_GETFL);
477 	FCNTLCASE(F_SETFL);
478 	FCNTLCASE(F_GETOWN);
479 	FCNTLCASE(F_SETOWN);
480 	FCNTLCASE(F_GETLK);
481 	FCNTLCASE(F_SETLK);
482 	FCNTLCASE(F_SETLKW);
483 	FCNTLCASE(F_CLOSEM);
484 	FCNTLCASE(F_MAXFD);
485 	FCNTLCASE(F_DUPFD_CLOEXEC);
486 	FCNTLCASE(F_GETNOSIGPIPE);
487 	FCNTLCASE(F_SETNOSIGPIPE);
488 	default:
489 		return NULL;
490 	}
491 }
492 
493 static void
494 ioctldecode(u_long cmd)
495 {
496 	char dirbuf[4], *dir = dirbuf;
497 	int c;
498 
499 	if (cmd & IOC_IN)
500 		*dir++ = 'W';
501 	if (cmd & IOC_OUT)
502 		*dir++ = 'R';
503 	*dir = '\0';
504 
505 	c = (cmd >> 8) & 0xff;
506 	if (isprint(c))
507 		printf("_IO%s('%c',", dirbuf, c);
508 	else
509 		printf("_IO%s(0x%02x,", dirbuf, c);
510 	output_long(cmd & 0xff, decimal == 0);
511 	if ((cmd & IOC_VOID) == 0) {
512 		putchar(',');
513 		output_long(IOCPARM_LEN(cmd), decimal == 0);
514 	}
515 	putchar(')');
516 }
517 
518 static void
519 putprot(int pr)
520 {
521 	const char *s = "";
522 
523 	if (pr == PROT_NONE) {
524 		fputs("PROT_NONE", stdout);
525 		return;
526 	}
527 
528 	if (pr & PROT_READ) {
529 		fputs("PROT_READ", stdout);
530 		s = "|";
531 		pr &= ~PROT_READ;
532 	}
533 
534 	if (pr & PROT_WRITE) {
535 		printf("%sPROT_WRITE", s);
536 		pr &= ~PROT_WRITE;
537 		s = "|";
538 	}
539 	if (pr & PROT_EXEC) {
540 		printf("%sPROT_EXEC", s);
541 		pr &= ~PROT_EXEC;
542 		s = "|";
543 	}
544 	if (pr) {
545 		printf("%s%#lx", s, (long)pr);
546 	}
547 }
548 
549 static void
550 ktrsyscall(struct ktr_syscall *ktr)
551 {
552 	int argcount;
553 	const struct emulation *emul = cur_emul;
554 	register_t *ap;
555 	char c;
556 	const char *cp;
557 	const char *sys_name;
558 
559 	argcount = ktr->ktr_argsize / sizeof (*ap);
560 
561 	emul_changed = 0;
562 
563 	if (numeric ||
564 	    ((ktr->ktr_code >= emul->nsysnames || ktr->ktr_code < 0))) {
565 		sys_name = "?";
566 		(void)printf("[%d]", ktr->ktr_code);
567 	} else {
568 		sys_name = emul->sysnames[ktr->ktr_code];
569 		(void)printf("%s", sys_name);
570 	}
571 #define NETBSD32_	"netbsd32_"
572 	if (cur_emul->flags & EMUL_FLAG_NETBSD32) {
573 		size_t len = strlen(NETBSD32_);
574 		if (strncmp(sys_name, NETBSD32_, len) == 0)
575 			sys_name += len;
576 	}
577 #undef NETBSD32_
578 
579 	ap = (register_t *)((char *)ktr + sizeof(struct ktr_syscall));
580 	if (argcount) {
581 		c = '(';
582 		if (plain) {
583 			;
584 
585 		} else if (strcmp(sys_name, "exit_group") == 0 ||
586 			   (strcmp(emul->name, "linux") != 0 &&
587 			    strcmp(emul->name, "linux32") != 0 &&
588 			    strcmp(sys_name, "exit") == 0)) {
589 			ectx_delete();
590 
591 		} else if (strcmp(sys_name, "ioctl") == 0 && argcount >= 2) {
592 			(void)putchar('(');
593 			output_long((long)*ap, !(decimal || small(*ap)));
594 			ap++;
595 			argcount--;
596 			if ((cp = ioctlname(*ap)) != NULL)
597 				(void)printf(",%s", cp);
598 			else {
599 				(void)putchar(',');
600 				ioctldecode(*ap);
601 			}
602 			ap++;
603 			argcount--;
604 			c = ',';
605 
606 		} else if (strcmp(sys_name, "fcntl") == 0 && argcount >= 2) {
607 			(void)putchar('(');
608 			output_long((long)*ap, !(decimal || small(*ap)));
609 			ap++;
610 			argcount--;
611 			if ((cp = fcntlname(*ap)) != NULL)
612 				(void)printf(",%s", cp);
613 			else {
614 				(void)printf(",%#lx", (unsigned long)*ap);
615 			}
616 			ap++;
617 			argcount--;
618 			c = ',';
619 		} else if ((strstr(sys_name, "sigaction") != NULL ||
620 		    strstr(sys_name, "sigvec") != NULL) && argcount >= 1) {
621 			(void)printf("(SIG%s", signame(ap[0], 1));
622 			ap += 1;
623 			argcount -= 1;
624 			c = ',';
625 
626 		} else if ((strcmp(sys_name, "kill") == 0 ||
627 		    strcmp(sys_name, "killpg") == 0) && argcount >= 2) {
628 			putchar('(');
629 			output_long((long)ap[0], !(decimal || small(*ap)));
630 			(void)printf(", SIG%s", signame(ap[1], 1));
631 			ap += 2;
632 			argcount -= 2;
633 			c = ',';
634 		} else if (strcmp(sys_name, "mprotect") == 0 && argcount >= 3) {
635 			putchar('(');
636 			output_long((long)ap[0], !(decimal || small(ap[0])));
637 			c = ',';
638 			putchar(c);
639 			output_long((long)ap[1], !(decimal || small(ap[1])));
640 			putchar(c);
641 			putprot(ap[2]);
642 			ap += 3;
643 			argcount -= 3;
644 			c = ',';
645 		} else if (strcmp(sys_name, "mmap") == 0 && argcount >= 6) {
646 			char buf[1024];
647 			putchar('(');
648 			output_long((long)ap[0], !(decimal || small(ap[0])));
649 			c = ',';
650 			putchar(c);
651 			output_long((long)ap[1], !(decimal || small(ap[1])));
652 			putchar(c);
653 			putprot(ap[2]);
654 			snprintb(buf, sizeof(buf), MAP_FMT, ap[3]);
655 			printf(",%s", buf);
656 			ap += 4;
657 			argcount -= 4;
658 			c = ',';
659 		} else if (strcmp(sys_name, "ptrace") == 0 && argcount >= 1) {
660 			putchar('(');
661 			if (strcmp(emul->name, "linux") == 0 ||
662 			    strcmp(emul->name, "linux32") == 0) {
663 				if ((long)*ap >= 0 && *ap <
664 				    (register_t)(sizeof(linux_ptrace_ops) /
665 				    sizeof(linux_ptrace_ops[0])))
666 					(void)printf("%s",
667 					    linux_ptrace_ops[*ap]);
668 				else
669 					output_long((long)*ap, 1);
670 			} else {
671 				if ((long)*ap >= 0 && *ap < (register_t)
672 				    __arraycount(ptrace_ops))
673 					(void)printf("%s", ptrace_ops[*ap]);
674 #ifdef PT_MACHDEP_STRINGS
675 				else if (*ap >= PT_FIRSTMACH &&
676 				    *ap - PT_FIRSTMACH < (register_t)
677 				    __arraycount(ptrace_machdep_ops))
678 					(void)printf("%s", ptrace_machdep_ops[*ap - PT_FIRSTMACH]);
679 #endif
680 				else
681 					output_long((long)*ap, 1);
682 			}
683 			ap++;
684 			argcount--;
685 			c = ',';
686 
687 		}
688 		while (argcount > 0) {
689 			putchar(c);
690 			output_long((long)*ap, !(decimal || small(*ap)));
691 			ap++;
692 			argcount--;
693 			c = ',';
694 		}
695 		(void)putchar(')');
696 	}
697 	(void)putchar('\n');
698 }
699 
700 static void
701 ktrsysret(struct ktr_sysret *ktr, int len)
702 {
703 	const struct emulation *emul;
704 	int error = ktr->ktr_error;
705 	int code = ktr->ktr_code;
706 
707 	if (emul_changed)  {
708 		/* In order to get system call name right in execve return */
709 		emul = prev_emul;
710 		emul_changed = 0;
711 	} else
712 		emul = cur_emul;
713 
714 	if (numeric || ((code >= emul->nsysnames || code < 0 || plain > 1)))
715 		(void)printf("[%d] ", code);
716 	else
717 		(void)printf("%s ", emul->sysnames[code]);
718 
719 	switch (error) {
720 	case 0:
721 		rprint(ktr->ktr_retval);
722 		if (len > (int)offsetof(struct ktr_sysret, ktr_retval_1) &&
723 		    ktr->ktr_retval_1 != 0) {
724 			(void)printf(", ");
725 			rprint(ktr->ktr_retval_1);
726 		}
727 		break;
728 
729 	default:
730 		eprint(error);
731 		break;
732 	}
733 	(void)putchar('\n');
734 }
735 
736 static void
737 ktrexecfd(struct ktr_execfd *ktr)
738 {
739 	static const char *dnames[] = { DTYPE_NAMES };
740 	if (ktr->ktr_dtype < __arraycount(dnames))
741 		printf("%s %d\n", dnames[ktr->ktr_dtype], ktr->ktr_fd);
742 	else
743 		printf("UNKNOWN(%u) %d\n", ktr->ktr_dtype, ktr->ktr_fd);
744 }
745 
746 static void
747 rprint(register_t ret)
748 {
749 
750 	if (!plain) {
751 		output_long(ret, 0);
752 		if (!small(ret)) {
753 			putchar('/');
754 			output_long(ret, 1);
755 		}
756 	} else {
757 		output_long(ret, !(decimal || small(ret)));
758 	}
759 }
760 
761 /*
762  * We print the original emulation's error numerically, but we
763  * translate it to netbsd to print it symbolically.
764  */
765 static void
766 eprint(int e)
767 {
768 	int i = e;
769 
770 	if (cur_emul->errnomap) {
771 
772 		/* No remapping for ERESTART and EJUSTRETURN */
773 		/* Kludge for linux that has negative error numbers */
774 		if (cur_emul->errnomap[2] > 0 && e < 0)
775 			goto normal;
776 
777 		for (i = 0; i < cur_emul->nerrnomap; i++)
778 			if (e == cur_emul->errnomap[i])
779 				break;
780 
781 		if (i == cur_emul->nerrnomap) {
782 			printf("-1 unknown errno %d", e);
783 			return;
784 		}
785 	}
786 
787 normal:
788 	switch (i) {
789 	case ERESTART:
790 		(void)printf("RESTART");
791 		break;
792 
793 	case EJUSTRETURN:
794 		(void)printf("JUSTRETURN");
795 		break;
796 
797 	default:
798 		(void)printf("-1 errno %d", e);
799 		if (!plain)
800 			(void)printf(" %s", strerror(i));
801 	}
802 }
803 
804 static void
805 ktrnamei(char *cp, int len)
806 {
807 
808 	(void)printf("\"%.*s\"\n", len, cp);
809 }
810 
811 static void
812 ktremul(char *name, size_t len, size_t bufsize)
813 {
814 
815 	if (len >= bufsize)
816 		len = bufsize - 1;
817 
818 	name[len] = '\0';
819 	setemul(name, ktr_header.ktr_pid, 1);
820 	emul_changed = 1;
821 
822 	(void)printf("\"%s\"\n", name);
823 }
824 
825 static void
826 hexdump_buf(const void *vdp, int datalen, int word_sz)
827 {
828 	const char hex[] = "0123456789abcdef";
829 	char chars[16], prev[16];
830 	char bytes[16 * 3 + 4];
831 	const unsigned char *dp = vdp;
832 	const unsigned char *datalim = dp + datalen;
833 	const unsigned char *line_end;
834 	int off, l = 0, c;
835 	char *cp, *bp;
836 	int divmask = word_sz - 1;	/* block size in bytes */
837 	int gdelim = 3;			/* gap between blocks */
838 	int bsize = 2;			/* increment for each byte */
839 	int width;
840 	int dupl = 0;
841 #if _BYTE_ORDER == _LITTLE_ENDIAN
842 	int bswap = word_sz - 1;
843 #else
844 #define	bswap 0
845 #endif
846 
847 	switch (word_sz) {
848 	case 2:
849 		gdelim = 2;
850 		break;
851 	case 1:
852 		divmask = 7;
853 		bsize = 3;
854 		gdelim = 1;
855 		break;
856 	default:
857 		break;
858 	}
859 	width = 16 * bsize + (16 / (divmask + 1)) * gdelim;
860 	if (word_sz != 1)
861 		width += 2;
862 
863 	for (off = 0; dp < datalim; off += l) {
864 		memset(bytes, ' ', sizeof bytes);
865 		line_end = dp + 16;
866 		if (line_end >= datalim) {
867 			line_end = datalim;
868 			dupl |= 1;	/* need to print */
869 		} else {
870 			if (dupl == 0 || memcmp(dp, prev, sizeof chars))
871 				dupl |= 1;
872 		}
873 
874 		if (!(dupl & 1)) {
875 			/* This is a duplicate of the line above, count 'em */
876 			dupl += 2;
877 			dp = line_end;
878 			continue;
879 		}
880 
881 		if (dupl > 3) {
882 			/* previous line as a duplicate */
883 			if (dupl == 5)
884 				/* Only one duplicate, print line */
885 				printf("\t%-5.3x%.*s%.*s\n",
886 					off - l, width, bytes, l, chars);
887 			else
888 				printf("\t%.*s\n",
889 					snprintf(NULL, 0, "%3x", off), "*****");
890 		}
891 
892 		for (l = 0, bp = bytes, cp = chars; dp < line_end; l++) {
893 			c = *dp++;
894 			prev[l] = c;
895 			if ((l & divmask) == 0)
896 				bp += gdelim;
897 			bp[(l ^ bswap) * bsize] = hex[c >> 4];
898 			bp[(l ^ bswap) * bsize + 1] = hex[c & 0xf];
899 			*cp++ = isgraph(c) ? c : '.';
900 		}
901 
902 		printf("\t%-5.3x%.*s%.*s\n", off, width, bytes, l, chars);
903 		dupl = 2;
904 	}
905 }
906 
907 static void
908 visdump_buf(const void *vdp, int datalen, int col)
909 {
910 	const unsigned char *dp = vdp;
911 	char *cp;
912 	int width;
913 	char visbuf[5];
914 	static int screenwidth = 0;
915 
916 	if (screenwidth == 0) {
917 		struct winsize ws;
918 
919 		if (!plain && ioctl(fileno(stderr), TIOCGWINSZ, &ws) != -1 &&
920 		    ws.ws_col > 8)
921 			screenwidth = ws.ws_col;
922 		else
923 			screenwidth = 80;
924 	}
925 
926 	(void)printf("\"");
927 	col++;
928 	for (; datalen > 0; datalen--, dp++) {
929 		(void)svis(visbuf, *dp, VIS_CSTYLE,
930 		    datalen > 1 ? *(dp + 1) : 0, "\"\n");
931 		cp = visbuf;
932 		/*
933 		 * Keep track of printables and
934 		 * space chars (like fold(1)).
935 		 */
936 		if (col == 0) {
937 			(void)putchar('\t');
938 			col = 8;
939 		}
940 		switch (*cp) {
941 		case '\n':
942 			col = 0;
943 			(void)putchar('\n');
944 			continue;
945 		case '\t':
946 			width = 8 - (col & 07);
947 			break;
948 		default:
949 			width = strlen(cp);
950 		}
951 		if (col + width > (screenwidth - 2)) {
952 			(void)printf("\\\n\t");
953 			col = 8;
954 			if (*cp == '\t')
955 				width = 8;
956 		}
957 		col += width;
958 		do {
959 			(void)putchar(*cp++);
960 		} while (*cp);
961 	}
962 	if (col == 0)
963 		(void)printf("       ");
964 	(void)printf("\"\n");
965 }
966 
967 static void
968 ktrgenio(struct ktr_genio *ktr, int len)
969 {
970 	int datalen = len - sizeof (struct ktr_genio);
971 	char *dp = (char *)ktr + sizeof (struct ktr_genio);
972 
973 	if (ktr->ktr_fd != -1)
974 		printf("fd %d ", ktr->ktr_fd);
975 	printf("%s %d bytes\n",
976 	    ktr->ktr_rw == UIO_READ ? "read" : "wrote", datalen);
977 	if (maxdata == 0)
978 		return;
979 	if (maxdata > 0 && datalen > maxdata)
980 		datalen = maxdata;
981 	if (word_size) {
982 		hexdump_buf(dp, datalen, word_size);
983 		return;
984 	}
985 	(void)printf("       ");
986 	visdump_buf(dp, datalen, 7);
987 }
988 
989 static void
990 ktrpsig(void *v, int len)
991 {
992 	int signo, first;
993 	struct {
994 		struct ktr_psig ps;
995 		siginfo_t si;
996 	} *psig = v;
997 	siginfo_t *si = &psig->si;
998 	const char *code;
999 
1000 	(void)printf("SIG%s ", signame(psig->ps.signo, 0));
1001 	if (psig->ps.action == SIG_DFL)
1002 		(void)printf("SIG_DFL");
1003 	else {
1004 		(void)printf("caught handler=%p mask=(", psig->ps.action);
1005 		first = 1;
1006 		for (signo = 1; signo < NSIG; signo++) {
1007 			if (sigismember(&psig->ps.mask, signo)) {
1008 				if (first)
1009 					first = 0;
1010 				else
1011 					(void)printf(",");
1012 				(void)printf("%d", signo);
1013 			}
1014 		}
1015 		(void)printf(")");
1016 	}
1017 	switch (len) {
1018 	case sizeof(struct ktr_psig):
1019 		if (psig->ps.code)
1020 			printf(" code=0x%x", psig->ps.code);
1021 		printf(psig->ps.action == SIG_DFL ? "\n" : ")\n");
1022 		return;
1023 	case sizeof(*psig):
1024 		if (si->si_code == 0) {
1025 			printf(": code=SI_USER sent by pid=%d, uid=%d)\n",
1026 			    si->si_pid, si->si_uid);
1027 			return;
1028 		}
1029 
1030 		if (si->si_code < 0) {
1031 			switch (si->si_code) {
1032 			case SI_TIMER:
1033 			case SI_QUEUE:
1034 				printf(": code=%s sent by pid=%d, uid=%d with "
1035 				    "sigval %p)\n", si->si_code == SI_TIMER ?
1036 				    "SI_TIMER" : "SI_QUEUE", si->si_pid,
1037 				    si->si_uid, si->si_value.sival_ptr);
1038 				return;
1039 			case SI_ASYNCIO:
1040 			case SI_MESGQ:
1041 				printf(": code=%s with sigval %p)\n",
1042 				    si->si_code == SI_ASYNCIO ?
1043 				    "SI_ASYNCIO" : "SI_MESGQ",
1044 				    si->si_value.sival_ptr);
1045 				return;
1046 			case SI_LWP:
1047 				printf(": code=SI_LWP sent by pid=%d, "
1048 				    "uid=%d)\n", si->si_pid, si->si_uid);
1049 				return;
1050 			default:
1051 				code = NULL;
1052 				break;
1053 			}
1054 			if (code)
1055 				printf(": code=%s unimplemented)\n", code);
1056 			else
1057 				printf(": code=%d unimplemented)\n",
1058 				    si->si_code);
1059 			return;
1060 		}
1061 
1062 		if (si->si_code == SI_NOINFO) {
1063 			printf(": code=SI_NOINFO\n");
1064 			return;
1065 		}
1066 
1067 		code = siginfocodename(si->si_signo, si->si_code);
1068 		switch (si->si_signo) {
1069 		case SIGCHLD:
1070 			printf(": code=%s child pid=%d, uid=%d, "
1071 			    " status=%u, utime=%lu, stime=%lu)\n",
1072 			    code, si->si_pid,
1073 			    si->si_uid, si->si_status,
1074 			    (unsigned long) si->si_utime,
1075 			    (unsigned long) si->si_stime);
1076 			return;
1077 		case SIGILL:
1078 		case SIGFPE:
1079 		case SIGSEGV:
1080 		case SIGBUS:
1081 		case SIGTRAP:
1082 			printf(": code=%s, addr=%p, trap=%d)\n",
1083 			    code, si->si_addr, si->si_trap);
1084 			return;
1085 		case SIGIO:
1086 			printf(": code=%s, fd=%d, band=%lx)\n",
1087 			    code, si->si_fd, si->si_band);
1088 			return;
1089 		default:
1090 			printf(": code=%s, errno=%d)\n",
1091 			    code, si->si_errno);
1092 			return;
1093 		}
1094 		/*NOTREACHED*/
1095 	default:
1096 		warnx("Unhandled size %d for ktrpsig", len);
1097 		break;
1098 	}
1099 }
1100 
1101 static void
1102 ktrcsw(struct ktr_csw *cs)
1103 {
1104 
1105 	(void)printf("%s %s\n", cs->out ? "stop" : "resume",
1106 	    cs->user ? "user" : "kernel");
1107 }
1108 
1109 static void
1110 ktruser_msghdr(const char *name, const void *buf, size_t len)
1111 {
1112 	struct msghdr m;
1113 
1114 	if (len != sizeof(m))
1115 		warnx("%.*s: len %zu != %zu", KTR_USER_MAXIDLEN, name, len,
1116 		    sizeof(m));
1117 	memcpy(&m, buf, len);
1118 	printf("%.*s: [name=%p, namelen=%zu, iov=%p, iovlen=%zu, control=%p, "
1119 	    "controllen=%zu, flags=%x]\n", KTR_USER_MAXIDLEN, name,
1120 	    m.msg_name, (size_t)m.msg_namelen, m.msg_iov, (size_t)m.msg_iovlen,
1121 	    m.msg_control, (size_t)m.msg_controllen, m.msg_flags);
1122 }
1123 
1124 static void
1125 ktruser_soname(const char *name, const void *buf, size_t len)
1126 {
1127 	char fmt[512];
1128 	sockaddr_snprintf(fmt, sizeof(fmt), "%a", buf);
1129 	printf("%.*s: [%s]\n", KTR_USER_MAXIDLEN, name, fmt);
1130 }
1131 
1132 static void
1133 ktruser_control(const char *name, const void *buf, size_t len)
1134 {
1135 	struct cmsghdr m;
1136 
1137 	if (len < sizeof(m))
1138 		warnx("%.*s: len %zu < %zu", KTR_USER_MAXIDLEN, name, len,
1139 		    sizeof(m));
1140 	memcpy(&m, buf, sizeof(m));
1141 	printf("%.*s: [len=%zu, level=%d, type=%d]\n", KTR_USER_MAXIDLEN, name,
1142 	    (size_t)m.cmsg_len, m.cmsg_level, m.cmsg_type);
1143 }
1144 
1145 static void
1146 ktruser_malloc(const char *name, const void *buf, size_t len)
1147 {
1148 	struct ut { void *p; size_t s; void *r; } m;
1149 
1150 	if (len != sizeof(m))
1151 		warnx("%.*s: len %zu != %zu", KTR_USER_MAXIDLEN, name, len,
1152 		    sizeof(m));
1153 	memcpy(&m, buf, len < sizeof(m) ? len : sizeof(m));
1154 	if (m.p == NULL && m.s == 0 && m.r == NULL)
1155 		printf("%.*s: malloc_init()\n", KTR_USER_MAXIDLEN, name);
1156 	else if (m.p != NULL && m.s != 0)
1157 		printf("%.*s: %p = realloc(%p, %zu)\n", KTR_USER_MAXIDLEN, name,
1158 		    m.r, m.p, m.s);
1159 	else if (m.s == 0)
1160 		printf("%.*s: free(%p)\n", KTR_USER_MAXIDLEN, name, m.p);
1161 	else
1162 		printf("%.*s: %p = malloc(%zu)\n", KTR_USER_MAXIDLEN, name,
1163 		    m.r, m.s);
1164 }
1165 
1166 static void
1167 ktruser_misc(const char *name, const void *buf, size_t len)
1168 {
1169 	size_t i;
1170 	const char *dta = buf;
1171 
1172 	printf("%.*s: %zu, ", KTR_USER_MAXIDLEN, name, len);
1173 	for (i = 0; i < len; i++)
1174 		printf("%02x", (unsigned char)dta[i]);
1175 	printf("\n");
1176 }
1177 
1178 static struct {
1179 	const char *name;
1180 	void (*func)(const char *, const void *, size_t);
1181 } nv[] = {
1182 	{ "msghdr", ktruser_msghdr },
1183 	{ "mbsoname", ktruser_soname },
1184 	{ "mbcontrol", ktruser_control },
1185 	{ "malloc", ktruser_malloc },
1186 	{ NULL,	ktruser_misc },
1187 };
1188 
1189 static void
1190 ktruser(struct ktr_user *usr, int len)
1191 {
1192 	unsigned char *dta;
1193 
1194 	len -= sizeof(struct ktr_user);
1195 	dta = (unsigned char *)(usr + 1);
1196 	if (word_size) {
1197 		printf("%.*s:", KTR_USER_MAXIDLEN, usr->ktr_id);
1198 		printf("\n");
1199 		hexdump_buf(dta, len, word_size);
1200 		return;
1201 	}
1202 	for (size_t j = 0; j < __arraycount(nv); j++)
1203 		if (nv[j].name == NULL ||
1204 		    strncmp(nv[j].name, usr->ktr_id, KTR_USER_MAXIDLEN) == 0) {
1205 			(*nv[j].func)(usr->ktr_id, dta, len);
1206 			break;
1207 		}
1208 }
1209 
1210 static void
1211 ktrmib(int *namep, int len)
1212 {
1213 	size_t i;
1214 
1215 	for (i = 0; i < (len / sizeof(*namep)); i++)
1216 		printf("%s%d", (i == 0) ? "" : ".", namep[i]);
1217 	printf("\n");
1218 }
1219 
1220 static const char *
1221 signame(long sig, int xlat)
1222 {
1223 	static char buf[64];
1224 
1225 	if (sig == 0)
1226 		return " 0";
1227 	else if (sig < 0 || sig >= NSIG) {
1228 		(void)snprintf(buf, sizeof(buf), "*unknown %ld*", sig);
1229 		return buf;
1230 	} else
1231 		return sys_signame[(xlat && cur_emul->signalmap != NULL) ?
1232 		    cur_emul->signalmap[sig] : sig];
1233 }
1234 
1235 static void
1236 usage(void)
1237 {
1238 	if (strcmp(getprogname(), "ioctlname") == 0) {
1239 		(void)fprintf(stderr, "Usage: %s [-e emulation] <ioctl> ...\n",
1240 		    getprogname());
1241 	} else {
1242 		(void)fprintf(stderr, "Usage: %s [-dElNnRT] [-e emulation] "
1243 		   "[-f file] [-m maxdata] [-p pid]\n             [-t trstr] "
1244 		   "[-x | -X size] [file]\n", getprogname());
1245 	}
1246 	exit(1);
1247 }
1248