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