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