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