xref: /netbsd-src/usr.bin/kdump/kdump.c (revision 37b34d511dea595d3ba03a661cf3b775038ea5f8)
1 /*	$NetBSD: kdump.c,v 1.41 2002/09/27 20:31:44 atatat 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. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *	This product includes software developed by the University of
18  *	California, Berkeley and its contributors.
19  * 4. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 
36 #include <sys/cdefs.h>
37 #ifndef lint
38 __COPYRIGHT("@(#) Copyright (c) 1988, 1993\n\
39 	The Regents of the University of California.  All rights reserved.\n");
40 #endif /* not lint */
41 
42 #ifndef lint
43 #if 0
44 static char sccsid[] = "@(#)kdump.c	8.4 (Berkeley) 4/28/95";
45 #else
46 __RCSID("$NetBSD: kdump.c,v 1.41 2002/09/27 20:31:44 atatat Exp $");
47 #endif
48 #endif /* not lint */
49 
50 #include <sys/param.h>
51 #define _KERNEL
52 #include <sys/errno.h>
53 #undef _KERNEL
54 #include <sys/time.h>
55 #include <sys/uio.h>
56 #include <sys/ktrace.h>
57 #include <sys/ioctl.h>
58 #include <sys/ptrace.h>
59 
60 #include <err.h>
61 #include <signal.h>
62 #include <stdio.h>
63 #include <stdlib.h>
64 #include <string.h>
65 #include <unistd.h>
66 #include <vis.h>
67 
68 #include "ktrace.h"
69 #include "setemul.h"
70 
71 #include <sys/syscall.h>
72 
73 int timestamp, decimal, plain, tail, maxdata;
74 pid_t do_pid = -1;
75 const char *tracefile = NULL;
76 struct ktr_header ktr_header;
77 int emul_changed = 0;
78 
79 #define eqs(s1, s2)	(strcmp((s1), (s2)) == 0)
80 
81 static const char *ptrace_ops[] = {
82 	"PT_TRACE_ME",	"PT_READ_I",	"PT_READ_D",	"PT_READ_U",
83 	"PT_WRITE_I",	"PT_WRITE_D",	"PT_WRITE_U",	"PT_CONTINUE",
84 	"PT_KILL",	"PT_ATTACH",	"PT_DETACH",
85 };
86 
87 static const char *linux_ptrace_ops[] = {
88 	"PTRACE_TRACEME",
89 	"PTRACE_PEEKTEXT", "PTRACE_PEEKDATA", "PTRACE_PEEKUSER",
90 	"PTRACE_POKETEXT", "PTRACE_POKEDATA", "PTRACE_POKEUSER",
91 	"PTRACE_CONT", "PTRACE_KILL", "PTRACE_SINGLESTEP",
92 	NULL, NULL,
93 	"PTRACE_GETREGS", "PTRACE_SETREGS", "PTRACE_GETFPREGS",
94 	"PTRACE_SETFPREGS", "PTRACE_ATTACH", "PTRACE_DETACH",
95 	"PTRACE_SYSCALL",
96 };
97 
98 int	main __P((int, char **));
99 int	fread_tail __P((char *, int, int));
100 void	dumpheader __P((struct ktr_header *));
101 void	ioctldecode __P((u_long));
102 void	ktrsyscall __P((struct ktr_syscall *));
103 void	ktrsysret __P((struct ktr_sysret *));
104 void	ktrnamei __P((char *, int));
105 void	ktremul __P((char *, int, int));
106 void	ktrgenio __P((struct ktr_genio *, int));
107 void	ktrpsig __P((struct ktr_psig *));
108 void	ktrcsw __P((struct ktr_csw *));
109 void	ktruser __P((struct ktr_user *, int));
110 void	usage __P((void));
111 void	eprint __P((int));
112 char	*ioctlname __P((long));
113 static const char *signame __P((long, int));
114 
115 int
116 main(argc, argv)
117 	int argc;
118 	char *argv[];
119 {
120 	int ch, ktrlen, size;
121 	void *m;
122 	int trpoints = ALL_POINTS;
123 	const char *emul_name = "netbsd";
124 
125 	while ((ch = getopt(argc, argv, "e:f:dlm:np:RTt:")) != -1)
126 		switch (ch) {
127 		case 'e':
128 			emul_name = strdup(optarg); /* it's safer to copy it */
129 			break;
130 		case 'f':
131 			tracefile = optarg;
132 			break;
133 		case 'd':
134 			decimal = 1;
135 			break;
136 		case 'l':
137 			tail = 1;
138 			break;
139 		case 'p':
140 			do_pid = atoi(optarg);
141 			break;
142 		case 'm':
143 			maxdata = atoi(optarg);
144 			break;
145 		case 'n':
146 			plain++;
147 			break;
148 		case 'R':
149 			timestamp = 2;	/* relative timestamp */
150 			break;
151 		case 'T':
152 			timestamp = 1;
153 			break;
154 		case 't':
155 			trpoints = getpoints(optarg);
156 			if (trpoints < 0)
157 				errx(1, "unknown trace point in %s", optarg);
158 			break;
159 		default:
160 			usage();
161 		}
162 	argv += optind;
163 	argc -= optind;
164 
165 	if (tracefile == NULL) {
166 		if (argc == 1) {
167 			tracefile = argv[0];
168 			argv++;
169 			argc--;
170 		}
171 		else
172 			tracefile = DEF_TRACEFILE;
173 	}
174 
175 	if (argc > 0)
176 		usage();
177 
178 	setemul(emul_name, 0, 0);
179 
180 	m = malloc(size = 1024);
181 	if (m == NULL)
182 		errx(1, "malloc: %s", strerror(ENOMEM));
183 	if (!freopen(tracefile, "r", stdin))
184 		err(1, "%s", tracefile);
185 	while (fread_tail((char *)&ktr_header, sizeof(struct ktr_header), 1)) {
186 		if (trpoints & (1<<ktr_header.ktr_type))
187 			if (do_pid == -1 || ktr_header.ktr_pid == do_pid)
188 				dumpheader(&ktr_header);
189 		if ((ktrlen = ktr_header.ktr_len) < 0)
190 			errx(1, "bogus length 0x%x", ktrlen);
191 		if (ktrlen > size) {
192 			while(ktrlen > size) size *= 2;
193 			m = (void *)realloc(m, size);
194 			if (m == NULL)
195 				errx(1, "realloc: %s", strerror(ENOMEM));
196 		}
197 		if (ktrlen && fread_tail(m, ktrlen, 1) == 0)
198 			errx(1, "data too short");
199 		if ((trpoints & (1<<ktr_header.ktr_type)) == 0)
200 			continue;
201 
202 		/* update context to match currently processed record */
203 		if (do_pid != -1 && ktr_header.ktr_pid != do_pid)
204 			continue;
205 		ectx_sanify(ktr_header.ktr_pid);
206 
207 		switch (ktr_header.ktr_type) {
208 		case KTR_SYSCALL:
209 			ktrsyscall((struct ktr_syscall *)m);
210 			break;
211 		case KTR_SYSRET:
212 			ktrsysret((struct ktr_sysret *)m);
213 			break;
214 		case KTR_NAMEI:
215 			ktrnamei(m, ktrlen);
216 			break;
217 		case KTR_GENIO:
218 			ktrgenio((struct ktr_genio *)m, ktrlen);
219 			break;
220 		case KTR_PSIG:
221 			ktrpsig((struct ktr_psig *)m);
222 			break;
223 		case KTR_CSW:
224 			ktrcsw((struct ktr_csw *)m);
225 			break;
226 		case KTR_EMUL:
227 			ktremul(m, ktrlen, size);
228 			break;
229 		case KTR_USER:
230 			ktruser((struct ktr_user *)m, ktrlen);
231 			break;
232 		}
233 		if (tail)
234 			(void)fflush(stdout);
235 	}
236 	return (0);
237 }
238 
239 int
240 fread_tail(buf, size, num)
241 	char *buf;
242 	int num, size;
243 {
244 	int i;
245 
246 	while ((i = fread(buf, size, num, stdin)) == 0 && tail) {
247 		(void)sleep(1);
248 		clearerr(stdin);
249 	}
250 	return (i);
251 }
252 
253 void
254 dumpheader(kth)
255 	struct ktr_header *kth;
256 {
257 	char unknown[64], *type;
258 	static struct timeval prevtime;
259 	struct timeval temp;
260 
261 	switch (kth->ktr_type) {
262 	case KTR_SYSCALL:
263 		type = "CALL";
264 		break;
265 	case KTR_SYSRET:
266 		type = "RET ";
267 		break;
268 	case KTR_NAMEI:
269 		type = "NAMI";
270 		break;
271 	case KTR_GENIO:
272 		type = "GIO ";
273 		break;
274 	case KTR_PSIG:
275 		type = "PSIG";
276 		break;
277 	case KTR_CSW:
278 		type = "CSW";
279 		break;
280 	case KTR_EMUL:
281 		type = "EMUL";
282 		break;
283 	case KTR_USER:
284 		type = "USER";
285 		break;
286 	default:
287 		(void)sprintf(unknown, "UNKNOWN(%d)", kth->ktr_type);
288 		type = unknown;
289 	}
290 
291 	(void)printf("%6d %-8.*s ", kth->ktr_pid, MAXCOMLEN, kth->ktr_comm);
292 	if (timestamp) {
293 		if (timestamp == 2) {
294 			timersub(&kth->ktr_time, &prevtime, &temp);
295 			prevtime = kth->ktr_time;
296 		} else
297 			temp = kth->ktr_time;
298 		(void)printf("%ld.%06ld ",
299 		    (long int)temp.tv_sec, (long int)temp.tv_usec);
300 	}
301 	(void)printf("%s  ", type);
302 }
303 
304 void
305 ioctldecode(cmd)
306 	u_long cmd;
307 {
308 	char dirbuf[4], *dir = dirbuf;
309 
310 	if (cmd & IOC_IN)
311 		*dir++ = 'W';
312 	if (cmd & IOC_OUT)
313 		*dir++ = 'R';
314 	*dir = '\0';
315 
316 	printf(decimal ? ",_IO%s('%c',%ld" : ",_IO%s('%c',%#lx",
317 	    dirbuf, (int) ((cmd >> 8) & 0xff), cmd & 0xff);
318 	if ((cmd & IOC_VOID) == 0)
319 		printf(decimal ? ",%ld)" : ",%#lx)", (cmd >> 16) & 0xff);
320 	else
321 		printf(")");
322 }
323 
324 void
325 ktrsyscall(ktr)
326 	struct ktr_syscall *ktr;
327 {
328 	int argsize = ktr->ktr_argsize;
329 	register_t *ap;
330 
331 	if (ktr->ktr_code >= current->nsysnames || ktr->ktr_code < 0)
332 		(void)printf("[%d]", ktr->ktr_code);
333 	else
334 		(void)printf("%s", current->sysnames[ktr->ktr_code]);
335 	ap = (register_t *)((char *)ktr + sizeof(struct ktr_syscall));
336 	if (argsize) {
337 		char c = '(';
338 		if (!plain) {
339 			char *cp;
340 
341 			switch (ktr->ktr_code) {
342 			case SYS_ioctl:
343 				if (decimal)
344 					(void)printf("(%ld", (long)*ap);
345 				else
346 					(void)printf("(%#lx", (long)*ap);
347 				ap++;
348 				argsize -= sizeof(register_t);
349 				if ((cp = ioctlname(*ap)) != NULL)
350 					(void)printf(",%s", cp);
351 				else
352 					ioctldecode(*ap);
353 				c = ',';
354 				ap++;
355 				argsize -= sizeof(register_t);
356 				break;
357 
358 			case SYS_ptrace:
359 				if (strcmp(current->name, "linux") == 0) {
360 				  if (*ap >= 0 && *ap <=
361 				      sizeof(linux_ptrace_ops) /
362 				      sizeof(linux_ptrace_ops[0]))
363 					(void)printf("(%s",
364 					    linux_ptrace_ops[*ap]);
365 				  else
366 					(void)printf("(%ld", (long)*ap);
367 				} else {
368 				  if (*ap >= 0 && *ap <=
369 				    sizeof(ptrace_ops) / sizeof(ptrace_ops[0]))
370 					(void)printf("(%s", ptrace_ops[*ap]);
371 				  else
372 					(void)printf("(%ld", (long)*ap);
373 				}
374 				c = ',';
375 				ap++;
376 				argsize -= sizeof(register_t);
377 				break;
378 
379 			case SYS_kill:
380 				if (decimal)
381 					(void)printf("(%ld, SIG%s",
382 					    (long)ap[0], signame(ap[1], 1));
383 				else
384 					(void)printf("(%#lx, SIG%s",
385 					    (long)ap[0], signame(ap[1], 1));
386 				ap += 2;
387 				argsize -= 2 * sizeof(register_t);
388 				break;
389 
390 			default:
391 				/* No special handling */
392 				break;
393 			}
394 		}
395 		while (argsize) {
396 			if (decimal)
397 				(void)printf("%c%ld", c, (long)*ap);
398 			else
399 				(void)printf("%c%#lx", c, (long)*ap);
400 			c = ',';
401 			ap++;
402 			argsize -= sizeof(register_t);
403 		}
404 		(void)putchar(')');
405 	}
406 	(void)putchar('\n');
407 }
408 
409 void
410 ktrsysret(ktr)
411 	struct ktr_sysret *ktr;
412 {
413 	const struct emulation *revelant;
414 	register_t ret = ktr->ktr_retval;
415 	int error = ktr->ktr_error;
416 	int code = ktr->ktr_code;
417 
418 	if (emul_changed)
419 		revelant = previous;
420 	else
421 		revelant = current;
422 	emul_changed = 0;
423 
424 	if (code >= revelant->nsysnames || code < 0 || plain > 1)
425 		(void)printf("[%d] ", code);
426 	else
427 		(void)printf("%s ", revelant->sysnames[code]);
428 
429 	switch (error) {
430 	case 0:
431 		if (!plain) {
432 			(void)printf("%ld", (long)ret);
433 			if (ret < 0 || ret > 9)
434 				(void)printf("/%#lx", (long)ret);
435 		} else {
436 			if (decimal)
437 				(void)printf("%ld", (long)ret);
438 			else
439 				(void)printf("%#lx", (long)ret);
440 		}
441 		break;
442 
443 	default:
444 		eprint(error);
445 		break;
446 	}
447 	(void)putchar('\n');
448 
449 }
450 
451 /*
452  * We print the original emulation's error numerically, but we
453  * translate it to netbsd to print it symbolically.
454  */
455 void
456 eprint(e)
457 	int e;
458 {
459 	int i = e;
460 
461 	if (current->errnomap) {
462 
463 		/* No remapping for ERESTART and EJUSTRETURN */
464 		/* Kludge for linux that has negative error numbers */
465 		if (current->errnomap[2] > 0 && e < 0)
466 			goto normal;
467 
468 		for (i = 0; i < current->nerrnomap; i++)
469 			if (e == current->errnomap[i])
470 				break;
471 
472 		if (i == current->nerrnomap) {
473 			printf("-1 unknown errno %d", e);
474 			return;
475 		}
476 	}
477 
478 normal:
479 	switch (i) {
480 	case ERESTART:
481 		(void)printf("RESTART");
482 		break;
483 
484 	case EJUSTRETURN:
485 		(void)printf("JUSTRETURN");
486 		break;
487 
488 	default:
489 		(void)printf("-1 errno %d", e);
490 		if (!plain)
491 			(void)printf(" %s", strerror(i));
492 	}
493 }
494 
495 void
496 ktrnamei(cp, len)
497 	char *cp;
498 	int len;
499 {
500 
501 	(void)printf("\"%.*s\"\n", len, cp);
502 }
503 
504 void
505 ktremul(name, len, bufsize)
506 	char *name;
507 	int len, bufsize;
508 {
509 	if (len >= bufsize)
510 		len = bufsize - 1;
511 
512 	name[len] = '\0';
513 	setemul(name, ktr_header.ktr_pid, 1);
514 	emul_changed = 1;
515 
516 	(void)printf("\"%s\"\n", name);
517 }
518 
519 void
520 ktrgenio(ktr, len)
521 	struct ktr_genio *ktr;
522 	int len;
523 {
524 	int datalen = len - sizeof (struct ktr_genio);
525 	char *dp = (char *)ktr + sizeof (struct ktr_genio);
526 	char *cp;
527 	int col = 0;
528 	int width;
529 	char visbuf[5];
530 	static int screenwidth = 0;
531 
532 	if (screenwidth == 0) {
533 		struct winsize ws;
534 
535 		if (!plain && ioctl(fileno(stderr), TIOCGWINSZ, &ws) != -1 &&
536 		    ws.ws_col > 8)
537 			screenwidth = ws.ws_col;
538 		else
539 			screenwidth = 80;
540 	}
541 	printf("fd %d %s %d bytes\n", ktr->ktr_fd,
542 		ktr->ktr_rw == UIO_READ ? "read" : "wrote", datalen);
543 	if (maxdata && datalen > maxdata)
544 		datalen = maxdata;
545 	(void)printf("       \"");
546 	col = 8;
547 	for (; datalen > 0; datalen--, dp++) {
548 		(void) vis(visbuf, *dp, VIS_CSTYLE, datalen>1?*(dp+1):0);
549 		cp = visbuf;
550 		/*
551 		 * Keep track of printables and
552 		 * space chars (like fold(1)).
553 		 */
554 		if (col == 0) {
555 			(void)putchar('\t');
556 			col = 8;
557 		}
558 		switch(*cp) {
559 		case '\n':
560 			col = 0;
561 			(void)putchar('\n');
562 			continue;
563 		case '\t':
564 			width = 8 - (col&07);
565 			break;
566 		default:
567 			width = strlen(cp);
568 		}
569 		if (col + width > (screenwidth-2)) {
570 			(void)printf("\\\n\t");
571 			col = 8;
572 		}
573 		col += width;
574 		do {
575 			(void)putchar(*cp++);
576 		} while (*cp);
577 	}
578 	if (col == 0)
579 		(void)printf("       ");
580 	(void)printf("\"\n");
581 }
582 
583 void
584 ktrpsig(psig)
585 	struct ktr_psig *psig;
586 {
587 	int signo, first;
588 
589 	(void)printf("SIG%s ", signame(psig->signo, 0));
590 	if (psig->action == SIG_DFL)
591 		(void)printf("SIG_DFL\n");
592 	else {
593 		(void)printf("caught handler=0x%lx mask=(",
594 		    (u_long)psig->action);
595 		first = 1;
596 		for (signo = 1; signo < NSIG; signo++) {
597 			if (sigismember(&psig->mask, signo)) {
598 				if (first)
599 					first = 0;
600 				else
601 					(void)printf(",");
602 				(void)printf("%d", signo);
603 			}
604 		}
605 		(void)printf(") code=0x%x\n", psig->code);
606 	}
607 }
608 
609 void
610 ktrcsw(cs)
611 	struct ktr_csw *cs;
612 {
613 
614 	(void)printf("%s %s\n", cs->out ? "stop" : "resume",
615 	    cs->user ? "user" : "kernel");
616 }
617 
618 void
619 ktruser(usr, len)
620 	struct ktr_user *usr;
621 	int len;
622 {
623 	int i;
624 	unsigned char *dta;
625 
626 	printf("\"%.*s: %d, ", KTR_USER_MAXIDLEN, usr->ktr_id, len);
627 	dta = (unsigned char *)usr;
628 	for(i=sizeof(struct ktr_user); i < len; i++)
629 		printf("%02x", (unsigned int) dta[i]);
630 	printf("\"\n");
631 }
632 
633 static const char *
634 signame(long sig, int xlat)
635 {
636 	static char buf[64];
637 	if (sig <= 0 || sig >= NSIG) {
638 		(void)snprintf(buf, sizeof(buf), "*unknown %ld*", sig);
639 		return buf;
640 	} else
641 		return sys_signame[(xlat && current->signalmap != NULL) ?
642 		    current->signalmap[sig] : sig];
643 }
644 
645 void
646 usage()
647 {
648 
649 	(void)fprintf(stderr,
650 "usage: kdump [-dnlRT] [-e emulation] [-f trfile] [-m maxdata] [-p pid]\n"
651 "             [-t [cnis]] [trfile]\n");
652 	exit(1);
653 }
654