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