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