xref: /netbsd-src/lib/libkvm/kvm.c (revision 001c68bd94f75ce9270b69227c4199fbf34ee396)
1 /*	$NetBSD: kvm.c,v 1.80 2003/05/11 13:37:34 ragge 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.80 2003/05/11 13:37:34 ragge Exp $");
46 #endif
47 #endif /* LIBC_SCCS and not lint */
48 
49 #include <sys/param.h>
50 #include <sys/user.h>
51 #include <sys/lwp.h>
52 #include <sys/proc.h>
53 #include <sys/ioctl.h>
54 #include <sys/stat.h>
55 #include <sys/sysctl.h>
56 
57 #include <sys/core.h>
58 #include <sys/exec_aout.h>
59 #include <sys/kcore.h>
60 #include <sys/ksyms.h>
61 
62 #include <uvm/uvm_extern.h>
63 
64 #include <machine/cpu.h>
65 
66 #include <ctype.h>
67 #include <fcntl.h>
68 #include <limits.h>
69 #include <nlist.h>
70 #include <paths.h>
71 #include <stdarg.h>
72 #include <stdio.h>
73 #include <stdlib.h>
74 #include <string.h>
75 #include <unistd.h>
76 #include <kvm.h>
77 
78 #include "kvm_private.h"
79 
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->pmfd = -1;
232 	kd->vmfd = -1;
233 	kd->swfd = -1;
234 	kd->nlfd = -1;
235 	kd->alive = KVM_ALIVE_DEAD;
236 	kd->procbase = 0;
237 	kd->procbase2 = 0;
238 	kd->lwpbase = 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 the kernel namelist.  If /dev/ksyms doesn't
335 		 * exist, open the current kernel.
336 		 */
337 		if (ufgiven == 0)
338 			kd->nlfd = open_cloexec(_PATH_KSYMS, O_RDONLY, 0);
339 		if (kd->nlfd < 0) {
340 			if ((kd->nlfd = open_cloexec(uf, O_RDONLY, 0)) < 0) {
341 				_kvm_syserr(kd, kd->program, "%s", uf);
342 				goto failed;
343 			}
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->vmst)
710 		_kvm_freevtop(kd);
711 	kd->cpu_dsize = 0;
712 	if (kd->cpu_data != NULL)
713 		free((void *)kd->cpu_data);
714 	if (kd->kcore_hdr != NULL)
715 		free((void *)kd->kcore_hdr);
716 	if (kd->procbase != 0)
717 		free((void *)kd->procbase);
718 	if (kd->procbase2 != 0)
719 		free((void *)kd->procbase2);
720 	if (kd->lwpbase != 0)
721 		free((void *)kd->lwpbase);
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 int
736 kvm_nlist(kd, nl)
737 	kvm_t *kd;
738 	struct nlist *nl;
739 {
740 	int rv;
741 
742 	/*
743 	 * Call the nlist(3) routines to retrieve the given namelist.
744 	 */
745 	rv = __fdnlist(kd->nlfd, nl);
746 	if (rv == -1)
747 		_kvm_err(kd, 0, "bad namelist");
748 	return (rv);
749 }
750 
751 int kvm_dump_inval(kd)
752 kvm_t	*kd;
753 {
754 	struct nlist	nl[2];
755 	u_long		pa, val;
756 
757 	if (ISALIVE(kd)) {
758 		_kvm_err(kd, kd->program, "clearing dump on live kernel");
759 		return (-1);
760 	}
761 	nl[0].n_name = "_dumpmag";
762 	nl[1].n_name = NULL;
763 
764 	if (kvm_nlist(kd, nl) == -1) {
765 		_kvm_err(kd, 0, "bad namelist");
766 		return (-1);
767 	}
768 	if (_kvm_kvatop(kd, (u_long)nl[0].n_value, &pa) == 0)
769 		return (-1);
770 
771 	errno = 0;
772 	val = 0;
773 	if (pwrite(kd->pmfd, (void *)&val, sizeof(val),
774 	    _kvm_pa2off(kd, pa)) == -1) {
775 		_kvm_syserr(kd, 0, "cannot invalidate dump - pwrite");
776 		return (-1);
777 	}
778 	return (0);
779 }
780 
781 ssize_t
782 kvm_read(kd, kva, buf, len)
783 	kvm_t *kd;
784 	u_long kva;
785 	void *buf;
786 	size_t len;
787 {
788 	int cc;
789 	void *cp;
790 
791 	if (ISKMEM(kd)) {
792 		/*
793 		 * We're using /dev/kmem.  Just read straight from the
794 		 * device and let the active kernel do the address translation.
795 		 */
796 		errno = 0;
797 		cc = pread(kd->vmfd, buf, len, (off_t)kva);
798 		if (cc < 0) {
799 			_kvm_syserr(kd, 0, "kvm_read");
800 			return (-1);
801 		} else if (cc < len)
802 			_kvm_err(kd, kd->program, "short read");
803 		return (cc);
804 	} else if (ISSYSCTL(kd)) {
805 		_kvm_err(kd, kd->program, "kvm_open called with KVM_NO_FILES, "
806 		    "can't use kvm_read");
807 		return (-1);
808 	} else {
809 		if ((kd->kcore_hdr == NULL) || (kd->cpu_data == NULL)) {
810 			_kvm_err(kd, kd->program, "no valid dump header");
811 			return (-1);
812 		}
813 		cp = buf;
814 		while (len > 0) {
815 			u_long	pa;
816 			off_t	foff;
817 
818 			cc = _kvm_kvatop(kd, kva, &pa);
819 			if (cc == 0)
820 				return (-1);
821 			if (cc > len)
822 				cc = len;
823 			foff = _kvm_pa2off(kd, pa);
824 			errno = 0;
825 			cc = pread(kd->pmfd, cp, (size_t)cc, foff);
826 			if (cc < 0) {
827 				_kvm_syserr(kd, kd->program, "kvm_read");
828 				break;
829 			}
830 			/*
831 			 * If kvm_kvatop returns a bogus value or our core
832 			 * file is truncated, we might wind up seeking beyond
833 			 * the end of the core file in which case the read will
834 			 * return 0 (EOF).
835 			 */
836 			if (cc == 0)
837 				break;
838 			cp = (char *)cp + cc;
839 			kva += cc;
840 			len -= cc;
841 		}
842 		return ((char *)cp - (char *)buf);
843 	}
844 	/* NOTREACHED */
845 }
846 
847 ssize_t
848 kvm_write(kd, kva, buf, len)
849 	kvm_t *kd;
850 	u_long kva;
851 	const void *buf;
852 	size_t len;
853 {
854 	int cc;
855 
856 	if (ISKMEM(kd)) {
857 		/*
858 		 * Just like kvm_read, only we write.
859 		 */
860 		errno = 0;
861 		cc = pwrite(kd->vmfd, buf, len, (off_t)kva);
862 		if (cc < 0) {
863 			_kvm_syserr(kd, 0, "kvm_write");
864 			return (-1);
865 		} else if (cc < len)
866 			_kvm_err(kd, kd->program, "short write");
867 		return (cc);
868 	} else if (ISSYSCTL(kd)) {
869 		_kvm_err(kd, kd->program, "kvm_open called with KVM_NO_FILES, "
870 		    "can't use kvm_write");
871 		return (-1);
872 	} else {
873 		_kvm_err(kd, kd->program,
874 		    "kvm_write not implemented for dead kernels");
875 		return (-1);
876 	}
877 	/* NOTREACHED */
878 }
879