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