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