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