xref: /openbsd-src/lib/libkvm/kvm.c (revision a28daedfc357b214be5c701aa8ba8adb29a7f1c2)
1 /*	$OpenBSD: kvm.c,v 1.46 2009/01/21 22:18:00 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.46 2009/01/21 22:18:00 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, 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 
217 	if ((kd->pmfd = open(mf, flag, 0)) < 0) {
218 		_kvm_syserr(kd, kd->program, "%s", mf);
219 		goto failed;
220 	}
221 	if (fstat(kd->pmfd, &st) < 0) {
222 		_kvm_syserr(kd, kd->program, "%s", mf);
223 		goto failed;
224 	}
225 	if (S_ISCHR(st.st_mode)) {
226 		/*
227 		 * If this is a character special device, then check that
228 		 * it's /dev/mem.  If so, open kmem too.  (Maybe we should
229 		 * make it work for either /dev/mem or /dev/kmem -- in either
230 		 * case you're working with a live kernel.)
231 		 */
232 		if (strcmp(mf, _PATH_MEM) != 0) {	/* XXX */
233 			_kvm_err(kd, kd->program,
234 				 "%s: not physical memory device", mf);
235 			goto failed;
236 		}
237 		if ((kd->vmfd = open(_PATH_KMEM, flag, 0)) < 0) {
238 			_kvm_syserr(kd, kd->program, "%s", _PATH_KMEM);
239 			goto failed;
240 		}
241 		kd->alive = 1;
242 		if (sf != NULL && (kd->swfd = open(sf, flag, 0)) < 0) {
243 			_kvm_syserr(kd, kd->program, "%s", sf);
244 			goto failed;
245 		}
246 		/*
247 		 * Open kvm nlist database.  We only try to use
248 		 * the pre-built database if the namelist file name
249 		 * pointer is NULL.  If the database cannot or should
250 		 * not be opened, open the namelist argument so we
251 		 * revert to slow nlist() calls.
252 		 * If no file is specified, try opening _PATH_KSYMS and
253 		 * fall back to _PATH_UNIX.
254 		 */
255 		if (kvm_dbopen(kd, uf ? uf : _PATH_UNIX) == -1 &&
256 		    ((uf && (kd->nlfd = open(uf, O_RDONLY, 0)) == -1) || (!uf &&
257 		    (kd->nlfd = open((uf = _PATH_KSYMS), O_RDONLY, 0)) == -1 &&
258 		    (kd->nlfd = open((uf = _PATH_UNIX), O_RDONLY, 0)) == -1))) {
259 			_kvm_syserr(kd, kd->program, "%s", uf);
260 			goto failed;
261 		}
262 	} else {
263 		/*
264 		 * This is a crash dump.
265 		 * Initialize the virtual address translation machinery,
266 		 * but first setup the namelist fd.
267 		 * If no file is specified, try opening _PATH_KSYMS and
268 		 * fall back to _PATH_UNIX.
269 		 */
270 		if ((uf && (kd->nlfd = open(uf, O_RDONLY, 0)) == -1) || (!uf &&
271 		    (kd->nlfd = open((uf = _PATH_KSYMS), O_RDONLY, 0)) == -1 &&
272 		    (kd->nlfd = open((uf = _PATH_UNIX), O_RDONLY, 0)) == -1)) {
273 			_kvm_syserr(kd, kd->program, "%s", uf);
274 			goto failed;
275 		}
276 
277 		/*
278 		 * If there is no valid core header, fail silently here.
279 		 * The address translations however will fail without
280 		 * header. Things can be made to run by calling
281 		 * kvm_dump_mkheader() before doing any translation.
282 		 */
283 		if (_kvm_get_header(kd) == 0) {
284 			if (_kvm_initvtop(kd) < 0)
285 				goto failed;
286 		}
287 	}
288 	if (kvm_setfd(kd) == 0)
289 		return (kd);
290 	else
291 		_kvm_syserr(kd, kd->program, "can't set close on exec flag");
292 failed:
293 	/*
294 	 * Copy out the error if doing sane error semantics.
295 	 */
296 	if (errout != 0)
297 		(void)strlcpy(errout, kd->errbuf, _POSIX2_LINE_MAX);
298 	(void)kvm_close(kd);
299 	return (0);
300 }
301 
302 /*
303  * The kernel dump file (from savecore) contains:
304  *    kcore_hdr_t kcore_hdr;
305  *    kcore_seg_t cpu_hdr;
306  *    (opaque)    cpu_data; (size is cpu_hdr.c_size)
307  *    kcore_seg_t mem_hdr;
308  *    (memory)    mem_data; (size is mem_hdr.c_size)
309  *
310  * Note: khdr is padded to khdr.c_hdrsize;
311  * cpu_hdr and mem_hdr are padded to khdr.c_seghdrsize
312  */
313 static int
314 _kvm_get_header(kvm_t *kd)
315 {
316 	kcore_hdr_t	kcore_hdr;
317 	kcore_seg_t	cpu_hdr;
318 	kcore_seg_t	mem_hdr;
319 	size_t		offset;
320 	ssize_t		sz;
321 
322 	/*
323 	 * Read the kcore_hdr_t
324 	 */
325 	sz = _kvm_pread(kd, kd->pmfd, &kcore_hdr, sizeof(kcore_hdr), (off_t)0);
326 	if (sz != sizeof(kcore_hdr)) {
327 		return (-1);
328 	}
329 
330 	/*
331 	 * Currently, we only support dump-files made by the current
332 	 * architecture...
333 	 */
334 	if ((CORE_GETMAGIC(kcore_hdr) != KCORE_MAGIC) ||
335 	    (CORE_GETMID(kcore_hdr) != MID_MACHINE))
336 		return (-1);
337 
338 	/*
339 	 * Currently, we only support exactly 2 segments: cpu-segment
340 	 * and data-segment in exactly that order.
341 	 */
342 	if (kcore_hdr.c_nseg != 2)
343 		return (-1);
344 
345 	/*
346 	 * Save away the kcore_hdr.  All errors after this
347 	 * should do a to "goto fail" to deallocate things.
348 	 */
349 	kd->kcore_hdr = _kvm_malloc(kd, sizeof(kcore_hdr));
350 	if (kd->kcore_hdr == NULL)
351 		goto fail;
352 	memcpy(kd->kcore_hdr, &kcore_hdr, sizeof(kcore_hdr));
353 	offset = kcore_hdr.c_hdrsize;
354 
355 	/*
356 	 * Read the CPU segment header
357 	 */
358 	sz = _kvm_pread(kd, kd->pmfd, &cpu_hdr, sizeof(cpu_hdr), (off_t)offset);
359 	if (sz != sizeof(cpu_hdr)) {
360 		goto fail;
361 	}
362 
363 	if ((CORE_GETMAGIC(cpu_hdr) != KCORESEG_MAGIC) ||
364 	    (CORE_GETFLAG(cpu_hdr) != CORE_CPU))
365 		goto fail;
366 	offset += kcore_hdr.c_seghdrsize;
367 
368 	/*
369 	 * Read the CPU segment DATA.
370 	 */
371 	kd->cpu_dsize = cpu_hdr.c_size;
372 	kd->cpu_data = _kvm_malloc(kd, (size_t)cpu_hdr.c_size);
373 	if (kd->cpu_data == NULL)
374 		goto fail;
375 
376 	sz = _kvm_pread(kd, kd->pmfd, kd->cpu_data, (size_t)cpu_hdr.c_size,
377 	    (off_t)offset);
378 	if (sz != (size_t)cpu_hdr.c_size) {
379 		goto fail;
380 	}
381 
382 	offset += cpu_hdr.c_size;
383 
384 	/*
385 	 * Read the next segment header: data segment
386 	 */
387 	sz = _kvm_pread(kd, kd->pmfd, &mem_hdr, sizeof(mem_hdr), (off_t)offset);
388 	if (sz != sizeof(mem_hdr)) {
389 		goto fail;
390 	}
391 
392 	offset += kcore_hdr.c_seghdrsize;
393 
394 	if ((CORE_GETMAGIC(mem_hdr) != KCORESEG_MAGIC) ||
395 	    (CORE_GETFLAG(mem_hdr) != CORE_DATA))
396 		goto fail;
397 
398 	kd->dump_off = offset;
399 	return (0);
400 
401 fail:
402 	if (kd->kcore_hdr != NULL) {
403 		free(kd->kcore_hdr);
404 		kd->kcore_hdr = NULL;
405 	}
406 	if (kd->cpu_data != NULL) {
407 		free(kd->cpu_data);
408 		kd->cpu_data = NULL;
409 		kd->cpu_dsize = 0;
410 	}
411 
412 	return (-1);
413 }
414 
415 /*
416  * The format while on the dump device is: (new format)
417  *    kcore_seg_t cpu_hdr;
418  *    (opaque)    cpu_data; (size is cpu_hdr.c_size)
419  *    kcore_seg_t mem_hdr;
420  *    (memory)    mem_data; (size is mem_hdr.c_size)
421  */
422 int
423 kvm_dump_mkheader(kvm_t *kd, off_t dump_off)
424 {
425 	kcore_seg_t	cpu_hdr;
426 	int	hdr_size;
427 	ssize_t 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, (size_t)cpu_hdr.c_size,
461 	    (off_t)dump_off+hdr_size);
462 	if (sz != (ssize_t)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(kd->kcore_hdr, sizeof(kcore_hdr_t), 1, fp) < 1) {
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 = (u_long)ALIGN(kd->cpu_dsize);
558 	if (fwrite(&seghdr, sizeof(seghdr), 1, fp) < 1) {
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(kd->cpu_data, kd->cpu_dsize, 1, fp) < 1) {
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(&seghdr, sizeof(seghdr), 1, fp) < 1) {
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     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 	size_t dbversionlen;
674 	DBT rec;
675 
676 	uf = basename(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 	/*
714 	 * Read version string from kernel memory.
715 	 * Since we are dealing with a live kernel, we can call kvm_read()
716 	 * at this point.
717 	 */
718 	rec.data = VRS_SYM;
719 	rec.size = sizeof(VRS_SYM) - 1;
720 	if ((kd->db->get)(kd->db, (DBT *)&rec, (DBT *)&rec, 0))
721 		goto close;
722 	if (rec.data == 0 || rec.size != sizeof(struct nlist))
723 		goto close;
724 	bcopy(rec.data, &nitem, sizeof(nitem));
725 	if (kvm_read(kd, (u_long)nitem.n_value, kversion, dbversionlen) !=
726 	    dbversionlen)
727 		goto close;
728 	/*
729 	 * If they match, we win - otherwise clear out kd->db so
730 	 * we revert to slow nlist().
731 	 */
732 	if (bcmp(dbversion, kversion, dbversionlen) == 0)
733 		return (0);
734 close:
735 	(void)(kd->db->close)(kd->db);
736 	kd->db = 0;
737 
738 	return (-1);
739 }
740 
741 int
742 kvm_nlist(kvm_t *kd, struct nlist *nl)
743 {
744 	struct nlist *p;
745 	int nvalid, rv;
746 
747 	/*
748 	 * If we can't use the data base, revert to the
749 	 * slow library call.
750 	 */
751 	if (kd->db == 0) {
752 		rv = __fdnlist(kd->nlfd, nl);
753 		if (rv == -1)
754 			_kvm_err(kd, 0, "bad namelist");
755 		return (rv);
756 	}
757 
758 	/*
759 	 * We can use the kvm data base.  Go through each nlist entry
760 	 * and look it up with a db query.
761 	 */
762 	nvalid = 0;
763 	for (p = nl; p->n_name && p->n_name[0]; ++p) {
764 		size_t len;
765 		DBT rec;
766 
767 		if ((len = strlen(p->n_name)) > 4096) {
768 			/* sanity */
769 			_kvm_err(kd, kd->program, "symbol too large");
770 			return (-1);
771 		}
772 		rec.data = p->n_name;
773 		rec.size = len;
774 
775 		/*
776 		 * Make sure that n_value = 0 when the symbol isn't found
777 		 */
778 		p->n_value = 0;
779 
780 		if ((kd->db->get)(kd->db, (DBT *)&rec, (DBT *)&rec, 0))
781 			continue;
782 		if (rec.data == 0 || rec.size != sizeof(struct nlist))
783 			continue;
784 		++nvalid;
785 		/*
786 		 * Avoid alignment issues.
787 		 */
788 		bcopy(&((struct nlist *)rec.data)->n_type,
789 		    &p->n_type, sizeof(p->n_type));
790 		bcopy(&((struct nlist *)rec.data)->n_value,
791 		    &p->n_value, sizeof(p->n_value));
792 	}
793 	/*
794 	 * Return the number of entries that weren't found.
795 	 */
796 	return ((p - nl) - nvalid);
797 }
798 
799 int
800 kvm_dump_inval(kvm_t *kd)
801 {
802 	struct nlist	nl[2];
803 	u_long		x;
804 	paddr_t		pa;
805 
806 	if (ISALIVE(kd)) {
807 		_kvm_err(kd, kd->program, "clearing dump on live kernel");
808 		return (-1);
809 	}
810 	nl[0].n_name = "_dumpmag";
811 	nl[1].n_name = NULL;
812 
813 	if (kvm_nlist(kd, nl) == -1) {
814 		_kvm_err(kd, 0, "bad namelist");
815 		return (-1);
816 	}
817 
818 	if (nl[0].n_value == 0) {
819 		_kvm_err(kd, nl[0].n_name, "not in name list");
820 		return (-1);
821 	}
822 
823 	if (_kvm_kvatop(kd, (u_long)nl[0].n_value, &pa) == 0)
824 		return (-1);
825 
826 	x = 0;
827 	if (_kvm_pwrite(kd, kd->pmfd, &x, sizeof(x),
828 	    (off_t)_kvm_pa2off(kd, pa)) != sizeof(x)) {
829 		_kvm_err(kd, 0, "cannot invalidate dump");
830 		return (-1);
831 	}
832 	return (0);
833 }
834 
835 ssize_t
836 kvm_read(kvm_t *kd, u_long kva, void *buf, size_t len)
837 {
838 	ssize_t cc;
839 	void *cp;
840 
841 	if (ISALIVE(kd)) {
842 		/*
843 		 * We're using /dev/kmem.  Just read straight from the
844 		 * device and let the active kernel do the address translation.
845 		 */
846 		cc = _kvm_pread(kd, kd->vmfd, buf, len, (off_t)kva);
847 		if (cc == -1) {
848 			_kvm_err(kd, 0, "invalid address (%lx)", kva);
849 			return (-1);
850 		} else if (cc < len)
851 			_kvm_err(kd, kd->program, "short read");
852 		return (cc);
853 	} else {
854 		if ((kd->kcore_hdr == NULL) || (kd->cpu_data == NULL)) {
855 			_kvm_err(kd, kd->program, "no valid dump header");
856 			return (-1);
857 		}
858 		cp = buf;
859 		while (len > 0) {
860 			paddr_t	pa;
861 
862 			/* In case of error, _kvm_kvatop sets the err string */
863 			cc = _kvm_kvatop(kd, kva, &pa);
864 			if (cc == 0)
865 				return (-1);
866 			if (cc > len)
867 				cc = len;
868 			cc = _kvm_pread(kd, kd->pmfd, cp, (size_t)cc,
869 			    (off_t)_kvm_pa2off(kd, pa));
870 			if (cc == -1) {
871 				_kvm_syserr(kd, 0, _PATH_MEM);
872 				break;
873 			}
874 			/*
875 			 * If kvm_kvatop returns a bogus value or our core
876 			 * file is truncated, we might wind up seeking beyond
877 			 * the end of the core file in which case the read will
878 			 * return 0 (EOF).
879 			 */
880 			if (cc == 0)
881 				break;
882 			cp = (char *)cp + cc;
883 			kva += cc;
884 			len -= cc;
885 		}
886 		return ((char *)cp - (char *)buf);
887 	}
888 	/* NOTREACHED */
889 }
890 
891 ssize_t
892 kvm_write(kvm_t *kd, u_long kva, const void *buf, size_t len)
893 {
894 	int cc;
895 
896 	if (ISALIVE(kd)) {
897 		/*
898 		 * Just like kvm_read, only we write.
899 		 */
900 		cc = _kvm_pwrite(kd, kd->vmfd, buf, len, (off_t)kva);
901 		if (cc == -1) {
902 			_kvm_err(kd, 0, "invalid address (%lx)", kva);
903 			return (-1);
904 		} else if (cc < len)
905 			_kvm_err(kd, kd->program, "short write");
906 		return (cc);
907 	} else {
908 		_kvm_err(kd, kd->program,
909 		    "kvm_write not implemented for dead kernels");
910 		return (-1);
911 	}
912 	/* NOTREACHED */
913 }
914 
915 static int
916 kvm_setfd(kvm_t *kd)
917 {
918 	if (kd->pmfd >= 0 && fcntl(kd->pmfd, F_SETFD, FD_CLOEXEC) < 0)
919 		return (-1);
920 	if (kd->vmfd >= 0 && fcntl(kd->vmfd, F_SETFD, FD_CLOEXEC) < 0)
921 		return (-1);
922 	if (kd->nlfd >= 0 && fcntl(kd->nlfd, F_SETFD, FD_CLOEXEC) < 0)
923 		return (-1);
924 	if (kd->swfd >= 0 && fcntl(kd->swfd, F_SETFD, FD_CLOEXEC) < 0)
925 		return (-1);
926 
927 	return (0);
928 }
929