xref: /openbsd-src/lib/libkvm/kvm.c (revision b33a8d55775a3013157d6b0e3602c1fe178b48a6)
1 /*	$OpenBSD: kvm.c,v 1.58 2015/09/08 15:40:32 dlg 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 void *
167 _kvm_realloc(kvm_t *kd, void *p, size_t n)
168 {
169 	if ((p = realloc(p, n)) == NULL)
170 		_kvm_err(kd, kd->program, "%s", strerror(errno));
171 	return (p);
172 }
173 
174 static kvm_t *
175 _kvm_open(kvm_t *kd, const char *uf, const char *mf, const char *sf,
176     int flag, char *errout)
177 {
178 	struct stat st;
179 
180 	kd->db = 0;
181 	kd->pmfd = -1;
182 	kd->vmfd = -1;
183 	kd->swfd = -1;
184 	kd->nlfd = -1;
185 	kd->alive = 0;
186 	kd->filebase = NULL;
187 	kd->procbase = NULL;
188 	kd->nbpg = getpagesize();
189 	kd->swapspc = 0;
190 	kd->argspc = 0;
191 	kd->argbuf = 0;
192 	kd->argv = 0;
193 	kd->vmst = NULL;
194 	kd->vm_page_buckets = 0;
195 	kd->kcore_hdr = 0;
196 	kd->cpu_dsize = 0;
197 	kd->cpu_data = 0;
198 	kd->dump_off = 0;
199 
200 	if (flag & KVM_NO_FILES) {
201 		kd->alive = 1;
202 		return (kd);
203 	}
204 
205 	if (uf && strlen(uf) >= PATH_MAX) {
206 		_kvm_err(kd, kd->program, "exec file name too long");
207 		goto failed;
208 	}
209 	if (flag != O_RDONLY && flag != O_WRONLY && flag != O_RDWR) {
210 		_kvm_err(kd, kd->program, "bad flags arg");
211 		goto failed;
212 	}
213 	flag |= O_CLOEXEC;
214 
215 	if (mf == 0)
216 		mf = _PATH_MEM;
217 
218 	if ((kd->pmfd = open(mf, flag)) < 0) {
219 		_kvm_syserr(kd, kd->program, "%s", mf);
220 		goto failed;
221 	}
222 	if (fstat(kd->pmfd, &st) < 0) {
223 		_kvm_syserr(kd, kd->program, "%s", mf);
224 		goto failed;
225 	}
226 	if (S_ISCHR(st.st_mode)) {
227 		/*
228 		 * If this is a character special device, then check that
229 		 * it's /dev/mem.  If so, open kmem too.  (Maybe we should
230 		 * make it work for either /dev/mem or /dev/kmem -- in either
231 		 * case you're working with a live kernel.)
232 		 */
233 		if (strcmp(mf, _PATH_MEM) != 0) {	/* XXX */
234 			_kvm_err(kd, kd->program,
235 				 "%s: not physical memory device", mf);
236 			goto failed;
237 		}
238 		if ((kd->vmfd = open(_PATH_KMEM, flag)) < 0) {
239 			_kvm_syserr(kd, kd->program, "%s", _PATH_KMEM);
240 			goto failed;
241 		}
242 		kd->alive = 1;
243 		if (sf != NULL && (kd->swfd = open(sf, flag)) < 0) {
244 			_kvm_syserr(kd, kd->program, "%s", sf);
245 			goto failed;
246 		}
247 		/*
248 		 * Open kvm nlist database.  We only try to use
249 		 * the pre-built database if the namelist file name
250 		 * pointer is NULL.  If the database cannot or should
251 		 * not be opened, open the namelist argument so we
252 		 * revert to slow nlist() calls.
253 		 * If no file is specified, try opening _PATH_KSYMS and
254 		 * fall back to _PATH_UNIX.
255 		 */
256 		if (kvm_dbopen(kd, uf ? uf : _PATH_UNIX) == -1 &&
257 		    kvm_opennamelist(kd, uf))
258 			goto failed;
259 	} else {
260 		/*
261 		 * This is a crash dump.
262 		 * Initialize the virtual address translation machinery,
263 		 * but first setup the namelist fd.
264 		 * If no file is specified, try opening _PATH_KSYMS and
265 		 * fall back to _PATH_UNIX.
266 		 */
267 		if (kvm_opennamelist(kd, uf))
268 			goto failed;
269 
270 		/*
271 		 * If there is no valid core header, fail silently here.
272 		 * The address translations however will fail without
273 		 * header. Things can be made to run by calling
274 		 * kvm_dump_mkheader() before doing any translation.
275 		 */
276 		if (_kvm_get_header(kd) == 0) {
277 			if (_kvm_initvtop(kd) < 0)
278 				goto failed;
279 		}
280 	}
281 	return (kd);
282 failed:
283 	/*
284 	 * Copy out the error if doing sane error semantics.
285 	 */
286 	if (errout != 0)
287 		(void)strlcpy(errout, kd->errbuf, _POSIX2_LINE_MAX);
288 	(void)kvm_close(kd);
289 	return (0);
290 }
291 
292 static int
293 kvm_opennamelist(kvm_t *kd, const char *uf)
294 {
295 	int fd;
296 
297 	if (uf != NULL)
298 		fd = open(uf, O_RDONLY | O_CLOEXEC);
299 	else {
300 		fd = open(_PATH_KSYMS, O_RDONLY | O_CLOEXEC);
301 		uf = _PATH_UNIX;
302 		if (fd == -1)
303 			fd = open(uf, O_RDONLY | O_CLOEXEC);
304 	}
305 	if (fd == -1) {
306 		_kvm_syserr(kd, kd->program, "%s", uf);
307 		return (-1);
308 	}
309 
310 	kd->nlfd = fd;
311 	return (0);
312 }
313 
314 /*
315  * The kernel dump file (from savecore) contains:
316  *    kcore_hdr_t kcore_hdr;
317  *    kcore_seg_t cpu_hdr;
318  *    (opaque)    cpu_data; (size is cpu_hdr.c_size)
319  *    kcore_seg_t mem_hdr;
320  *    (memory)    mem_data; (size is mem_hdr.c_size)
321  *
322  * Note: khdr is padded to khdr.c_hdrsize;
323  * cpu_hdr and mem_hdr are padded to khdr.c_seghdrsize
324  */
325 static int
326 _kvm_get_header(kvm_t *kd)
327 {
328 	kcore_hdr_t	kcore_hdr;
329 	kcore_seg_t	cpu_hdr;
330 	kcore_seg_t	mem_hdr;
331 	size_t		offset;
332 	ssize_t		sz;
333 
334 	/*
335 	 * Read the kcore_hdr_t
336 	 */
337 	sz = _kvm_pread(kd, kd->pmfd, &kcore_hdr, sizeof(kcore_hdr), (off_t)0);
338 	if (sz != sizeof(kcore_hdr)) {
339 		return (-1);
340 	}
341 
342 	/*
343 	 * Currently, we only support dump-files made by the current
344 	 * architecture...
345 	 */
346 	if ((CORE_GETMAGIC(kcore_hdr) != KCORE_MAGIC) ||
347 	    (CORE_GETMID(kcore_hdr) != MID_MACHINE))
348 		return (-1);
349 
350 	/*
351 	 * Currently, we only support exactly 2 segments: cpu-segment
352 	 * and data-segment in exactly that order.
353 	 */
354 	if (kcore_hdr.c_nseg != 2)
355 		return (-1);
356 
357 	/*
358 	 * Save away the kcore_hdr.  All errors after this
359 	 * should do a to "goto fail" to deallocate things.
360 	 */
361 	kd->kcore_hdr = _kvm_malloc(kd, sizeof(kcore_hdr));
362 	if (kd->kcore_hdr == NULL)
363 		goto fail;
364 	memcpy(kd->kcore_hdr, &kcore_hdr, sizeof(kcore_hdr));
365 	offset = kcore_hdr.c_hdrsize;
366 
367 	/*
368 	 * Read the CPU segment header
369 	 */
370 	sz = _kvm_pread(kd, kd->pmfd, &cpu_hdr, sizeof(cpu_hdr), (off_t)offset);
371 	if (sz != sizeof(cpu_hdr)) {
372 		goto fail;
373 	}
374 
375 	if ((CORE_GETMAGIC(cpu_hdr) != KCORESEG_MAGIC) ||
376 	    (CORE_GETFLAG(cpu_hdr) != CORE_CPU))
377 		goto fail;
378 	offset += kcore_hdr.c_seghdrsize;
379 
380 	/*
381 	 * Read the CPU segment DATA.
382 	 */
383 	kd->cpu_dsize = cpu_hdr.c_size;
384 	kd->cpu_data = _kvm_malloc(kd, (size_t)cpu_hdr.c_size);
385 	if (kd->cpu_data == NULL)
386 		goto fail;
387 
388 	sz = _kvm_pread(kd, kd->pmfd, kd->cpu_data, (size_t)cpu_hdr.c_size,
389 	    (off_t)offset);
390 	if (sz != (size_t)cpu_hdr.c_size) {
391 		goto fail;
392 	}
393 
394 	offset += cpu_hdr.c_size;
395 
396 	/*
397 	 * Read the next segment header: data segment
398 	 */
399 	sz = _kvm_pread(kd, kd->pmfd, &mem_hdr, sizeof(mem_hdr), (off_t)offset);
400 	if (sz != sizeof(mem_hdr)) {
401 		goto fail;
402 	}
403 
404 	offset += kcore_hdr.c_seghdrsize;
405 
406 	if ((CORE_GETMAGIC(mem_hdr) != KCORESEG_MAGIC) ||
407 	    (CORE_GETFLAG(mem_hdr) != CORE_DATA))
408 		goto fail;
409 
410 	kd->dump_off = offset;
411 	return (0);
412 
413 fail:
414 	if (kd->kcore_hdr != NULL) {
415 		free(kd->kcore_hdr);
416 		kd->kcore_hdr = NULL;
417 	}
418 	if (kd->cpu_data != NULL) {
419 		free(kd->cpu_data);
420 		kd->cpu_data = NULL;
421 		kd->cpu_dsize = 0;
422 	}
423 
424 	return (-1);
425 }
426 
427 /*
428  * The format while on the dump device is: (new format)
429  *    kcore_seg_t cpu_hdr;
430  *    (opaque)    cpu_data; (size is cpu_hdr.c_size)
431  *    kcore_seg_t mem_hdr;
432  *    (memory)    mem_data; (size is mem_hdr.c_size)
433  */
434 int
435 kvm_dump_mkheader(kvm_t *kd, off_t dump_off)
436 {
437 	kcore_seg_t	cpu_hdr;
438 	int	hdr_size;
439 	ssize_t sz;
440 
441 	if (kd->kcore_hdr != NULL) {
442 	    _kvm_err(kd, kd->program, "already has a dump header");
443 	    return (-1);
444 	}
445 	if (ISALIVE(kd)) {
446 		_kvm_err(kd, kd->program, "don't use on live kernel");
447 		return (-1);
448 	}
449 
450 	/*
451 	 * Validate new format crash dump
452 	 */
453 	sz = _kvm_pread(kd, kd->pmfd, &cpu_hdr, sizeof(cpu_hdr), (off_t)dump_off);
454 	if (sz != sizeof(cpu_hdr)) {
455 		return (-1);
456 	}
457 	if ((CORE_GETMAGIC(cpu_hdr) != KCORE_MAGIC)
458 		|| (CORE_GETMID(cpu_hdr) != MID_MACHINE)) {
459 		_kvm_err(kd, 0, "invalid magic in cpu_hdr");
460 		return (-1);
461 	}
462 	hdr_size = ALIGN(sizeof(cpu_hdr));
463 
464 	/*
465 	 * Read the CPU segment.
466 	 */
467 	kd->cpu_dsize = cpu_hdr.c_size;
468 	kd->cpu_data = _kvm_malloc(kd, kd->cpu_dsize);
469 	if (kd->cpu_data == NULL)
470 		goto fail;
471 
472 	sz = _kvm_pread(kd, kd->pmfd, kd->cpu_data, (size_t)cpu_hdr.c_size,
473 	    (off_t)dump_off+hdr_size);
474 	if (sz != (ssize_t)cpu_hdr.c_size) {
475 		_kvm_err(kd, 0, "invalid size in cpu_hdr");
476 		goto fail;
477 	}
478 	hdr_size += kd->cpu_dsize;
479 
480 	/*
481 	 * Leave phys mem pointer at beginning of memory data
482 	 */
483 	kd->dump_off = dump_off + hdr_size;
484 	errno = 0;
485 	if (lseek(kd->pmfd, kd->dump_off, SEEK_SET) != kd->dump_off && errno != 0) {
486 		_kvm_err(kd, 0, "invalid dump offset - lseek");
487 		goto fail;
488 	}
489 
490 	/*
491 	 * Create a kcore_hdr.
492 	 */
493 	kd->kcore_hdr = _kvm_malloc(kd, sizeof(kcore_hdr_t));
494 	if (kd->kcore_hdr == NULL)
495 		goto fail;
496 
497 	kd->kcore_hdr->c_hdrsize    = ALIGN(sizeof(kcore_hdr_t));
498 	kd->kcore_hdr->c_seghdrsize = ALIGN(sizeof(kcore_seg_t));
499 	kd->kcore_hdr->c_nseg       = 2;
500 	CORE_SETMAGIC(*(kd->kcore_hdr), KCORE_MAGIC, MID_MACHINE,0);
501 
502 	/*
503 	 * Now that we have a valid header, enable translations.
504 	 */
505 	if (_kvm_initvtop(kd) == 0)
506 		/* Success */
507 		return (hdr_size);
508 
509 fail:
510 	if (kd->kcore_hdr != NULL) {
511 		free(kd->kcore_hdr);
512 		kd->kcore_hdr = NULL;
513 	}
514 	if (kd->cpu_data != NULL) {
515 		free(kd->cpu_data);
516 		kd->cpu_data = NULL;
517 		kd->cpu_dsize = 0;
518 	}
519 	return (-1);
520 }
521 
522 static int
523 clear_gap(kvm_t *kd, FILE *fp, int size)
524 {
525 	if (size <= 0) /* XXX - < 0 should never happen */
526 		return (0);
527 	while (size-- > 0) {
528 		if (fputc(0, fp) == EOF) {
529 			_kvm_syserr(kd, kd->program, "clear_gap");
530 			return (-1);
531 		}
532 	}
533 	return (0);
534 }
535 
536 /*
537  * Write the dump header info to 'fp'. Note that we can't use fseek(3) here
538  * because 'fp' might be a file pointer obtained by zopen().
539  */
540 int
541 kvm_dump_wrtheader(kvm_t *kd, FILE *fp, int dumpsize)
542 {
543 	kcore_seg_t	seghdr;
544 	long		offset;
545 	int		gap;
546 
547 	if (kd->kcore_hdr == NULL || kd->cpu_data == NULL) {
548 		_kvm_err(kd, kd->program, "no valid dump header(s)");
549 		return (-1);
550 	}
551 
552 	/*
553 	 * Write the generic header
554 	 */
555 	offset = 0;
556 	if (fwrite(kd->kcore_hdr, sizeof(kcore_hdr_t), 1, fp) < 1) {
557 		_kvm_syserr(kd, kd->program, "kvm_dump_wrtheader");
558 		return (-1);
559 	}
560 	offset += kd->kcore_hdr->c_hdrsize;
561 	gap     = kd->kcore_hdr->c_hdrsize - sizeof(kcore_hdr_t);
562 	if (clear_gap(kd, fp, gap) == -1)
563 		return (-1);
564 
565 	/*
566 	 * Write the cpu header
567 	 */
568 	CORE_SETMAGIC(seghdr, KCORESEG_MAGIC, 0, CORE_CPU);
569 	seghdr.c_size = (u_long)ALIGN(kd->cpu_dsize);
570 	if (fwrite(&seghdr, sizeof(seghdr), 1, fp) < 1) {
571 		_kvm_syserr(kd, kd->program, "kvm_dump_wrtheader");
572 		return (-1);
573 	}
574 	offset += kd->kcore_hdr->c_seghdrsize;
575 	gap     = kd->kcore_hdr->c_seghdrsize - sizeof(seghdr);
576 	if (clear_gap(kd, fp, gap) == -1)
577 		return (-1);
578 
579 	if (fwrite(kd->cpu_data, kd->cpu_dsize, 1, fp) < 1) {
580 		_kvm_syserr(kd, kd->program, "kvm_dump_wrtheader");
581 		return (-1);
582 	}
583 	offset += seghdr.c_size;
584 	gap     = seghdr.c_size - kd->cpu_dsize;
585 	if (clear_gap(kd, fp, gap) == -1)
586 		return (-1);
587 
588 	/*
589 	 * Write the actual dump data segment header
590 	 */
591 	CORE_SETMAGIC(seghdr, KCORESEG_MAGIC, 0, CORE_DATA);
592 	seghdr.c_size = dumpsize;
593 	if (fwrite(&seghdr, sizeof(seghdr), 1, fp) < 1) {
594 		_kvm_syserr(kd, kd->program, "kvm_dump_wrtheader");
595 		return (-1);
596 	}
597 	offset += kd->kcore_hdr->c_seghdrsize;
598 	gap     = kd->kcore_hdr->c_seghdrsize - sizeof(seghdr);
599 	if (clear_gap(kd, fp, gap) == -1)
600 		return (-1);
601 
602 	return (offset);
603 }
604 
605 kvm_t *
606 kvm_openfiles(const char *uf, const char *mf, const char *sf,
607     int flag, char *errout)
608 {
609 	kvm_t *kd;
610 
611 	if ((kd = malloc(sizeof(*kd))) == NULL) {
612 		(void)strlcpy(errout, strerror(errno), _POSIX2_LINE_MAX);
613 		return (0);
614 	}
615 	kd->program = 0;
616 	return (_kvm_open(kd, uf, mf, sf, flag, errout));
617 }
618 
619 kvm_t *
620 kvm_open(const char *uf, const char *mf, const char *sf, int flag,
621     const char *program)
622 {
623 	kvm_t *kd;
624 
625 	if ((kd = malloc(sizeof(*kd))) == NULL && program != NULL) {
626 		(void)fprintf(stderr, "%s: %s\n", program, strerror(errno));
627 		return (0);
628 	}
629 	kd->program = program;
630 	return (_kvm_open(kd, uf, mf, sf, flag, NULL));
631 }
632 
633 int
634 kvm_close(kvm_t *kd)
635 {
636 	int error = 0;
637 
638 	if (kd->pmfd >= 0)
639 		error |= close(kd->pmfd);
640 	if (kd->vmfd >= 0)
641 		error |= close(kd->vmfd);
642 	kd->alive = 0;
643 	if (kd->nlfd >= 0)
644 		error |= close(kd->nlfd);
645 	if (kd->swfd >= 0)
646 		error |= close(kd->swfd);
647 	if (kd->db != 0)
648 		error |= (kd->db->close)(kd->db);
649 	if (kd->vmst)
650 		_kvm_freevtop(kd);
651 	kd->cpu_dsize = 0;
652 	if (kd->cpu_data != NULL)
653 		free((void *)kd->cpu_data);
654 	if (kd->kcore_hdr != NULL)
655 		free((void *)kd->kcore_hdr);
656 	free(kd->filebase);
657 	free(kd->procbase);
658 	if (kd->swapspc != 0)
659 		free((void *)kd->swapspc);
660 	if (kd->argspc != 0)
661 		free((void *)kd->argspc);
662 	if (kd->argbuf != 0)
663 		free((void *)kd->argbuf);
664 	if (kd->argv != 0)
665 		free((void *)kd->argv);
666 	free((void *)kd);
667 
668 	return (error);
669 }
670 
671 /*
672  * Set up state necessary to do queries on the kernel namelist
673  * data base.  If the data base is out-of-data/incompatible with
674  * given executable, set up things so we revert to standard nlist call.
675  * Only called for live kernels.  Return 0 on success, -1 on failure.
676  */
677 static int
678 kvm_dbopen(kvm_t *kd, const char *uf)
679 {
680 	char dbversion[_POSIX2_LINE_MAX], kversion[_POSIX2_LINE_MAX];
681 	char dbname[PATH_MAX];
682 	struct nlist nitem;
683 	size_t dbversionlen;
684 	DBT rec;
685 
686 	uf = basename(uf);
687 
688 	(void)snprintf(dbname, sizeof(dbname), "%skvm_%s.db", _PATH_VARDB, uf);
689 	kd->db = dbopen(dbname, O_RDONLY, 0, DB_HASH, NULL);
690 	if (kd->db == NULL) {
691 		switch (errno) {
692 		case ENOENT:
693 			/* No kvm_bsd.db, fall back to /bsd silently */
694 			break;
695 		case EFTYPE:
696 			_kvm_err(kd, kd->program,
697 			    "file %s is incorrectly formatted", dbname);
698 			break;
699 		case EINVAL:
700 			_kvm_err(kd, kd->program,
701 			    "invalid argument to dbopen()");
702 			break;
703 		default:
704 			_kvm_err(kd, kd->program, "unknown dbopen() error");
705 			break;
706 		}
707 		return (-1);
708 	}
709 
710 	/*
711 	 * read version out of database
712 	 */
713 	rec.data = VRS_KEY;
714 	rec.size = sizeof(VRS_KEY) - 1;
715 	if ((kd->db->get)(kd->db, (DBT *)&rec, (DBT *)&rec, 0))
716 		goto close;
717 	if (rec.data == 0 || rec.size > sizeof(dbversion))
718 		goto close;
719 
720 	bcopy(rec.data, dbversion, rec.size);
721 	dbversionlen = rec.size;
722 
723 	/*
724 	 * Read version string from kernel memory.
725 	 * Since we are dealing with a live kernel, we can call kvm_read()
726 	 * at this point.
727 	 */
728 	rec.data = VRS_SYM;
729 	rec.size = sizeof(VRS_SYM) - 1;
730 	if ((kd->db->get)(kd->db, (DBT *)&rec, (DBT *)&rec, 0))
731 		goto close;
732 	if (rec.data == 0 || rec.size != sizeof(struct nlist))
733 		goto close;
734 	bcopy(rec.data, &nitem, sizeof(nitem));
735 	if (kvm_read(kd, (u_long)nitem.n_value, kversion, dbversionlen) !=
736 	    dbversionlen)
737 		goto close;
738 	/*
739 	 * If they match, we win - otherwise clear out kd->db so
740 	 * we revert to slow nlist().
741 	 */
742 	if (bcmp(dbversion, kversion, dbversionlen) == 0)
743 		return (0);
744 close:
745 	(void)(kd->db->close)(kd->db);
746 	kd->db = 0;
747 
748 	return (-1);
749 }
750 
751 int
752 kvm_nlist(kvm_t *kd, struct nlist *nl)
753 {
754 	struct nlist *p;
755 	int nvalid, rv;
756 
757 	/*
758 	 * If we can't use the data base, revert to the
759 	 * slow library call.
760 	 */
761 	if (kd->db == 0) {
762 		rv = __fdnlist(kd->nlfd, nl);
763 		if (rv == -1)
764 			_kvm_err(kd, 0, "bad namelist");
765 		return (rv);
766 	}
767 
768 	/*
769 	 * We can use the kvm data base.  Go through each nlist entry
770 	 * and look it up with a db query.
771 	 */
772 	nvalid = 0;
773 	for (p = nl; p->n_name && p->n_name[0]; ++p) {
774 		size_t len;
775 		DBT rec;
776 
777 		if ((len = strlen(p->n_name)) > 4096) {
778 			/* sanity */
779 			_kvm_err(kd, kd->program, "symbol too large");
780 			return (-1);
781 		}
782 		rec.data = p->n_name;
783 		rec.size = len;
784 
785 		/*
786 		 * Make sure that n_value = 0 when the symbol isn't found
787 		 */
788 		p->n_value = 0;
789 
790 		if ((kd->db->get)(kd->db, (DBT *)&rec, (DBT *)&rec, 0))
791 			continue;
792 		if (rec.data == 0 || rec.size != sizeof(struct nlist))
793 			continue;
794 		++nvalid;
795 		/*
796 		 * Avoid alignment issues.
797 		 */
798 		bcopy(&((struct nlist *)rec.data)->n_type,
799 		    &p->n_type, sizeof(p->n_type));
800 		bcopy(&((struct nlist *)rec.data)->n_value,
801 		    &p->n_value, sizeof(p->n_value));
802 	}
803 	/*
804 	 * Return the number of entries that weren't found.
805 	 */
806 	return ((p - nl) - nvalid);
807 }
808 
809 int
810 kvm_dump_inval(kvm_t *kd)
811 {
812 	struct nlist	nl[2];
813 	u_long		x;
814 	paddr_t		pa;
815 
816 	if (ISALIVE(kd)) {
817 		_kvm_err(kd, kd->program, "clearing dump on live kernel");
818 		return (-1);
819 	}
820 	nl[0].n_name = "_dumpmag";
821 	nl[1].n_name = NULL;
822 
823 	if (kvm_nlist(kd, nl) == -1) {
824 		_kvm_err(kd, 0, "bad namelist");
825 		return (-1);
826 	}
827 
828 	if (nl[0].n_value == 0) {
829 		_kvm_err(kd, nl[0].n_name, "not in name list");
830 		return (-1);
831 	}
832 
833 	if (_kvm_kvatop(kd, (u_long)nl[0].n_value, &pa) == 0)
834 		return (-1);
835 
836 	x = 0;
837 	if (_kvm_pwrite(kd, kd->pmfd, &x, sizeof(x),
838 	    (off_t)_kvm_pa2off(kd, pa)) != sizeof(x)) {
839 		_kvm_err(kd, 0, "cannot invalidate dump");
840 		return (-1);
841 	}
842 	return (0);
843 }
844 
845 ssize_t
846 kvm_read(kvm_t *kd, u_long kva, void *buf, size_t len)
847 {
848 	ssize_t cc;
849 	void *cp;
850 
851 	if (ISALIVE(kd)) {
852 		/*
853 		 * We're using /dev/kmem.  Just read straight from the
854 		 * device and let the active kernel do the address translation.
855 		 */
856 		cc = _kvm_pread(kd, kd->vmfd, buf, len, (off_t)kva);
857 		if (cc == -1) {
858 			_kvm_err(kd, 0, "invalid address (%lx)", kva);
859 			return (-1);
860 		} else if (cc < len)
861 			_kvm_err(kd, kd->program, "short read");
862 		return (cc);
863 	} else {
864 		if ((kd->kcore_hdr == NULL) || (kd->cpu_data == NULL)) {
865 			_kvm_err(kd, kd->program, "no valid dump header");
866 			return (-1);
867 		}
868 		cp = buf;
869 		while (len > 0) {
870 			paddr_t	pa;
871 
872 			/* In case of error, _kvm_kvatop sets the err string */
873 			cc = _kvm_kvatop(kd, kva, &pa);
874 			if (cc == 0)
875 				return (-1);
876 			if (cc > len)
877 				cc = len;
878 			cc = _kvm_pread(kd, kd->pmfd, cp, (size_t)cc,
879 			    (off_t)_kvm_pa2off(kd, pa));
880 			if (cc == -1) {
881 				_kvm_syserr(kd, 0, _PATH_MEM);
882 				break;
883 			}
884 			/*
885 			 * If kvm_kvatop returns a bogus value or our core
886 			 * file is truncated, we might wind up seeking beyond
887 			 * the end of the core file in which case the read will
888 			 * return 0 (EOF).
889 			 */
890 			if (cc == 0)
891 				break;
892 			cp = (char *)cp + cc;
893 			kva += cc;
894 			len -= cc;
895 		}
896 		return ((char *)cp - (char *)buf);
897 	}
898 	/* NOTREACHED */
899 }
900 
901 ssize_t
902 kvm_write(kvm_t *kd, u_long kva, const void *buf, size_t len)
903 {
904 	int cc;
905 
906 	if (ISALIVE(kd)) {
907 		/*
908 		 * Just like kvm_read, only we write.
909 		 */
910 		cc = _kvm_pwrite(kd, kd->vmfd, buf, len, (off_t)kva);
911 		if (cc == -1) {
912 			_kvm_err(kd, 0, "invalid address (%lx)", kva);
913 			return (-1);
914 		} else if (cc < len)
915 			_kvm_err(kd, kd->program, "short write");
916 		return (cc);
917 	} else {
918 		_kvm_err(kd, kd->program,
919 		    "kvm_write not implemented for dead kernels");
920 		return (-1);
921 	}
922 	/* NOTREACHED */
923 }
924