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