xref: /openbsd-src/lib/libkvm/kvm.c (revision 11efff7f3ac2b3cfeff0c0cddc14294d9b3aca4f)
1 /*	$OpenBSD: kvm.c,v 1.42 2004/09/15 19:31:31 miod 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.42 2004/09/15 19:31:31 miod 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, 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), (char *)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 	int 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), (char *)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, cpu_hdr.c_size);
375 	if (kd->cpu_data == NULL)
376 		goto fail;
377 
378 	sz = _kvm_pread(kd, kd->pmfd, kd->cpu_data, cpu_hdr.c_size, (off_t)offset);
379 	if (sz != cpu_hdr.c_size) {
380 		goto fail;
381 	}
382 
383 	offset += cpu_hdr.c_size;
384 
385 	/*
386 	 * Read the next segment header: data segment
387 	 */
388 	sz = _kvm_pread(kd, kd->pmfd, &mem_hdr, sizeof(mem_hdr), (off_t)offset);
389 	if (sz != sizeof(mem_hdr)) {
390 		goto fail;
391 	}
392 
393 	offset += kcore_hdr.c_seghdrsize;
394 
395 	if ((CORE_GETMAGIC(mem_hdr) != KCORESEG_MAGIC) ||
396 	    (CORE_GETFLAG(mem_hdr) != CORE_DATA))
397 		goto fail;
398 
399 	kd->dump_off = offset;
400 	return (0);
401 
402 fail:
403 	if (kd->kcore_hdr != NULL) {
404 		free(kd->kcore_hdr);
405 		kd->kcore_hdr = NULL;
406 	}
407 	if (kd->cpu_data != NULL) {
408 		free(kd->cpu_data);
409 		kd->cpu_data = NULL;
410 		kd->cpu_dsize = 0;
411 	}
412 
413 	return (-1);
414 }
415 
416 /*
417  * The format while on the dump device is: (new format)
418  *    kcore_seg_t cpu_hdr;
419  *    (opaque)    cpu_data; (size is cpu_hdr.c_size)
420  *    kcore_seg_t mem_hdr;
421  *    (memory)    mem_data; (size is mem_hdr.c_size)
422  */
423 int
424 kvm_dump_mkheader(kvm_t *kd, off_t dump_off)
425 {
426 	kcore_seg_t	cpu_hdr;
427 	int	hdr_size, sz;
428 
429 	if (kd->kcore_hdr != NULL) {
430 	    _kvm_err(kd, kd->program, "already has a dump header");
431 	    return (-1);
432 	}
433 	if (ISALIVE(kd)) {
434 		_kvm_err(kd, kd->program, "don't use on live kernel");
435 		return (-1);
436 	}
437 
438 	/*
439 	 * Validate new format crash dump
440 	 */
441 	sz = _kvm_pread(kd, kd->pmfd, &cpu_hdr, sizeof(cpu_hdr), (off_t)dump_off);
442 	if (sz != sizeof(cpu_hdr)) {
443 		return (-1);
444 	}
445 	if ((CORE_GETMAGIC(cpu_hdr) != KCORE_MAGIC)
446 		|| (CORE_GETMID(cpu_hdr) != MID_MACHINE)) {
447 		_kvm_err(kd, 0, "invalid magic in cpu_hdr");
448 		return (-1);
449 	}
450 	hdr_size = ALIGN(sizeof(cpu_hdr));
451 
452 	/*
453 	 * Read the CPU segment.
454 	 */
455 	kd->cpu_dsize = cpu_hdr.c_size;
456 	kd->cpu_data = _kvm_malloc(kd, kd->cpu_dsize);
457 	if (kd->cpu_data == NULL)
458 		goto fail;
459 
460 	sz = _kvm_pread(kd, kd->pmfd, kd->cpu_data, cpu_hdr.c_size,
461 	    (off_t)dump_off+hdr_size);
462 	if (sz != cpu_hdr.c_size) {
463 		_kvm_err(kd, 0, "invalid size in cpu_hdr");
464 		goto fail;
465 	}
466 	hdr_size += kd->cpu_dsize;
467 
468 	/*
469 	 * Leave phys mem pointer at beginning of memory data
470 	 */
471 	kd->dump_off = dump_off + hdr_size;
472 	errno = 0;
473 	if (lseek(kd->pmfd, kd->dump_off, SEEK_SET) != kd->dump_off && errno != 0) {
474 		_kvm_err(kd, 0, "invalid dump offset - lseek");
475 		goto fail;
476 	}
477 
478 	/*
479 	 * Create a kcore_hdr.
480 	 */
481 	kd->kcore_hdr = _kvm_malloc(kd, sizeof(kcore_hdr_t));
482 	if (kd->kcore_hdr == NULL)
483 		goto fail;
484 
485 	kd->kcore_hdr->c_hdrsize    = ALIGN(sizeof(kcore_hdr_t));
486 	kd->kcore_hdr->c_seghdrsize = ALIGN(sizeof(kcore_seg_t));
487 	kd->kcore_hdr->c_nseg       = 2;
488 	CORE_SETMAGIC(*(kd->kcore_hdr), KCORE_MAGIC, MID_MACHINE,0);
489 
490 	/*
491 	 * Now that we have a valid header, enable translations.
492 	 */
493 	if (_kvm_initvtop(kd) == 0)
494 		/* Success */
495 		return (hdr_size);
496 
497 fail:
498 	if (kd->kcore_hdr != NULL) {
499 		free(kd->kcore_hdr);
500 		kd->kcore_hdr = NULL;
501 	}
502 	if (kd->cpu_data != NULL) {
503 		free(kd->cpu_data);
504 		kd->cpu_data = NULL;
505 		kd->cpu_dsize = 0;
506 	}
507 	return (-1);
508 }
509 
510 static int
511 clear_gap(kvm_t *kd, FILE *fp, int size)
512 {
513 	if (size <= 0) /* XXX - < 0 should never happen */
514 		return (0);
515 	while (size-- > 0) {
516 		if (fputc(0, fp) == EOF) {
517 			_kvm_syserr(kd, kd->program, "clear_gap");
518 			return (-1);
519 		}
520 	}
521 	return (0);
522 }
523 
524 /*
525  * Write the dump header info to 'fp'. Note that we can't use fseek(3) here
526  * because 'fp' might be a file pointer obtained by zopen().
527  */
528 int
529 kvm_dump_wrtheader(kvm_t *kd, FILE *fp, int dumpsize)
530 {
531 	kcore_seg_t	seghdr;
532 	long		offset;
533 	int		gap;
534 
535 	if (kd->kcore_hdr == NULL || kd->cpu_data == NULL) {
536 		_kvm_err(kd, kd->program, "no valid dump header(s)");
537 		return (-1);
538 	}
539 
540 	/*
541 	 * Write the generic header
542 	 */
543 	offset = 0;
544 	if (fwrite((void*)kd->kcore_hdr, sizeof(kcore_hdr_t), 1, fp) <= 0) {
545 		_kvm_syserr(kd, kd->program, "kvm_dump_wrtheader");
546 		return (-1);
547 	}
548 	offset += kd->kcore_hdr->c_hdrsize;
549 	gap     = kd->kcore_hdr->c_hdrsize - sizeof(kcore_hdr_t);
550 	if (clear_gap(kd, fp, gap) == -1)
551 		return (-1);
552 
553 	/*
554 	 * Write the cpu header
555 	 */
556 	CORE_SETMAGIC(seghdr, KCORESEG_MAGIC, 0, CORE_CPU);
557 	seghdr.c_size = ALIGN(kd->cpu_dsize);
558 	if (fwrite((void*)&seghdr, sizeof(seghdr), 1, fp) <= 0) {
559 		_kvm_syserr(kd, kd->program, "kvm_dump_wrtheader");
560 		return (-1);
561 	}
562 	offset += kd->kcore_hdr->c_seghdrsize;
563 	gap     = kd->kcore_hdr->c_seghdrsize - sizeof(seghdr);
564 	if (clear_gap(kd, fp, gap) == -1)
565 		return (-1);
566 
567 	if (fwrite((void*)kd->cpu_data, kd->cpu_dsize, 1, fp) <= 0) {
568 		_kvm_syserr(kd, kd->program, "kvm_dump_wrtheader");
569 		return (-1);
570 	}
571 	offset += seghdr.c_size;
572 	gap     = seghdr.c_size - kd->cpu_dsize;
573 	if (clear_gap(kd, fp, gap) == -1)
574 		return (-1);
575 
576 	/*
577 	 * Write the actual dump data segment header
578 	 */
579 	CORE_SETMAGIC(seghdr, KCORESEG_MAGIC, 0, CORE_DATA);
580 	seghdr.c_size = dumpsize;
581 	if (fwrite((void*)&seghdr, sizeof(seghdr), 1, fp) <= 0) {
582 		_kvm_syserr(kd, kd->program, "kvm_dump_wrtheader");
583 		return (-1);
584 	}
585 	offset += kd->kcore_hdr->c_seghdrsize;
586 	gap     = kd->kcore_hdr->c_seghdrsize - sizeof(seghdr);
587 	if (clear_gap(kd, fp, gap) == -1)
588 		return (-1);
589 
590 	return (offset);
591 }
592 
593 kvm_t *
594 kvm_openfiles(const char *uf, const char *mf, const char *sf,
595     unsigned int flag, char *errout)
596 {
597 	kvm_t *kd;
598 
599 	if ((kd = malloc(sizeof(*kd))) == NULL) {
600 		(void)strlcpy(errout, strerror(errno), _POSIX2_LINE_MAX);
601 		return (0);
602 	}
603 	kd->program = 0;
604 	return (_kvm_open(kd, uf, mf, sf, flag, errout));
605 }
606 
607 kvm_t *
608 kvm_open(const char *uf, const char *mf, const char *sf, int flag,
609     const char *program)
610 {
611 	kvm_t *kd;
612 
613 	if ((kd = malloc(sizeof(*kd))) == NULL && program != NULL) {
614 		(void)fprintf(stderr, "%s: %s\n", program, strerror(errno));
615 		return (0);
616 	}
617 	kd->program = program;
618 	return (_kvm_open(kd, uf, mf, sf, flag, NULL));
619 }
620 
621 int
622 kvm_close(kvm_t *kd)
623 {
624 	int error = 0;
625 
626 	if (kd->pmfd >= 0)
627 		error |= close(kd->pmfd);
628 	if (kd->vmfd >= 0)
629 		error |= close(kd->vmfd);
630 	kd->alive = 0;
631 	if (kd->nlfd >= 0)
632 		error |= close(kd->nlfd);
633 	if (kd->swfd >= 0)
634 		error |= close(kd->swfd);
635 	if (kd->db != 0)
636 		error |= (kd->db->close)(kd->db);
637 	if (kd->vmst)
638 		_kvm_freevtop(kd);
639 	kd->cpu_dsize = 0;
640 	if (kd->cpu_data != NULL)
641 		free((void *)kd->cpu_data);
642 	if (kd->kcore_hdr != NULL)
643 		free((void *)kd->kcore_hdr);
644 	if (kd->procbase != 0)
645 		free((void *)kd->procbase);
646 	if (kd->procbase2 != 0)
647 		free(kd->procbase2);
648 	if (kd->swapspc != 0)
649 		free((void *)kd->swapspc);
650 	if (kd->argspc != 0)
651 		free((void *)kd->argspc);
652 	if (kd->argbuf != 0)
653 		free((void *)kd->argbuf);
654 	if (kd->argv != 0)
655 		free((void *)kd->argv);
656 	free((void *)kd);
657 
658 	return (error);
659 }
660 
661 /*
662  * Set up state necessary to do queries on the kernel namelist
663  * data base.  If the data base is out-of-data/incompatible with
664  * given executable, set up things so we revert to standard nlist call.
665  * Only called for live kernels.  Return 0 on success, -1 on failure.
666  */
667 static int
668 kvm_dbopen(kvm_t *kd, const char *uf)
669 {
670 	char dbversion[_POSIX2_LINE_MAX], kversion[_POSIX2_LINE_MAX];
671 	char dbname[MAXPATHLEN];
672 	struct nlist nitem;
673 	int dbversionlen;
674 	DBT rec;
675 
676 	uf = basename((char *)uf);
677 
678 	(void)snprintf(dbname, sizeof(dbname), "%skvm_%s.db", _PATH_VARDB, uf);
679 	kd->db = dbopen(dbname, O_RDONLY, 0, DB_HASH, NULL);
680 	if (kd->db == NULL) {
681 		switch (errno) {
682 		case ENOENT:
683 			/* No kvm_bsd.db, fall back to /bsd silently */
684 			break;
685 		case EFTYPE:
686 			_kvm_err(kd, kd->program,
687 			    "file %s is incorrectly formatted", dbname);
688 			break;
689 		case EINVAL:
690 			_kvm_err(kd, kd->program,
691 			    "invalid argument to dbopen()");
692 			break;
693 		default:
694 			_kvm_err(kd, kd->program, "unknown dbopen() error");
695 			break;
696 		}
697 		return (-1);
698 	}
699 
700 	/*
701 	 * read version out of database
702 	 */
703 	rec.data = VRS_KEY;
704 	rec.size = sizeof(VRS_KEY) - 1;
705 	if ((kd->db->get)(kd->db, (DBT *)&rec, (DBT *)&rec, 0))
706 		goto close;
707 	if (rec.data == 0 || rec.size > sizeof(dbversion))
708 		goto close;
709 
710 	bcopy(rec.data, dbversion, rec.size);
711 	dbversionlen = rec.size;
712 	/*
713 	 * Read version string from kernel memory.
714 	 * Since we are dealing with a live kernel, we can call kvm_read()
715 	 * at this point.
716 	 */
717 	rec.data = VRS_SYM;
718 	rec.size = sizeof(VRS_SYM) - 1;
719 	if ((kd->db->get)(kd->db, (DBT *)&rec, (DBT *)&rec, 0))
720 		goto close;
721 	if (rec.data == 0 || rec.size != sizeof(struct nlist))
722 		goto close;
723 	bcopy((char *)rec.data, (char *)&nitem, sizeof(nitem));
724 	if (kvm_read(kd, (u_long)nitem.n_value, kversion, dbversionlen) !=
725 	    dbversionlen)
726 		goto close;
727 	/*
728 	 * If they match, we win - otherwise clear out kd->db so
729 	 * we revert to slow nlist().
730 	 */
731 	if (bcmp(dbversion, kversion, dbversionlen) == 0)
732 		return (0);
733 close:
734 	(void)(kd->db->close)(kd->db);
735 	kd->db = 0;
736 
737 	return (-1);
738 }
739 
740 int
741 kvm_nlist(kvm_t *kd, struct nlist *nl)
742 {
743 	struct nlist *p;
744 	int nvalid, rv;
745 
746 	/*
747 	 * If we can't use the data base, revert to the
748 	 * slow library call.
749 	 */
750 	if (kd->db == 0) {
751 		rv = __fdnlist(kd->nlfd, nl);
752 		if (rv == -1)
753 			_kvm_err(kd, 0, "bad namelist");
754 		return (rv);
755 	}
756 
757 	/*
758 	 * We can use the kvm data base.  Go through each nlist entry
759 	 * and look it up with a db query.
760 	 */
761 	nvalid = 0;
762 	for (p = nl; p->n_name && p->n_name[0]; ++p) {
763 		int len;
764 		DBT rec;
765 
766 		if ((len = strlen(p->n_name)) > 4096) {
767 			/* sanity */
768 			_kvm_err(kd, kd->program, "symbol too large");
769 			return (-1);
770 		}
771 		rec.data = p->n_name;
772 		rec.size = len;
773 
774 		/*
775 		 * Make sure that n_value = 0 when the symbol isn't found
776 		 */
777 		p->n_value = 0;
778 
779 		if ((kd->db->get)(kd->db, (DBT *)&rec, (DBT *)&rec, 0))
780 			continue;
781 		if (rec.data == 0 || rec.size != sizeof(struct nlist))
782 			continue;
783 		++nvalid;
784 		/*
785 		 * Avoid alignment issues.
786 		 */
787 		bcopy((char *)&((struct nlist *)rec.data)->n_type,
788 		    (char *)&p->n_type, sizeof(p->n_type));
789 		bcopy((char *)&((struct nlist *)rec.data)->n_value,
790 		    (char *)&p->n_value, sizeof(p->n_value));
791 	}
792 	/*
793 	 * Return the number of entries that weren't found.
794 	 */
795 	return ((p - nl) - nvalid);
796 }
797 
798 int
799 kvm_dump_inval(kvm_t *kd)
800 {
801 	struct nlist	nlist[2];
802 	u_long		pa, x;
803 
804 	if (ISALIVE(kd)) {
805 		_kvm_err(kd, kd->program, "clearing dump on live kernel");
806 		return (-1);
807 	}
808 	nlist[0].n_name = "_dumpmag";
809 	nlist[1].n_name = NULL;
810 
811 	if (kvm_nlist(kd, nlist) == -1) {
812 		_kvm_err(kd, 0, "bad namelist");
813 		return (-1);
814 	}
815 
816 	if (nlist[0].n_value == 0) {
817 		_kvm_err(kd, nlist[0].n_name, "not in name list");
818 		return (-1);
819 	}
820 
821 	if (_kvm_kvatop(kd, (u_long)nlist[0].n_value, &pa) == 0)
822 		return (-1);
823 
824 	x = 0;
825 	if (_kvm_pwrite(kd, kd->pmfd, &x, sizeof(x),
826 	    (off_t)_kvm_pa2off(kd, pa)) != sizeof(x)) {
827 		_kvm_err(kd, 0, "cannot invalidate dump");
828 		return (-1);
829 	}
830 	return (0);
831 }
832 
833 ssize_t
834 kvm_read(kvm_t *kd, u_long kva, void *buf, size_t len)
835 {
836 	int cc;
837 	void *cp;
838 
839 	if (ISALIVE(kd)) {
840 		/*
841 		 * We're using /dev/kmem.  Just read straight from the
842 		 * device and let the active kernel do the address translation.
843 		 */
844 		cc = _kvm_pread(kd, kd->vmfd, buf, len, (off_t)kva);
845 		if (cc == -1) {
846 			_kvm_err(kd, 0, "invalid address (%lx)", kva);
847 			return (-1);
848 		} else if (cc < len)
849 			_kvm_err(kd, kd->program, "short read");
850 		return (cc);
851 	} else {
852 		if ((kd->kcore_hdr == NULL) || (kd->cpu_data == NULL)) {
853 			_kvm_err(kd, kd->program, "no valid dump header");
854 			return (-1);
855 		}
856 		cp = buf;
857 		while (len > 0) {
858 			u_long	pa;
859 
860 			/* In case of error, _kvm_kvatop sets the err string */
861 			cc = _kvm_kvatop(kd, kva, &pa);
862 			if (cc == 0)
863 				return (-1);
864 			if (cc > len)
865 				cc = len;
866 			cc = _kvm_pread(kd, kd->pmfd, cp, cc,
867 			    (off_t)_kvm_pa2off(kd, pa));
868 			if (cc == -1) {
869 				_kvm_syserr(kd, 0, _PATH_MEM);
870 				break;
871 			}
872 			/*
873 			 * If kvm_kvatop returns a bogus value or our core
874 			 * file is truncated, we might wind up seeking beyond
875 			 * the end of the core file in which case the read will
876 			 * return 0 (EOF).
877 			 */
878 			if (cc == 0)
879 				break;
880 			cp = (char *)cp + cc;
881 			kva += cc;
882 			len -= cc;
883 		}
884 		return ((char *)cp - (char *)buf);
885 	}
886 	/* NOTREACHED */
887 }
888 
889 ssize_t
890 kvm_write(kvm_t *kd, u_long kva, const void *buf, size_t len)
891 {
892 	int cc;
893 
894 	if (ISALIVE(kd)) {
895 		/*
896 		 * Just like kvm_read, only we write.
897 		 */
898 		cc = _kvm_pwrite(kd, kd->vmfd, (void*)buf, (size_t)len, (off_t)kva);
899 		if (cc == -1) {
900 			_kvm_err(kd, 0, "invalid address (%lx)", kva);
901 			return (-1);
902 		} else if (cc < len)
903 			_kvm_err(kd, kd->program, "short write");
904 		return (cc);
905 	} else {
906 		_kvm_err(kd, kd->program,
907 		    "kvm_write not implemented for dead kernels");
908 		return (-1);
909 	}
910 	/* NOTREACHED */
911 }
912 
913 static int
914 kvm_setfd(kvm_t *kd)
915 {
916 	if (kd->pmfd >= 0 && fcntl(kd->pmfd, F_SETFD, FD_CLOEXEC) < 0)
917 		return (-1);
918 	if (kd->vmfd >= 0 && fcntl(kd->vmfd, F_SETFD, FD_CLOEXEC) < 0)
919 		return (-1);
920 	if (kd->nlfd >= 0 && fcntl(kd->nlfd, F_SETFD, FD_CLOEXEC) < 0)
921 		return (-1);
922 	if (kd->swfd >= 0 && fcntl(kd->swfd, F_SETFD, FD_CLOEXEC) < 0)
923 		return (-1);
924 
925 	return (0);
926 }
927