Home | History | Annotate | Line # | Download | only in libkvm
kvm.c revision 1.70.4.1
      1 /*	$NetBSD: kvm.c,v 1.70.4.1 2003/06/16 13:41:19 grant Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1989, 1992, 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * This code is derived from software developed by the Computer Systems
      8  * Engineering group at Lawrence Berkeley Laboratory under DARPA contract
      9  * BG 91-66 and contributed to Berkeley.
     10  *
     11  * Redistribution and use in source and binary forms, with or without
     12  * modification, are permitted provided that the following conditions
     13  * are met:
     14  * 1. Redistributions of source code must retain the above copyright
     15  *    notice, this list of conditions and the following disclaimer.
     16  * 2. Redistributions in binary form must reproduce the above copyright
     17  *    notice, this list of conditions and the following disclaimer in the
     18  *    documentation and/or other materials provided with the distribution.
     19  * 3. All advertising materials mentioning features or use of this software
     20  *    must display the following acknowledgement:
     21  *	This product includes software developed by the University of
     22  *	California, Berkeley and its contributors.
     23  * 4. Neither the name of the University nor the names of its contributors
     24  *    may be used to endorse or promote products derived from this software
     25  *    without specific prior written permission.
     26  *
     27  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     28  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     29  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     30  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     31  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     32  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     33  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     34  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     35  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     36  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     37  * SUCH DAMAGE.
     38  */
     39 
     40 #include <sys/cdefs.h>
     41 #if defined(LIBC_SCCS) && !defined(lint)
     42 #if 0
     43 static char sccsid[] = "@(#)kvm.c	8.2 (Berkeley) 2/13/94";
     44 #else
     45 __RCSID("$NetBSD: kvm.c,v 1.70.4.1 2003/06/16 13:41:19 grant Exp $");
     46 #endif
     47 #endif /* LIBC_SCCS and not lint */
     48 
     49 #include <sys/param.h>
     50 #include <sys/user.h>
     51 #include <sys/proc.h>
     52 #include <sys/ioctl.h>
     53 #include <sys/stat.h>
     54 #include <sys/sysctl.h>
     55 
     56 #include <sys/core.h>
     57 #include <sys/exec_aout.h>
     58 #include <sys/kcore.h>
     59 
     60 #include <uvm/uvm_extern.h>
     61 
     62 #include <ctype.h>
     63 #include <db.h>
     64 #include <fcntl.h>
     65 #include <limits.h>
     66 #include <nlist.h>
     67 #include <paths.h>
     68 #include <stdio.h>
     69 #include <stdlib.h>
     70 #include <string.h>
     71 #include <unistd.h>
     72 #include <kvm.h>
     73 
     74 #include "kvm_private.h"
     75 
     76 static int	kvm_dbopen __P((kvm_t *));
     77 static int	_kvm_get_header __P((kvm_t *));
     78 static kvm_t	*_kvm_open __P((kvm_t *, const char *, const char *,
     79 		    const char *, int, char *));
     80 static int	clear_gap __P((kvm_t *, FILE *, int));
     81 static int	open_cloexec  __P((const char *, int, int));
     82 static off_t	Lseek __P((kvm_t *, int, off_t, int));
     83 static ssize_t	Pread __P((kvm_t *, int, void *, size_t, off_t));
     84 
     85 char *
     86 kvm_geterr(kd)
     87 	kvm_t *kd;
     88 {
     89 	return (kd->errbuf);
     90 }
     91 
     92 #if __STDC__
     93 #include <stdarg.h>
     94 #else
     95 #include <varargs.h>
     96 #endif
     97 
     98 /*
     99  * Report an error using printf style arguments.  "program" is kd->program
    100  * on hard errors, and 0 on soft errors, so that under sun error emulation,
    101  * only hard errors are printed out (otherwise, programs like gdb will
    102  * generate tons of error messages when trying to access bogus pointers).
    103  */
    104 void
    105 #if __STDC__
    106 _kvm_err(kvm_t *kd, const char *program, const char *fmt, ...)
    107 #else
    108 _kvm_err(kd, program, fmt, va_alist)
    109 	kvm_t *kd;
    110 	char *program, *fmt;
    111 	va_dcl
    112 #endif
    113 {
    114 	va_list ap;
    115 
    116 #ifdef __STDC__
    117 	va_start(ap, fmt);
    118 #else
    119 	va_start(ap);
    120 #endif
    121 	if (program != NULL) {
    122 		(void)fprintf(stderr, "%s: ", program);
    123 		(void)vfprintf(stderr, fmt, ap);
    124 		(void)fputc('\n', stderr);
    125 	} else
    126 		(void)vsnprintf(kd->errbuf,
    127 		    sizeof(kd->errbuf), fmt, ap);
    128 
    129 	va_end(ap);
    130 }
    131 
    132 void
    133 #if __STDC__
    134 _kvm_syserr(kvm_t *kd, const char *program, const char *fmt, ...)
    135 #else
    136 _kvm_syserr(kd, program, fmt, va_alist)
    137 	kvm_t *kd;
    138 	char *program, *fmt;
    139 	va_dcl
    140 #endif
    141 {
    142 	va_list ap;
    143 	size_t n;
    144 
    145 #if __STDC__
    146 	va_start(ap, fmt);
    147 #else
    148 	va_start(ap);
    149 #endif
    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(kd, n)
    167 	kvm_t *kd;
    168 	size_t n;
    169 {
    170 	void *p;
    171 
    172 	if ((p = malloc(n)) == NULL)
    173 		_kvm_err(kd, kd->program, "%s", strerror(errno));
    174 	return (p);
    175 }
    176 
    177 /*
    178  * Open a file setting the close on exec bit.
    179  */
    180 static int
    181 open_cloexec(fname, flags, mode)
    182 	const char *fname;
    183 	int flags, mode;
    184 {
    185 	int fd;
    186 
    187 	if ((fd = open(fname, flags, mode)) == -1)
    188 		return fd;
    189 	if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1)
    190 		goto error;
    191 
    192 	return fd;
    193 error:
    194 	flags = errno;
    195 	(void)close(fd);
    196 	errno = flags;
    197 	return -1;
    198 }
    199 
    200 /*
    201  * Wrapper around the lseek(2) system call; calls _kvm_syserr() for us
    202  * in the event of emergency.
    203  */
    204 static off_t
    205 Lseek(kd, fd, offset, whence)
    206 	kvm_t *kd;
    207 	int fd;
    208 	off_t offset;
    209 	int whence;
    210 {
    211 	off_t off;
    212 
    213 	errno = 0;
    214 
    215 	if ((off = lseek(fd, offset, whence)) == -1 && errno != 0) {
    216 		_kvm_syserr(kd, kd->program, "Lseek");
    217 		return ((off_t)-1);
    218 	}
    219 	return (off);
    220 }
    221 
    222 /*
    223  * Wrapper around the pread(2) system call; calls _kvm_syserr() for us
    224  * in the event of emergency.
    225  */
    226 static ssize_t
    227 Pread(kd, fd, buf, nbytes, offset)
    228 	kvm_t *kd;
    229 	int fd;
    230 	void *buf;
    231 	size_t nbytes;
    232 	off_t offset;
    233 {
    234 	ssize_t rv;
    235 
    236 	errno = 0;
    237 
    238 	if ((rv = pread(fd, buf, nbytes, offset)) != nbytes &&
    239 	    errno != 0)
    240 		_kvm_syserr(kd, kd->program, "Pread");
    241 	return (rv);
    242 }
    243 
    244 static kvm_t *
    245 _kvm_open(kd, uf, mf, sf, flag, errout)
    246 	kvm_t *kd;
    247 	const char *uf;
    248 	const char *mf;
    249 	const char *sf;
    250 	int flag;
    251 	char *errout;
    252 {
    253 	struct stat st;
    254 	int ufgiven;
    255 
    256 	kd->db = 0;
    257 	kd->pmfd = -1;
    258 	kd->vmfd = -1;
    259 	kd->swfd = -1;
    260 	kd->nlfd = -1;
    261 	kd->alive = KVM_ALIVE_DEAD;
    262 	kd->procbase = 0;
    263 	kd->procbase2 = 0;
    264 	kd->nbpg = getpagesize();
    265 	kd->swapspc = 0;
    266 	kd->argspc = 0;
    267 	kd->arglen = 0;
    268 	kd->argbuf = 0;
    269 	kd->argv = 0;
    270 	kd->vmst = 0;
    271 	kd->vm_page_buckets = 0;
    272 	kd->kcore_hdr = 0;
    273 	kd->cpu_dsize = 0;
    274 	kd->cpu_data = 0;
    275 	kd->dump_off = 0;
    276 
    277 	if (flag & KVM_NO_FILES) {
    278 		kd->alive = KVM_ALIVE_SYSCTL;
    279 		return(kd);
    280 	}
    281 
    282 	/*
    283 	 * Call the MD open hook.  This sets:
    284 	 *	usrstack, min_uva, max_uva
    285 	 */
    286 	if (_kvm_mdopen(kd)) {
    287 		_kvm_err(kd, kd->program, "md init failed");
    288 		goto failed;
    289 	}
    290 
    291 	ufgiven = (uf != NULL);
    292 	if (!ufgiven)
    293 		uf = _PATH_UNIX;
    294 	else if (strlen(uf) >= MAXPATHLEN) {
    295 		_kvm_err(kd, kd->program, "exec file name too long");
    296 		goto failed;
    297 	}
    298 	if (flag & ~O_RDWR) {
    299 		_kvm_err(kd, kd->program, "bad flags arg");
    300 		goto failed;
    301 	}
    302 	if (mf == 0)
    303 		mf = _PATH_MEM;
    304 	if (sf == 0)
    305 		sf = _PATH_DRUM;
    306 
    307 	if ((kd->pmfd = open_cloexec(mf, flag, 0)) < 0) {
    308 		_kvm_syserr(kd, kd->program, "%s", mf);
    309 		goto failed;
    310 	}
    311 	if (fstat(kd->pmfd, &st) < 0) {
    312 		_kvm_syserr(kd, kd->program, "%s", mf);
    313 		goto failed;
    314 	}
    315 	if (S_ISCHR(st.st_mode)) {
    316 		/*
    317 		 * If this is a character special device, then check that
    318 		 * it's /dev/mem.  If so, open kmem too.  (Maybe we should
    319 		 * make it work for either /dev/mem or /dev/kmem -- in either
    320 		 * case you're working with a live kernel.)
    321 		 */
    322 		if (strcmp(mf, _PATH_MEM) != 0) {	/* XXX */
    323 			_kvm_err(kd, kd->program,
    324 				 "%s: not physical memory device", mf);
    325 			goto failed;
    326 		}
    327 		if ((kd->vmfd = open_cloexec(_PATH_KMEM, flag, 0)) < 0) {
    328 			_kvm_syserr(kd, kd->program, "%s", _PATH_KMEM);
    329 			goto failed;
    330 		}
    331 		kd->alive = KVM_ALIVE_FILES;
    332 		if ((kd->swfd = open_cloexec(sf, flag, 0)) < 0) {
    333 			_kvm_syserr(kd, kd->program, "%s", sf);
    334 			goto failed;
    335 		}
    336 		/*
    337 		 * Open kvm nlist database.  We only try to use
    338 		 * the pre-built database if the namelist file name
    339 		 * pointer is NULL.  If the database cannot or should
    340 		 * not be opened, open the namelist argument so we
    341 		 * revert to slow nlist() calls.
    342 		 */
    343 		if ((ufgiven || kvm_dbopen(kd) < 0) &&
    344 		    (kd->nlfd = open_cloexec(uf, O_RDONLY, 0)) < 0) {
    345 			_kvm_syserr(kd, kd->program, "%s", uf);
    346 			goto failed;
    347 		}
    348 	} else {
    349 		/*
    350 		 * This is a crash dump.
    351 		 * Initialize the virtual address translation machinery,
    352 		 * but first setup the namelist fd.
    353 		 */
    354 		if ((kd->nlfd = open_cloexec(uf, O_RDONLY, 0)) < 0) {
    355 			_kvm_syserr(kd, kd->program, "%s", uf);
    356 			goto failed;
    357 		}
    358 
    359 		/*
    360 		 * If there is no valid core header, fail silently here.
    361 		 * The address translations however will fail without
    362 		 * header. Things can be made to run by calling
    363 		 * kvm_dump_mkheader() before doing any translation.
    364 		 */
    365 		if (_kvm_get_header(kd) == 0) {
    366 			if (_kvm_initvtop(kd) < 0)
    367 				goto failed;
    368 		}
    369 	}
    370 	return (kd);
    371 failed:
    372 	/*
    373 	 * Copy out the error if doing sane error semantics.
    374 	 */
    375 	if (errout != 0)
    376 		(void)strncpy(errout, kd->errbuf, _POSIX2_LINE_MAX - 1);
    377 	(void)kvm_close(kd);
    378 	return (0);
    379 }
    380 
    381 /*
    382  * The kernel dump file (from savecore) contains:
    383  *    kcore_hdr_t kcore_hdr;
    384  *    kcore_seg_t cpu_hdr;
    385  *    (opaque)    cpu_data; (size is cpu_hdr.c_size)
    386  *	  kcore_seg_t mem_hdr;
    387  *    (memory)    mem_data; (size is mem_hdr.c_size)
    388  *
    389  * Note: khdr is padded to khdr.c_hdrsize;
    390  * cpu_hdr and mem_hdr are padded to khdr.c_seghdrsize
    391  */
    392 static int
    393 _kvm_get_header(kd)
    394 	kvm_t	*kd;
    395 {
    396 	kcore_hdr_t	kcore_hdr;
    397 	kcore_seg_t	cpu_hdr;
    398 	kcore_seg_t	mem_hdr;
    399 	size_t		offset;
    400 	ssize_t		sz;
    401 
    402 	/*
    403 	 * Read the kcore_hdr_t
    404 	 */
    405 	sz = Pread(kd, kd->pmfd, &kcore_hdr, sizeof(kcore_hdr), (off_t)0);
    406 	if (sz != sizeof(kcore_hdr))
    407 		return (-1);
    408 
    409 	/*
    410 	 * Currently, we only support dump-files made by the current
    411 	 * architecture...
    412 	 */
    413 	if ((CORE_GETMAGIC(kcore_hdr) != KCORE_MAGIC) ||
    414 	    (CORE_GETMID(kcore_hdr) != MID_MACHINE))
    415 		return (-1);
    416 
    417 	/*
    418 	 * Currently, we only support exactly 2 segments: cpu-segment
    419 	 * and data-segment in exactly that order.
    420 	 */
    421 	if (kcore_hdr.c_nseg != 2)
    422 		return (-1);
    423 
    424 	/*
    425 	 * Save away the kcore_hdr.  All errors after this
    426 	 * should do a to "goto fail" to deallocate things.
    427 	 */
    428 	kd->kcore_hdr = _kvm_malloc(kd, sizeof(kcore_hdr));
    429 	memcpy(kd->kcore_hdr, &kcore_hdr, sizeof(kcore_hdr));
    430 	offset = kcore_hdr.c_hdrsize;
    431 
    432 	/*
    433 	 * Read the CPU segment header
    434 	 */
    435 	sz = Pread(kd, kd->pmfd, &cpu_hdr, sizeof(cpu_hdr), (off_t)offset);
    436 	if (sz != sizeof(cpu_hdr))
    437 		goto fail;
    438 	if ((CORE_GETMAGIC(cpu_hdr) != KCORESEG_MAGIC) ||
    439 	    (CORE_GETFLAG(cpu_hdr) != CORE_CPU))
    440 		goto fail;
    441 	offset += kcore_hdr.c_seghdrsize;
    442 
    443 	/*
    444 	 * Read the CPU segment DATA.
    445 	 */
    446 	kd->cpu_dsize = cpu_hdr.c_size;
    447 	kd->cpu_data = _kvm_malloc(kd, cpu_hdr.c_size);
    448 	if (kd->cpu_data == NULL)
    449 		goto fail;
    450 	sz = Pread(kd, kd->pmfd, kd->cpu_data, cpu_hdr.c_size, (off_t)offset);
    451 	if (sz != cpu_hdr.c_size)
    452 		goto fail;
    453 	offset += cpu_hdr.c_size;
    454 
    455 	/*
    456 	 * Read the next segment header: data segment
    457 	 */
    458 	sz = Pread(kd, kd->pmfd, &mem_hdr, sizeof(mem_hdr), (off_t)offset);
    459 	if (sz != sizeof(mem_hdr))
    460 		goto fail;
    461 	offset += kcore_hdr.c_seghdrsize;
    462 
    463 	if ((CORE_GETMAGIC(mem_hdr) != KCORESEG_MAGIC) ||
    464 	    (CORE_GETFLAG(mem_hdr) != CORE_DATA))
    465 		goto fail;
    466 
    467 	kd->dump_off = offset;
    468 	return (0);
    469 
    470 fail:
    471 	if (kd->kcore_hdr != NULL) {
    472 		free(kd->kcore_hdr);
    473 		kd->kcore_hdr = NULL;
    474 	}
    475 	if (kd->cpu_data != NULL) {
    476 		free(kd->cpu_data);
    477 		kd->cpu_data = NULL;
    478 		kd->cpu_dsize = 0;
    479 	}
    480 	return (-1);
    481 }
    482 
    483 /*
    484  * The format while on the dump device is: (new format)
    485  *	kcore_seg_t cpu_hdr;
    486  *	(opaque)    cpu_data; (size is cpu_hdr.c_size)
    487  *	kcore_seg_t mem_hdr;
    488  *	(memory)    mem_data; (size is mem_hdr.c_size)
    489  */
    490 int
    491 kvm_dump_mkheader(kd, dump_off)
    492 kvm_t	*kd;
    493 off_t	dump_off;
    494 {
    495 	kcore_seg_t	cpu_hdr;
    496 	size_t hdr_size;
    497 	ssize_t sz;
    498 
    499 	if (kd->kcore_hdr != NULL) {
    500 	    _kvm_err(kd, kd->program, "already has a dump header");
    501 	    return (-1);
    502 	}
    503 	if (ISALIVE(kd)) {
    504 		_kvm_err(kd, kd->program, "don't use on live kernel");
    505 		return (-1);
    506 	}
    507 
    508 	/*
    509 	 * Validate new format crash dump
    510 	 */
    511 	sz = Pread(kd, kd->pmfd, &cpu_hdr, sizeof(cpu_hdr), dump_off);
    512 	if (sz != sizeof(cpu_hdr))
    513 		return (-1);
    514 	if ((CORE_GETMAGIC(cpu_hdr) != KCORE_MAGIC)
    515 		|| (CORE_GETMID(cpu_hdr) != MID_MACHINE)) {
    516 		_kvm_err(kd, 0, "invalid magic in cpu_hdr");
    517 		return (0);
    518 	}
    519 	hdr_size = ALIGN(sizeof(cpu_hdr));
    520 
    521 	/*
    522 	 * Read the CPU segment.
    523 	 */
    524 	kd->cpu_dsize = cpu_hdr.c_size;
    525 	kd->cpu_data = _kvm_malloc(kd, kd->cpu_dsize);
    526 	if (kd->cpu_data == NULL)
    527 		goto fail;
    528 	sz = Pread(kd, kd->pmfd, kd->cpu_data, cpu_hdr.c_size,
    529 	    dump_off + hdr_size);
    530 	if (sz != cpu_hdr.c_size)
    531 		goto fail;
    532 	hdr_size += kd->cpu_dsize;
    533 
    534 	/*
    535 	 * Leave phys mem pointer at beginning of memory data
    536 	 */
    537 	kd->dump_off = dump_off + hdr_size;
    538 	if (Lseek(kd, kd->pmfd, kd->dump_off, SEEK_SET) == -1)
    539 		goto fail;
    540 
    541 	/*
    542 	 * Create a kcore_hdr.
    543 	 */
    544 	kd->kcore_hdr = _kvm_malloc(kd, sizeof(kcore_hdr_t));
    545 	if (kd->kcore_hdr == NULL)
    546 		goto fail;
    547 
    548 	kd->kcore_hdr->c_hdrsize    = ALIGN(sizeof(kcore_hdr_t));
    549 	kd->kcore_hdr->c_seghdrsize = ALIGN(sizeof(kcore_seg_t));
    550 	kd->kcore_hdr->c_nseg       = 2;
    551 	CORE_SETMAGIC(*(kd->kcore_hdr), KCORE_MAGIC, MID_MACHINE,0);
    552 
    553 	/*
    554 	 * Now that we have a valid header, enable translations.
    555 	 */
    556 	if (_kvm_initvtop(kd) == 0)
    557 		/* Success */
    558 		return (hdr_size);
    559 
    560 fail:
    561 	if (kd->kcore_hdr != NULL) {
    562 		free(kd->kcore_hdr);
    563 		kd->kcore_hdr = NULL;
    564 	}
    565 	if (kd->cpu_data != NULL) {
    566 		free(kd->cpu_data);
    567 		kd->cpu_data = NULL;
    568 		kd->cpu_dsize = 0;
    569 	}
    570 	return (-1);
    571 }
    572 
    573 static int
    574 clear_gap(kd, fp, size)
    575 kvm_t	*kd;
    576 FILE	*fp;
    577 int	size;
    578 {
    579 	if (size <= 0) /* XXX - < 0 should never happen */
    580 		return (0);
    581 	while (size-- > 0) {
    582 		if (fputc(0, fp) == EOF) {
    583 			_kvm_syserr(kd, kd->program, "clear_gap");
    584 			return (-1);
    585 		}
    586 	}
    587 	return (0);
    588 }
    589 
    590 /*
    591  * Write the dump header info to 'fp'. Note that we can't use fseek(3) here
    592  * because 'fp' might be a file pointer obtained by zopen().
    593  */
    594 int
    595 kvm_dump_wrtheader(kd, fp, dumpsize)
    596 kvm_t	*kd;
    597 FILE	*fp;
    598 int	dumpsize;
    599 {
    600 	kcore_seg_t	seghdr;
    601 	long		offset;
    602 	int		gap;
    603 
    604 	if (kd->kcore_hdr == NULL || kd->cpu_data == NULL) {
    605 		_kvm_err(kd, kd->program, "no valid dump header(s)");
    606 		return (-1);
    607 	}
    608 
    609 	/*
    610 	 * Write the generic header
    611 	 */
    612 	offset = 0;
    613 	if (fwrite((void*)kd->kcore_hdr, sizeof(kcore_hdr_t), 1, fp) == 0) {
    614 		_kvm_syserr(kd, kd->program, "kvm_dump_wrtheader");
    615 		return (-1);
    616 	}
    617 	offset += kd->kcore_hdr->c_hdrsize;
    618 	gap     = kd->kcore_hdr->c_hdrsize - sizeof(kcore_hdr_t);
    619 	if (clear_gap(kd, fp, gap) == -1)
    620 		return (-1);
    621 
    622 	/*
    623 	 * Write the cpu header
    624 	 */
    625 	CORE_SETMAGIC(seghdr, KCORESEG_MAGIC, 0, CORE_CPU);
    626 	seghdr.c_size = ALIGN(kd->cpu_dsize);
    627 	if (fwrite((void*)&seghdr, sizeof(seghdr), 1, fp) == 0) {
    628 		_kvm_syserr(kd, kd->program, "kvm_dump_wrtheader");
    629 		return (-1);
    630 	}
    631 	offset += kd->kcore_hdr->c_seghdrsize;
    632 	gap     = kd->kcore_hdr->c_seghdrsize - sizeof(seghdr);
    633 	if (clear_gap(kd, fp, gap) == -1)
    634 		return (-1);
    635 
    636 	if (fwrite((void*)kd->cpu_data, kd->cpu_dsize, 1, fp) == 0) {
    637 		_kvm_syserr(kd, kd->program, "kvm_dump_wrtheader");
    638 		return (-1);
    639 	}
    640 	offset += seghdr.c_size;
    641 	gap     = seghdr.c_size - kd->cpu_dsize;
    642 	if (clear_gap(kd, fp, gap) == -1)
    643 		return (-1);
    644 
    645 	/*
    646 	 * Write the actual dump data segment header
    647 	 */
    648 	CORE_SETMAGIC(seghdr, KCORESEG_MAGIC, 0, CORE_DATA);
    649 	seghdr.c_size = dumpsize;
    650 	if (fwrite((void*)&seghdr, sizeof(seghdr), 1, fp) == 0) {
    651 		_kvm_syserr(kd, kd->program, "kvm_dump_wrtheader");
    652 		return (-1);
    653 	}
    654 	offset += kd->kcore_hdr->c_seghdrsize;
    655 	gap     = kd->kcore_hdr->c_seghdrsize - sizeof(seghdr);
    656 	if (clear_gap(kd, fp, gap) == -1)
    657 		return (-1);
    658 
    659 	return (int)offset;
    660 }
    661 
    662 kvm_t *
    663 kvm_openfiles(uf, mf, sf, flag, errout)
    664 	const char *uf;
    665 	const char *mf;
    666 	const char *sf;
    667 	int flag;
    668 	char *errout;
    669 {
    670 	kvm_t *kd;
    671 
    672 	if ((kd = malloc(sizeof(*kd))) == NULL) {
    673 		(void)strncpy(errout, strerror(errno), _POSIX2_LINE_MAX - 1);
    674 		return (0);
    675 	}
    676 	kd->program = 0;
    677 	return (_kvm_open(kd, uf, mf, sf, flag, errout));
    678 }
    679 
    680 kvm_t *
    681 kvm_open(uf, mf, sf, flag, program)
    682 	const char *uf;
    683 	const char *mf;
    684 	const char *sf;
    685 	int flag;
    686 	const char *program;
    687 {
    688 	kvm_t *kd;
    689 
    690 	if ((kd = malloc(sizeof(*kd))) == NULL && program != NULL) {
    691 		(void)fprintf(stderr, "%s: %s\n", program, strerror(errno));
    692 		return (0);
    693 	}
    694 	kd->program = program;
    695 	return (_kvm_open(kd, uf, mf, sf, flag, NULL));
    696 }
    697 
    698 int
    699 kvm_close(kd)
    700 	kvm_t *kd;
    701 {
    702 	int error = 0;
    703 
    704 	if (kd->pmfd >= 0)
    705 		error |= close(kd->pmfd);
    706 	if (kd->vmfd >= 0)
    707 		error |= close(kd->vmfd);
    708 	if (kd->nlfd >= 0)
    709 		error |= close(kd->nlfd);
    710 	if (kd->swfd >= 0)
    711 		error |= close(kd->swfd);
    712 	if (kd->db != 0)
    713 		error |= (kd->db->close)(kd->db);
    714 	if (kd->vmst)
    715 		_kvm_freevtop(kd);
    716 	kd->cpu_dsize = 0;
    717 	if (kd->cpu_data != NULL)
    718 		free((void *)kd->cpu_data);
    719 	if (kd->kcore_hdr != NULL)
    720 		free((void *)kd->kcore_hdr);
    721 	if (kd->procbase != 0)
    722 		free((void *)kd->procbase);
    723 	if (kd->procbase2 != 0)
    724 		free((void *)kd->procbase2);
    725 	if (kd->swapspc != 0)
    726 		free((void *)kd->swapspc);
    727 	if (kd->argspc != 0)
    728 		free((void *)kd->argspc);
    729 	if (kd->argbuf != 0)
    730 		free((void *)kd->argbuf);
    731 	if (kd->argv != 0)
    732 		free((void *)kd->argv);
    733 	free((void *)kd);
    734 
    735 	return (0);
    736 }
    737 
    738 /*
    739  * Set up state necessary to do queries on the kernel namelist
    740  * data base.  If the data base is out-of-data/incompatible with
    741  * given executable, set up things so we revert to standard nlist call.
    742  * Only called for live kernels.  Return 0 on success, -1 on failure.
    743  */
    744 static int
    745 kvm_dbopen(kd)
    746 	kvm_t *kd;
    747 {
    748 	DBT rec;
    749 	size_t dbversionlen;
    750 	struct nlist nitem;
    751 	char dbversion[_POSIX2_LINE_MAX];
    752 	char kversion[_POSIX2_LINE_MAX];
    753 	int fd;
    754 
    755 	kd->db = dbopen(_PATH_KVMDB, O_RDONLY, 0, DB_HASH, NULL);
    756 	if (kd->db == 0)
    757 		return (-1);
    758 	if ((fd = (*kd->db->fd)(kd->db)) >= 0) {
    759 		if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) {
    760 		       (*kd->db->close)(kd->db);
    761 		       return (-1);
    762 		}
    763 	}
    764 	/*
    765 	 * read version out of database
    766 	 */
    767 	rec.data = VRS_KEY;
    768 	rec.size = sizeof(VRS_KEY) - 1;
    769 	if ((kd->db->get)(kd->db, (DBT *)&rec, (DBT *)&rec, 0))
    770 		goto close;
    771 	if (rec.data == 0 || rec.size > sizeof(dbversion))
    772 		goto close;
    773 
    774 	memcpy(dbversion, rec.data, rec.size);
    775 	dbversionlen = rec.size;
    776 	/*
    777 	 * Read version string from kernel memory.
    778 	 * Since we are dealing with a live kernel, we can call kvm_read()
    779 	 * at this point.
    780 	 */
    781 	rec.data = VRS_SYM;
    782 	rec.size = sizeof(VRS_SYM) - 1;
    783 	if ((kd->db->get)(kd->db, (DBT *)&rec, (DBT *)&rec, 0))
    784 		goto close;
    785 	if (rec.data == 0 || rec.size != sizeof(struct nlist))
    786 		goto close;
    787 	memcpy(&nitem, rec.data, sizeof(nitem));
    788 	if (kvm_read(kd, (u_long)nitem.n_value, kversion, dbversionlen) !=
    789 	    dbversionlen)
    790 		goto close;
    791 	/*
    792 	 * If they match, we win - otherwise clear out kd->db so
    793 	 * we revert to slow nlist().
    794 	 */
    795 	if (memcmp(dbversion, kversion, dbversionlen) == 0)
    796 		return (0);
    797 close:
    798 	(void)(kd->db->close)(kd->db);
    799 	kd->db = 0;
    800 
    801 	return (-1);
    802 }
    803 
    804 int
    805 kvm_nlist(kd, nl)
    806 	kvm_t *kd;
    807 	struct nlist *nl;
    808 {
    809 	struct nlist *p;
    810 	int nvalid, rv;
    811 
    812 	/*
    813 	 * If we can't use the data base, revert to the
    814 	 * slow library call.
    815 	 */
    816 	if (kd->db == 0) {
    817 		rv = __fdnlist(kd->nlfd, nl);
    818 		if (rv == -1)
    819 			_kvm_err(kd, 0, "bad namelist");
    820 		return (rv);
    821 	}
    822 
    823 	/*
    824 	 * We can use the kvm data base.  Go through each nlist entry
    825 	 * and look it up with a db query.
    826 	 */
    827 	nvalid = 0;
    828 	for (p = nl; p->n_name && p->n_name[0]; ++p) {
    829 		int len;
    830 		DBT rec;
    831 
    832 		if ((len = strlen(p->n_name)) > 4096) {
    833 			/* sanity */
    834 			_kvm_err(kd, kd->program, "symbol too large");
    835 			return (-1);
    836 		}
    837 		rec.data = (char *)p->n_name;
    838 		rec.size = len;
    839 
    840 		/*
    841 		 * Make sure that n_value = 0 when the symbol isn't found
    842 		 */
    843 		p->n_value = 0;
    844 
    845 		if ((kd->db->get)(kd->db, (DBT *)&rec, (DBT *)&rec, 0))
    846 			continue;
    847 		if (rec.data == 0 || rec.size != sizeof(struct nlist))
    848 			continue;
    849 		++nvalid;
    850 		/*
    851 		 * Avoid alignment issues.
    852 		 */
    853 		(void)memcpy(&p->n_type, &((struct nlist *)rec.data)->n_type,
    854 		      sizeof(p->n_type));
    855 		(void)memcpy(&p->n_value, &((struct nlist *)rec.data)->n_value,
    856 		      sizeof(p->n_value));
    857 	}
    858 	/*
    859 	 * Return the number of entries that weren't found.
    860 	 */
    861 	return ((p - nl) - nvalid);
    862 }
    863 
    864 int kvm_dump_inval(kd)
    865 kvm_t	*kd;
    866 {
    867 	struct nlist	nl[2];
    868 	u_long		pa, val;
    869 
    870 	if (ISALIVE(kd)) {
    871 		_kvm_err(kd, kd->program, "clearing dump on live kernel");
    872 		return (-1);
    873 	}
    874 	nl[0].n_name = "_dumpmag";
    875 	nl[1].n_name = NULL;
    876 
    877 	if (kvm_nlist(kd, nl) == -1) {
    878 		_kvm_err(kd, 0, "bad namelist");
    879 		return (-1);
    880 	}
    881 	if (_kvm_kvatop(kd, (u_long)nl[0].n_value, &pa) == 0)
    882 		return (-1);
    883 
    884 	errno = 0;
    885 	val = 0;
    886 	if (pwrite(kd->pmfd, (void *)&val, sizeof(val),
    887 	    _kvm_pa2off(kd, pa)) == -1) {
    888 		_kvm_syserr(kd, 0, "cannot invalidate dump - pwrite");
    889 		return (-1);
    890 	}
    891 	return (0);
    892 }
    893 
    894 ssize_t
    895 kvm_read(kd, kva, buf, len)
    896 	kvm_t *kd;
    897 	u_long kva;
    898 	void *buf;
    899 	size_t len;
    900 {
    901 	int cc;
    902 	void *cp;
    903 
    904 	if (ISKMEM(kd)) {
    905 		/*
    906 		 * We're using /dev/kmem.  Just read straight from the
    907 		 * device and let the active kernel do the address translation.
    908 		 */
    909 		errno = 0;
    910 		cc = pread(kd->vmfd, buf, len, (off_t)kva);
    911 		if (cc < 0) {
    912 			_kvm_syserr(kd, 0, "kvm_read");
    913 			return (-1);
    914 		} else if (cc < len)
    915 			_kvm_err(kd, kd->program, "short read");
    916 		return (cc);
    917 	} else if (ISSYSCTL(kd)) {
    918 		_kvm_err(kd, kd->program, "kvm_open called with KVM_NO_FILES, "
    919 		    "can't use kvm_read");
    920 		return (-1);
    921 	} else {
    922 		if ((kd->kcore_hdr == NULL) || (kd->cpu_data == NULL)) {
    923 			_kvm_err(kd, kd->program, "no valid dump header");
    924 			return (-1);
    925 		}
    926 		cp = buf;
    927 		while (len > 0) {
    928 			u_long	pa;
    929 			off_t	foff;
    930 
    931 			cc = _kvm_kvatop(kd, kva, &pa);
    932 			if (cc == 0)
    933 				return (-1);
    934 			if (cc > len)
    935 				cc = len;
    936 			foff = _kvm_pa2off(kd, pa);
    937 			errno = 0;
    938 			cc = pread(kd->pmfd, cp, (size_t)cc, foff);
    939 			if (cc < 0) {
    940 				_kvm_syserr(kd, kd->program, "kvm_read");
    941 				break;
    942 			}
    943 			/*
    944 			 * If kvm_kvatop returns a bogus value or our core
    945 			 * file is truncated, we might wind up seeking beyond
    946 			 * the end of the core file in which case the read will
    947 			 * return 0 (EOF).
    948 			 */
    949 			if (cc == 0)
    950 				break;
    951 			cp = (char *)cp + cc;
    952 			kva += cc;
    953 			len -= cc;
    954 		}
    955 		return ((char *)cp - (char *)buf);
    956 	}
    957 	/* NOTREACHED */
    958 }
    959 
    960 ssize_t
    961 kvm_write(kd, kva, buf, len)
    962 	kvm_t *kd;
    963 	u_long kva;
    964 	const void *buf;
    965 	size_t len;
    966 {
    967 	int cc;
    968 
    969 	if (ISKMEM(kd)) {
    970 		/*
    971 		 * Just like kvm_read, only we write.
    972 		 */
    973 		errno = 0;
    974 		cc = pwrite(kd->vmfd, buf, len, (off_t)kva);
    975 		if (cc < 0) {
    976 			_kvm_syserr(kd, 0, "kvm_write");
    977 			return (-1);
    978 		} else if (cc < len)
    979 			_kvm_err(kd, kd->program, "short write");
    980 		return (cc);
    981 	} else if (ISSYSCTL(kd)) {
    982 		_kvm_err(kd, kd->program, "kvm_open called with KVM_NO_FILES, "
    983 		    "can't use kvm_write");
    984 		return (-1);
    985 	} else {
    986 		_kvm_err(kd, kd->program,
    987 		    "kvm_write not implemented for dead kernels");
    988 		return (-1);
    989 	}
    990 	/* NOTREACHED */
    991 }
    992