xref: /openbsd/lib/libkvm/kvm.c (revision cecf84d4)
1 /*	$OpenBSD: kvm.c,v 1.55 2015/05/11 00:42:54 guenther Exp $ */
2 /*	$NetBSD: kvm.c,v 1.43 1996/05/05 04:31:59 gwr Exp $	*/
3 
4 /*-
5  * Copyright (c) 1989, 1992, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * This code is derived from software developed by the Computer Systems
9  * Engineering group at Lawrence Berkeley Laboratory under DARPA contract
10  * BG 91-66 and contributed to Berkeley.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  */
36 
37 #include <sys/param.h>	/* MAXCOMLEN MID_MACHINE */
38 #include <sys/proc.h>
39 #include <sys/ioctl.h>
40 #include <sys/stat.h>
41 #include <sys/sysctl.h>
42 
43 #include <sys/core.h>
44 #include <sys/exec.h>
45 #include <sys/kcore.h>
46 
47 #include <errno.h>
48 #include <ctype.h>
49 #include <db.h>
50 #include <fcntl.h>
51 #include <libgen.h>
52 #include <limits.h>
53 #include <nlist.h>
54 #include <paths.h>
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <string.h>
58 #include <unistd.h>
59 #include <kvm.h>
60 #include <stdarg.h>
61 
62 #include "kvm_private.h"
63 
64 extern int __fdnlist(int, struct nlist *);
65 
66 static int	kvm_dbopen(kvm_t *, const char *);
67 static int	kvm_opennamelist(kvm_t *, const char *);
68 static int	_kvm_get_header(kvm_t *);
69 static kvm_t	*_kvm_open(kvm_t *, const char *, const char *, const char *,
70 		     int, char *);
71 static int	clear_gap(kvm_t *, FILE *, int);
72 
73 char *
74 kvm_geterr(kvm_t *kd)
75 {
76 	return (kd->errbuf);
77 }
78 
79 /*
80  * Wrapper around pread.
81  */
82 ssize_t
83 _kvm_pread(kvm_t *kd, int fd, void *buf, size_t nbytes, off_t offset)
84 {
85 	ssize_t rval;
86 
87 	errno = 0;
88 	rval = pread(fd, buf, nbytes, offset);
89 	if (rval == -1 || errno != 0) {
90 		_kvm_syserr(kd, kd->program, "pread");
91 	}
92 	return (rval);
93 }
94 
95 /*
96  * Wrapper around pwrite.
97  */
98 ssize_t
99 _kvm_pwrite(kvm_t *kd, int fd, const void *buf, size_t nbytes, off_t offset)
100 {
101 	ssize_t rval;
102 
103 	errno = 0;
104 	rval = pwrite(fd, buf, nbytes, offset);
105 	if (rval == -1 || errno != 0) {
106 		_kvm_syserr(kd, kd->program, "pwrite");
107 	}
108 	return (rval);
109 }
110 
111 /*
112  * Report an error using printf style arguments.  "program" is kd->program
113  * on hard errors, and 0 on soft errors, so that under sun error emulation,
114  * only hard errors are printed out (otherwise, programs like gdb will
115  * generate tons of error messages when trying to access bogus pointers).
116  */
117 void
118 _kvm_err(kvm_t *kd, const char *program, const char *fmt, ...)
119 {
120 	va_list ap;
121 
122 	va_start(ap, fmt);
123 	if (program != NULL) {
124 		(void)fprintf(stderr, "%s: ", program);
125 		(void)vfprintf(stderr, fmt, ap);
126 		(void)fputc('\n', stderr);
127 	} else
128 		(void)vsnprintf(kd->errbuf,
129 		    sizeof(kd->errbuf), fmt, ap);
130 
131 	va_end(ap);
132 }
133 
134 void
135 _kvm_syserr(kvm_t *kd, const char *program, const char *fmt, ...)
136 {
137 	va_list ap;
138 	size_t n;
139 
140 	va_start(ap, fmt);
141 	if (program != NULL) {
142 		(void)fprintf(stderr, "%s: ", program);
143 		(void)vfprintf(stderr, fmt, ap);
144 		(void)fprintf(stderr, ": %s\n", strerror(errno));
145 	} else {
146 		char *cp = kd->errbuf;
147 
148 		(void)vsnprintf(cp, sizeof(kd->errbuf), fmt, ap);
149 		n = strlen(cp);
150 		(void)snprintf(&cp[n], sizeof(kd->errbuf) - n, ": %s",
151 		    strerror(errno));
152 	}
153 	va_end(ap);
154 }
155 
156 void *
157 _kvm_malloc(kvm_t *kd, size_t n)
158 {
159 	void *p;
160 
161 	if ((p = malloc(n)) == NULL)
162 		_kvm_err(kd, kd->program, "%s", strerror(errno));
163 	return (p);
164 }
165 
166 static kvm_t *
167 _kvm_open(kvm_t *kd, const char *uf, const char *mf, const char *sf,
168     int flag, char *errout)
169 {
170 	struct stat st;
171 
172 	kd->db = 0;
173 	kd->pmfd = -1;
174 	kd->vmfd = -1;
175 	kd->swfd = -1;
176 	kd->nlfd = -1;
177 	kd->alive = 0;
178 	kd->filebase = 0;
179 	kd->procbase = 0;
180 	kd->nbpg = getpagesize();
181 	kd->swapspc = 0;
182 	kd->argspc = 0;
183 	kd->argbuf = 0;
184 	kd->argv = 0;
185 	kd->vmst = NULL;
186 	kd->vm_page_buckets = 0;
187 	kd->kcore_hdr = 0;
188 	kd->cpu_dsize = 0;
189 	kd->cpu_data = 0;
190 	kd->dump_off = 0;
191 
192 	if (flag & KVM_NO_FILES) {
193 		kd->alive = 1;
194 		return (kd);
195 	}
196 
197 	if (uf && strlen(uf) >= PATH_MAX) {
198 		_kvm_err(kd, kd->program, "exec file name too long");
199 		goto failed;
200 	}
201 	if (flag != O_RDONLY && flag != O_WRONLY && flag != O_RDWR) {
202 		_kvm_err(kd, kd->program, "bad flags arg");
203 		goto failed;
204 	}
205 	flag |= O_CLOEXEC;
206 
207 	if (mf == 0)
208 		mf = _PATH_MEM;
209 
210 	if ((kd->pmfd = open(mf, flag)) < 0) {
211 		_kvm_syserr(kd, kd->program, "%s", mf);
212 		goto failed;
213 	}
214 	if (fstat(kd->pmfd, &st) < 0) {
215 		_kvm_syserr(kd, kd->program, "%s", mf);
216 		goto failed;
217 	}
218 	if (S_ISCHR(st.st_mode)) {
219 		/*
220 		 * If this is a character special device, then check that
221 		 * it's /dev/mem.  If so, open kmem too.  (Maybe we should
222 		 * make it work for either /dev/mem or /dev/kmem -- in either
223 		 * case you're working with a live kernel.)
224 		 */
225 		if (strcmp(mf, _PATH_MEM) != 0) {	/* XXX */
226 			_kvm_err(kd, kd->program,
227 				 "%s: not physical memory device", mf);
228 			goto failed;
229 		}
230 		if ((kd->vmfd = open(_PATH_KMEM, flag)) < 0) {
231 			_kvm_syserr(kd, kd->program, "%s", _PATH_KMEM);
232 			goto failed;
233 		}
234 		kd->alive = 1;
235 		if (sf != NULL && (kd->swfd = open(sf, flag)) < 0) {
236 			_kvm_syserr(kd, kd->program, "%s", sf);
237 			goto failed;
238 		}
239 		/*
240 		 * Open kvm nlist database.  We only try to use
241 		 * the pre-built database if the namelist file name
242 		 * pointer is NULL.  If the database cannot or should
243 		 * not be opened, open the namelist argument so we
244 		 * revert to slow nlist() calls.
245 		 * If no file is specified, try opening _PATH_KSYMS and
246 		 * fall back to _PATH_UNIX.
247 		 */
248 		if (kvm_dbopen(kd, uf ? uf : _PATH_UNIX) == -1 &&
249 		    kvm_opennamelist(kd, uf))
250 			goto failed;
251 	} else {
252 		/*
253 		 * This is a crash dump.
254 		 * Initialize the virtual address translation machinery,
255 		 * but first setup the namelist fd.
256 		 * If no file is specified, try opening _PATH_KSYMS and
257 		 * fall back to _PATH_UNIX.
258 		 */
259 		if (kvm_opennamelist(kd, uf))
260 			goto failed;
261 
262 		/*
263 		 * If there is no valid core header, fail silently here.
264 		 * The address translations however will fail without
265 		 * header. Things can be made to run by calling
266 		 * kvm_dump_mkheader() before doing any translation.
267 		 */
268 		if (_kvm_get_header(kd) == 0) {
269 			if (_kvm_initvtop(kd) < 0)
270 				goto failed;
271 		}
272 	}
273 	return (kd);
274 failed:
275 	/*
276 	 * Copy out the error if doing sane error semantics.
277 	 */
278 	if (errout != 0)
279 		(void)strlcpy(errout, kd->errbuf, _POSIX2_LINE_MAX);
280 	(void)kvm_close(kd);
281 	return (0);
282 }
283 
284 static int
285 kvm_opennamelist(kvm_t *kd, const char *uf)
286 {
287 	int fd;
288 
289 	if (uf != NULL)
290 		fd = open(uf, O_RDONLY | O_CLOEXEC);
291 	else {
292 		fd = open(_PATH_KSYMS, O_RDONLY | O_CLOEXEC);
293 		uf = _PATH_UNIX;
294 		if (fd == -1)
295 			fd = open(uf, O_RDONLY | O_CLOEXEC);
296 	}
297 	if (fd == -1) {
298 		_kvm_syserr(kd, kd->program, "%s", uf);
299 		return (-1);
300 	}
301 
302 	kd->nlfd = fd;
303 	return (0);
304 }
305 
306 /*
307  * The kernel dump file (from savecore) contains:
308  *    kcore_hdr_t kcore_hdr;
309  *    kcore_seg_t cpu_hdr;
310  *    (opaque)    cpu_data; (size is cpu_hdr.c_size)
311  *    kcore_seg_t mem_hdr;
312  *    (memory)    mem_data; (size is mem_hdr.c_size)
313  *
314  * Note: khdr is padded to khdr.c_hdrsize;
315  * cpu_hdr and mem_hdr are padded to khdr.c_seghdrsize
316  */
317 static int
318 _kvm_get_header(kvm_t *kd)
319 {
320 	kcore_hdr_t	kcore_hdr;
321 	kcore_seg_t	cpu_hdr;
322 	kcore_seg_t	mem_hdr;
323 	size_t		offset;
324 	ssize_t		sz;
325 
326 	/*
327 	 * Read the kcore_hdr_t
328 	 */
329 	sz = _kvm_pread(kd, kd->pmfd, &kcore_hdr, sizeof(kcore_hdr), (off_t)0);
330 	if (sz != sizeof(kcore_hdr)) {
331 		return (-1);
332 	}
333 
334 	/*
335 	 * Currently, we only support dump-files made by the current
336 	 * architecture...
337 	 */
338 	if ((CORE_GETMAGIC(kcore_hdr) != KCORE_MAGIC) ||
339 	    (CORE_GETMID(kcore_hdr) != MID_MACHINE))
340 		return (-1);
341 
342 	/*
343 	 * Currently, we only support exactly 2 segments: cpu-segment
344 	 * and data-segment in exactly that order.
345 	 */
346 	if (kcore_hdr.c_nseg != 2)
347 		return (-1);
348 
349 	/*
350 	 * Save away the kcore_hdr.  All errors after this
351 	 * should do a to "goto fail" to deallocate things.
352 	 */
353 	kd->kcore_hdr = _kvm_malloc(kd, sizeof(kcore_hdr));
354 	if (kd->kcore_hdr == NULL)
355 		goto fail;
356 	memcpy(kd->kcore_hdr, &kcore_hdr, sizeof(kcore_hdr));
357 	offset = kcore_hdr.c_hdrsize;
358 
359 	/*
360 	 * Read the CPU segment header
361 	 */
362 	sz = _kvm_pread(kd, kd->pmfd, &cpu_hdr, sizeof(cpu_hdr), (off_t)offset);
363 	if (sz != sizeof(cpu_hdr)) {
364 		goto fail;
365 	}
366 
367 	if ((CORE_GETMAGIC(cpu_hdr) != KCORESEG_MAGIC) ||
368 	    (CORE_GETFLAG(cpu_hdr) != CORE_CPU))
369 		goto fail;
370 	offset += kcore_hdr.c_seghdrsize;
371 
372 	/*
373 	 * Read the CPU segment DATA.
374 	 */
375 	kd->cpu_dsize = cpu_hdr.c_size;
376 	kd->cpu_data = _kvm_malloc(kd, (size_t)cpu_hdr.c_size);
377 	if (kd->cpu_data == NULL)
378 		goto fail;
379 
380 	sz = _kvm_pread(kd, kd->pmfd, kd->cpu_data, (size_t)cpu_hdr.c_size,
381 	    (off_t)offset);
382 	if (sz != (size_t)cpu_hdr.c_size) {
383 		goto fail;
384 	}
385 
386 	offset += cpu_hdr.c_size;
387 
388 	/*
389 	 * Read the next segment header: data segment
390 	 */
391 	sz = _kvm_pread(kd, kd->pmfd, &mem_hdr, sizeof(mem_hdr), (off_t)offset);
392 	if (sz != sizeof(mem_hdr)) {
393 		goto fail;
394 	}
395 
396 	offset += kcore_hdr.c_seghdrsize;
397 
398 	if ((CORE_GETMAGIC(mem_hdr) != KCORESEG_MAGIC) ||
399 	    (CORE_GETFLAG(mem_hdr) != CORE_DATA))
400 		goto fail;
401 
402 	kd->dump_off = offset;
403 	return (0);
404 
405 fail:
406 	if (kd->kcore_hdr != NULL) {
407 		free(kd->kcore_hdr);
408 		kd->kcore_hdr = NULL;
409 	}
410 	if (kd->cpu_data != NULL) {
411 		free(kd->cpu_data);
412 		kd->cpu_data = NULL;
413 		kd->cpu_dsize = 0;
414 	}
415 
416 	return (-1);
417 }
418 
419 /*
420  * The format while on the dump device is: (new format)
421  *    kcore_seg_t cpu_hdr;
422  *    (opaque)    cpu_data; (size is cpu_hdr.c_size)
423  *    kcore_seg_t mem_hdr;
424  *    (memory)    mem_data; (size is mem_hdr.c_size)
425  */
426 int
427 kvm_dump_mkheader(kvm_t *kd, off_t dump_off)
428 {
429 	kcore_seg_t	cpu_hdr;
430 	int	hdr_size;
431 	ssize_t sz;
432 
433 	if (kd->kcore_hdr != NULL) {
434 	    _kvm_err(kd, kd->program, "already has a dump header");
435 	    return (-1);
436 	}
437 	if (ISALIVE(kd)) {
438 		_kvm_err(kd, kd->program, "don't use on live kernel");
439 		return (-1);
440 	}
441 
442 	/*
443 	 * Validate new format crash dump
444 	 */
445 	sz = _kvm_pread(kd, kd->pmfd, &cpu_hdr, sizeof(cpu_hdr), (off_t)dump_off);
446 	if (sz != sizeof(cpu_hdr)) {
447 		return (-1);
448 	}
449 	if ((CORE_GETMAGIC(cpu_hdr) != KCORE_MAGIC)
450 		|| (CORE_GETMID(cpu_hdr) != MID_MACHINE)) {
451 		_kvm_err(kd, 0, "invalid magic in cpu_hdr");
452 		return (-1);
453 	}
454 	hdr_size = ALIGN(sizeof(cpu_hdr));
455 
456 	/*
457 	 * Read the CPU segment.
458 	 */
459 	kd->cpu_dsize = cpu_hdr.c_size;
460 	kd->cpu_data = _kvm_malloc(kd, kd->cpu_dsize);
461 	if (kd->cpu_data == NULL)
462 		goto fail;
463 
464 	sz = _kvm_pread(kd, kd->pmfd, kd->cpu_data, (size_t)cpu_hdr.c_size,
465 	    (off_t)dump_off+hdr_size);
466 	if (sz != (ssize_t)cpu_hdr.c_size) {
467 		_kvm_err(kd, 0, "invalid size in cpu_hdr");
468 		goto fail;
469 	}
470 	hdr_size += kd->cpu_dsize;
471 
472 	/*
473 	 * Leave phys mem pointer at beginning of memory data
474 	 */
475 	kd->dump_off = dump_off + hdr_size;
476 	errno = 0;
477 	if (lseek(kd->pmfd, kd->dump_off, SEEK_SET) != kd->dump_off && errno != 0) {
478 		_kvm_err(kd, 0, "invalid dump offset - lseek");
479 		goto fail;
480 	}
481 
482 	/*
483 	 * Create a kcore_hdr.
484 	 */
485 	kd->kcore_hdr = _kvm_malloc(kd, sizeof(kcore_hdr_t));
486 	if (kd->kcore_hdr == NULL)
487 		goto fail;
488 
489 	kd->kcore_hdr->c_hdrsize    = ALIGN(sizeof(kcore_hdr_t));
490 	kd->kcore_hdr->c_seghdrsize = ALIGN(sizeof(kcore_seg_t));
491 	kd->kcore_hdr->c_nseg       = 2;
492 	CORE_SETMAGIC(*(kd->kcore_hdr), KCORE_MAGIC, MID_MACHINE,0);
493 
494 	/*
495 	 * Now that we have a valid header, enable translations.
496 	 */
497 	if (_kvm_initvtop(kd) == 0)
498 		/* Success */
499 		return (hdr_size);
500 
501 fail:
502 	if (kd->kcore_hdr != NULL) {
503 		free(kd->kcore_hdr);
504 		kd->kcore_hdr = NULL;
505 	}
506 	if (kd->cpu_data != NULL) {
507 		free(kd->cpu_data);
508 		kd->cpu_data = NULL;
509 		kd->cpu_dsize = 0;
510 	}
511 	return (-1);
512 }
513 
514 static int
515 clear_gap(kvm_t *kd, FILE *fp, int size)
516 {
517 	if (size <= 0) /* XXX - < 0 should never happen */
518 		return (0);
519 	while (size-- > 0) {
520 		if (fputc(0, fp) == EOF) {
521 			_kvm_syserr(kd, kd->program, "clear_gap");
522 			return (-1);
523 		}
524 	}
525 	return (0);
526 }
527 
528 /*
529  * Write the dump header info to 'fp'. Note that we can't use fseek(3) here
530  * because 'fp' might be a file pointer obtained by zopen().
531  */
532 int
533 kvm_dump_wrtheader(kvm_t *kd, FILE *fp, int dumpsize)
534 {
535 	kcore_seg_t	seghdr;
536 	long		offset;
537 	int		gap;
538 
539 	if (kd->kcore_hdr == NULL || kd->cpu_data == NULL) {
540 		_kvm_err(kd, kd->program, "no valid dump header(s)");
541 		return (-1);
542 	}
543 
544 	/*
545 	 * Write the generic header
546 	 */
547 	offset = 0;
548 	if (fwrite(kd->kcore_hdr, sizeof(kcore_hdr_t), 1, fp) < 1) {
549 		_kvm_syserr(kd, kd->program, "kvm_dump_wrtheader");
550 		return (-1);
551 	}
552 	offset += kd->kcore_hdr->c_hdrsize;
553 	gap     = kd->kcore_hdr->c_hdrsize - sizeof(kcore_hdr_t);
554 	if (clear_gap(kd, fp, gap) == -1)
555 		return (-1);
556 
557 	/*
558 	 * Write the cpu header
559 	 */
560 	CORE_SETMAGIC(seghdr, KCORESEG_MAGIC, 0, CORE_CPU);
561 	seghdr.c_size = (u_long)ALIGN(kd->cpu_dsize);
562 	if (fwrite(&seghdr, sizeof(seghdr), 1, fp) < 1) {
563 		_kvm_syserr(kd, kd->program, "kvm_dump_wrtheader");
564 		return (-1);
565 	}
566 	offset += kd->kcore_hdr->c_seghdrsize;
567 	gap     = kd->kcore_hdr->c_seghdrsize - sizeof(seghdr);
568 	if (clear_gap(kd, fp, gap) == -1)
569 		return (-1);
570 
571 	if (fwrite(kd->cpu_data, kd->cpu_dsize, 1, fp) < 1) {
572 		_kvm_syserr(kd, kd->program, "kvm_dump_wrtheader");
573 		return (-1);
574 	}
575 	offset += seghdr.c_size;
576 	gap     = seghdr.c_size - kd->cpu_dsize;
577 	if (clear_gap(kd, fp, gap) == -1)
578 		return (-1);
579 
580 	/*
581 	 * Write the actual dump data segment header
582 	 */
583 	CORE_SETMAGIC(seghdr, KCORESEG_MAGIC, 0, CORE_DATA);
584 	seghdr.c_size = dumpsize;
585 	if (fwrite(&seghdr, sizeof(seghdr), 1, fp) < 1) {
586 		_kvm_syserr(kd, kd->program, "kvm_dump_wrtheader");
587 		return (-1);
588 	}
589 	offset += kd->kcore_hdr->c_seghdrsize;
590 	gap     = kd->kcore_hdr->c_seghdrsize - sizeof(seghdr);
591 	if (clear_gap(kd, fp, gap) == -1)
592 		return (-1);
593 
594 	return (offset);
595 }
596 
597 kvm_t *
598 kvm_openfiles(const char *uf, const char *mf, const char *sf,
599     int flag, char *errout)
600 {
601 	kvm_t *kd;
602 
603 	if ((kd = malloc(sizeof(*kd))) == NULL) {
604 		(void)strlcpy(errout, strerror(errno), _POSIX2_LINE_MAX);
605 		return (0);
606 	}
607 	kd->program = 0;
608 	return (_kvm_open(kd, uf, mf, sf, flag, errout));
609 }
610 
611 kvm_t *
612 kvm_open(const char *uf, const char *mf, const char *sf, int flag,
613     const char *program)
614 {
615 	kvm_t *kd;
616 
617 	if ((kd = malloc(sizeof(*kd))) == NULL && program != NULL) {
618 		(void)fprintf(stderr, "%s: %s\n", program, strerror(errno));
619 		return (0);
620 	}
621 	kd->program = program;
622 	return (_kvm_open(kd, uf, mf, sf, flag, NULL));
623 }
624 
625 int
626 kvm_close(kvm_t *kd)
627 {
628 	int error = 0;
629 
630 	if (kd->pmfd >= 0)
631 		error |= close(kd->pmfd);
632 	if (kd->vmfd >= 0)
633 		error |= close(kd->vmfd);
634 	kd->alive = 0;
635 	if (kd->nlfd >= 0)
636 		error |= close(kd->nlfd);
637 	if (kd->swfd >= 0)
638 		error |= close(kd->swfd);
639 	if (kd->db != 0)
640 		error |= (kd->db->close)(kd->db);
641 	if (kd->vmst)
642 		_kvm_freevtop(kd);
643 	kd->cpu_dsize = 0;
644 	if (kd->cpu_data != NULL)
645 		free((void *)kd->cpu_data);
646 	if (kd->kcore_hdr != NULL)
647 		free((void *)kd->kcore_hdr);
648 	if (kd->filebase != 0)
649 		free((void *)kd->filebase);
650 	if (kd->procbase != 0)
651 		free((void *)kd->procbase);
652 	if (kd->swapspc != 0)
653 		free((void *)kd->swapspc);
654 	if (kd->argspc != 0)
655 		free((void *)kd->argspc);
656 	if (kd->argbuf != 0)
657 		free((void *)kd->argbuf);
658 	if (kd->argv != 0)
659 		free((void *)kd->argv);
660 	free((void *)kd);
661 
662 	return (error);
663 }
664 
665 /*
666  * Set up state necessary to do queries on the kernel namelist
667  * data base.  If the data base is out-of-data/incompatible with
668  * given executable, set up things so we revert to standard nlist call.
669  * Only called for live kernels.  Return 0 on success, -1 on failure.
670  */
671 static int
672 kvm_dbopen(kvm_t *kd, const char *uf)
673 {
674 	char dbversion[_POSIX2_LINE_MAX], kversion[_POSIX2_LINE_MAX];
675 	char dbname[PATH_MAX];
676 	struct nlist nitem;
677 	size_t dbversionlen;
678 	DBT rec;
679 
680 	uf = basename(uf);
681 
682 	(void)snprintf(dbname, sizeof(dbname), "%skvm_%s.db", _PATH_VARDB, uf);
683 	kd->db = dbopen(dbname, O_RDONLY, 0, DB_HASH, NULL);
684 	if (kd->db == NULL) {
685 		switch (errno) {
686 		case ENOENT:
687 			/* No kvm_bsd.db, fall back to /bsd silently */
688 			break;
689 		case EFTYPE:
690 			_kvm_err(kd, kd->program,
691 			    "file %s is incorrectly formatted", dbname);
692 			break;
693 		case EINVAL:
694 			_kvm_err(kd, kd->program,
695 			    "invalid argument to dbopen()");
696 			break;
697 		default:
698 			_kvm_err(kd, kd->program, "unknown dbopen() error");
699 			break;
700 		}
701 		return (-1);
702 	}
703 
704 	/*
705 	 * read version out of database
706 	 */
707 	rec.data = VRS_KEY;
708 	rec.size = sizeof(VRS_KEY) - 1;
709 	if ((kd->db->get)(kd->db, (DBT *)&rec, (DBT *)&rec, 0))
710 		goto close;
711 	if (rec.data == 0 || rec.size > sizeof(dbversion))
712 		goto close;
713 
714 	bcopy(rec.data, dbversion, rec.size);
715 	dbversionlen = rec.size;
716 
717 	/*
718 	 * Read version string from kernel memory.
719 	 * Since we are dealing with a live kernel, we can call kvm_read()
720 	 * at this point.
721 	 */
722 	rec.data = VRS_SYM;
723 	rec.size = sizeof(VRS_SYM) - 1;
724 	if ((kd->db->get)(kd->db, (DBT *)&rec, (DBT *)&rec, 0))
725 		goto close;
726 	if (rec.data == 0 || rec.size != sizeof(struct nlist))
727 		goto close;
728 	bcopy(rec.data, &nitem, sizeof(nitem));
729 	if (kvm_read(kd, (u_long)nitem.n_value, kversion, dbversionlen) !=
730 	    dbversionlen)
731 		goto close;
732 	/*
733 	 * If they match, we win - otherwise clear out kd->db so
734 	 * we revert to slow nlist().
735 	 */
736 	if (bcmp(dbversion, kversion, dbversionlen) == 0)
737 		return (0);
738 close:
739 	(void)(kd->db->close)(kd->db);
740 	kd->db = 0;
741 
742 	return (-1);
743 }
744 
745 int
746 kvm_nlist(kvm_t *kd, struct nlist *nl)
747 {
748 	struct nlist *p;
749 	int nvalid, rv;
750 
751 	/*
752 	 * If we can't use the data base, revert to the
753 	 * slow library call.
754 	 */
755 	if (kd->db == 0) {
756 		rv = __fdnlist(kd->nlfd, nl);
757 		if (rv == -1)
758 			_kvm_err(kd, 0, "bad namelist");
759 		return (rv);
760 	}
761 
762 	/*
763 	 * We can use the kvm data base.  Go through each nlist entry
764 	 * and look it up with a db query.
765 	 */
766 	nvalid = 0;
767 	for (p = nl; p->n_name && p->n_name[0]; ++p) {
768 		size_t len;
769 		DBT rec;
770 
771 		if ((len = strlen(p->n_name)) > 4096) {
772 			/* sanity */
773 			_kvm_err(kd, kd->program, "symbol too large");
774 			return (-1);
775 		}
776 		rec.data = p->n_name;
777 		rec.size = len;
778 
779 		/*
780 		 * Make sure that n_value = 0 when the symbol isn't found
781 		 */
782 		p->n_value = 0;
783 
784 		if ((kd->db->get)(kd->db, (DBT *)&rec, (DBT *)&rec, 0))
785 			continue;
786 		if (rec.data == 0 || rec.size != sizeof(struct nlist))
787 			continue;
788 		++nvalid;
789 		/*
790 		 * Avoid alignment issues.
791 		 */
792 		bcopy(&((struct nlist *)rec.data)->n_type,
793 		    &p->n_type, sizeof(p->n_type));
794 		bcopy(&((struct nlist *)rec.data)->n_value,
795 		    &p->n_value, sizeof(p->n_value));
796 	}
797 	/*
798 	 * Return the number of entries that weren't found.
799 	 */
800 	return ((p - nl) - nvalid);
801 }
802 
803 int
804 kvm_dump_inval(kvm_t *kd)
805 {
806 	struct nlist	nl[2];
807 	u_long		x;
808 	paddr_t		pa;
809 
810 	if (ISALIVE(kd)) {
811 		_kvm_err(kd, kd->program, "clearing dump on live kernel");
812 		return (-1);
813 	}
814 	nl[0].n_name = "_dumpmag";
815 	nl[1].n_name = NULL;
816 
817 	if (kvm_nlist(kd, nl) == -1) {
818 		_kvm_err(kd, 0, "bad namelist");
819 		return (-1);
820 	}
821 
822 	if (nl[0].n_value == 0) {
823 		_kvm_err(kd, nl[0].n_name, "not in name list");
824 		return (-1);
825 	}
826 
827 	if (_kvm_kvatop(kd, (u_long)nl[0].n_value, &pa) == 0)
828 		return (-1);
829 
830 	x = 0;
831 	if (_kvm_pwrite(kd, kd->pmfd, &x, sizeof(x),
832 	    (off_t)_kvm_pa2off(kd, pa)) != sizeof(x)) {
833 		_kvm_err(kd, 0, "cannot invalidate dump");
834 		return (-1);
835 	}
836 	return (0);
837 }
838 
839 ssize_t
840 kvm_read(kvm_t *kd, u_long kva, void *buf, size_t len)
841 {
842 	ssize_t cc;
843 	void *cp;
844 
845 	if (ISALIVE(kd)) {
846 		/*
847 		 * We're using /dev/kmem.  Just read straight from the
848 		 * device and let the active kernel do the address translation.
849 		 */
850 		cc = _kvm_pread(kd, kd->vmfd, buf, len, (off_t)kva);
851 		if (cc == -1) {
852 			_kvm_err(kd, 0, "invalid address (%lx)", kva);
853 			return (-1);
854 		} else if (cc < len)
855 			_kvm_err(kd, kd->program, "short read");
856 		return (cc);
857 	} else {
858 		if ((kd->kcore_hdr == NULL) || (kd->cpu_data == NULL)) {
859 			_kvm_err(kd, kd->program, "no valid dump header");
860 			return (-1);
861 		}
862 		cp = buf;
863 		while (len > 0) {
864 			paddr_t	pa;
865 
866 			/* In case of error, _kvm_kvatop sets the err string */
867 			cc = _kvm_kvatop(kd, kva, &pa);
868 			if (cc == 0)
869 				return (-1);
870 			if (cc > len)
871 				cc = len;
872 			cc = _kvm_pread(kd, kd->pmfd, cp, (size_t)cc,
873 			    (off_t)_kvm_pa2off(kd, pa));
874 			if (cc == -1) {
875 				_kvm_syserr(kd, 0, _PATH_MEM);
876 				break;
877 			}
878 			/*
879 			 * If kvm_kvatop returns a bogus value or our core
880 			 * file is truncated, we might wind up seeking beyond
881 			 * the end of the core file in which case the read will
882 			 * return 0 (EOF).
883 			 */
884 			if (cc == 0)
885 				break;
886 			cp = (char *)cp + cc;
887 			kva += cc;
888 			len -= cc;
889 		}
890 		return ((char *)cp - (char *)buf);
891 	}
892 	/* NOTREACHED */
893 }
894 
895 ssize_t
896 kvm_write(kvm_t *kd, u_long kva, const void *buf, size_t len)
897 {
898 	int cc;
899 
900 	if (ISALIVE(kd)) {
901 		/*
902 		 * Just like kvm_read, only we write.
903 		 */
904 		cc = _kvm_pwrite(kd, kd->vmfd, buf, len, (off_t)kva);
905 		if (cc == -1) {
906 			_kvm_err(kd, 0, "invalid address (%lx)", kva);
907 			return (-1);
908 		} else if (cc < len)
909 			_kvm_err(kd, kd->program, "short write");
910 		return (cc);
911 	} else {
912 		_kvm_err(kd, kd->program,
913 		    "kvm_write not implemented for dead kernels");
914 		return (-1);
915 	}
916 	/* NOTREACHED */
917 }
918