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