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