kvm.c revision 291406
1/*-
2 * Copyright (c) 1989, 1992, 1993
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * This code is derived from software developed by the Computer Systems
6 * Engineering group at Lawrence Berkeley Laboratory under DARPA contract
7 * BG 91-66 and contributed to Berkeley.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 *    notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 *    notice, this list of conditions and the following disclaimer in the
16 *    documentation and/or other materials provided with the distribution.
17 * 4. Neither the name of the University nor the names of its contributors
18 *    may be used to endorse or promote products derived from this software
19 *    without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 */
33
34#include <sys/cdefs.h>
35__FBSDID("$FreeBSD: head/lib/libkvm/kvm.c 291406 2015-11-27 18:58:26Z jhb $");
36
37#if defined(LIBC_SCCS) && !defined(lint)
38#if 0
39static char sccsid[] = "@(#)kvm.c	8.2 (Berkeley) 2/13/94";
40#endif
41#endif /* LIBC_SCCS and not lint */
42
43#include <sys/param.h>
44#include <sys/fnv_hash.h>
45
46#define	_WANT_VNET
47
48#include <sys/user.h>
49#include <sys/linker.h>
50#include <sys/pcpu.h>
51#include <sys/stat.h>
52
53#include <net/vnet.h>
54
55#include <fcntl.h>
56#include <kvm.h>
57#include <limits.h>
58#include <paths.h>
59#include <stdint.h>
60#include <stdio.h>
61#include <stdlib.h>
62#include <string.h>
63#include <unistd.h>
64
65#include "kvm_private.h"
66
67SET_DECLARE(kvm_arch, struct kvm_arch);
68
69/* from src/lib/libc/gen/nlist.c */
70int __fdnlist(int, struct nlist *);
71
72static int
73kvm_fdnlist(kvm_t *kd, struct kvm_nlist *list)
74{
75	kvaddr_t addr;
76	int error, nfail;
77
78	if (kd->resolve_symbol == NULL) {
79		struct nlist *nl;
80		int count, i;
81
82		for (count = 0; list[count].n_name != NULL &&
83		     list[count].n_name[0] != '\0'; count++)
84			;
85		nl = calloc(count + 1, sizeof(*nl));
86		for (i = 0; i < count; i++)
87			nl[i].n_name = list[i].n_name;
88		nfail = __fdnlist(kd->nlfd, nl);
89		for (i = 0; i < count; i++) {
90			list[i].n_type = nl[i].n_type;
91			list[i].n_value = nl[i].n_value;
92		}
93		free(nl);
94		return (nfail);
95	}
96
97	nfail = 0;
98	while (list->n_name != NULL && list->n_name[0] != '\0') {
99		error = kd->resolve_symbol(list->n_name, &addr);
100		if (error != 0) {
101			nfail++;
102			list->n_value = 0;
103			list->n_type = 0;
104		} else {
105			list->n_value = addr;
106			list->n_type = N_DATA | N_EXT;
107		}
108		list++;
109	}
110	return (nfail);
111}
112
113char *
114kvm_geterr(kvm_t *kd)
115{
116	return (kd->errbuf);
117}
118
119#include <stdarg.h>
120
121/*
122 * Report an error using printf style arguments.  "program" is kd->program
123 * on hard errors, and 0 on soft errors, so that under sun error emulation,
124 * only hard errors are printed out (otherwise, programs like gdb will
125 * generate tons of error messages when trying to access bogus pointers).
126 */
127void
128_kvm_err(kvm_t *kd, const char *program, const char *fmt, ...)
129{
130	va_list ap;
131
132	va_start(ap, fmt);
133	if (program != NULL) {
134		(void)fprintf(stderr, "%s: ", program);
135		(void)vfprintf(stderr, fmt, ap);
136		(void)fputc('\n', stderr);
137	} else
138		(void)vsnprintf(kd->errbuf,
139		    sizeof(kd->errbuf), fmt, ap);
140
141	va_end(ap);
142}
143
144void
145_kvm_syserr(kvm_t *kd, const char *program, const char *fmt, ...)
146{
147	va_list ap;
148	int n;
149
150	va_start(ap, fmt);
151	if (program != NULL) {
152		(void)fprintf(stderr, "%s: ", program);
153		(void)vfprintf(stderr, fmt, ap);
154		(void)fprintf(stderr, ": %s\n", strerror(errno));
155	} else {
156		char *cp = kd->errbuf;
157
158		(void)vsnprintf(cp, sizeof(kd->errbuf), fmt, ap);
159		n = strlen(cp);
160		(void)snprintf(&cp[n], sizeof(kd->errbuf) - n, ": %s",
161		    strerror(errno));
162	}
163	va_end(ap);
164}
165
166void *
167_kvm_malloc(kvm_t *kd, size_t n)
168{
169	void *p;
170
171	if ((p = calloc(n, sizeof(char))) == NULL)
172		_kvm_err(kd, kd->program, "can't allocate %zu bytes: %s",
173			 n, strerror(errno));
174	return (p);
175}
176
177static int
178_kvm_read_kernel_ehdr(kvm_t *kd)
179{
180	Elf *elf;
181
182	if (elf_version(EV_CURRENT) == EV_NONE) {
183		_kvm_err(kd, kd->program, "Unsupported libelf");
184		return (-1);
185	}
186	elf = elf_begin(kd->nlfd, ELF_C_READ, NULL);
187	if (elf == NULL) {
188		_kvm_err(kd, kd->program, "%s", elf_errmsg(0));
189		return (-1);
190	}
191	if (elf_kind(elf) != ELF_K_ELF) {
192		_kvm_err(kd, kd->program, "kernel is not an ELF file");
193		return (-1);
194	}
195	if (gelf_getehdr(elf, &kd->nlehdr) == NULL) {
196		_kvm_err(kd, kd->program, "%s", elf_errmsg(0));
197		elf_end(elf);
198		return (-1);
199	}
200	elf_end(elf);
201
202	switch (kd->nlehdr.e_ident[EI_DATA]) {
203	case ELFDATA2LSB:
204	case ELFDATA2MSB:
205		return (0);
206	default:
207		_kvm_err(kd, kd->program,
208		    "unsupported ELF data encoding for kernel");
209		return (-1);
210	}
211}
212
213int
214_kvm_probe_elf_kernel(kvm_t *kd, int class, int machine)
215{
216
217	return (kd->nlehdr.e_ident[EI_CLASS] == class &&
218	    kd->nlehdr.e_type == ET_EXEC &&
219	    kd->nlehdr.e_machine == machine);
220}
221
222int
223_kvm_is_minidump(kvm_t *kd)
224{
225	char minihdr[8];
226
227	if (kd->rawdump)
228		return (0);
229	if (pread(kd->pmfd, &minihdr, 8, 0) == 8 &&
230	    memcmp(&minihdr, "minidump", 8) == 0)
231		return (1);
232	return (0);
233}
234
235/*
236 * The powerpc backend has a hack to strip a leading kerneldump
237 * header from the core before treating it as an ELF header.
238 *
239 * We can add that here if we can get a change to libelf to support
240 * an inital offset into the file.  Alternatively we could patch
241 * savecore to extract cores from a regular file instead.
242 */
243int
244_kvm_read_core_phdrs(kvm_t *kd, size_t *phnump, GElf_Phdr **phdrp)
245{
246	GElf_Ehdr ehdr;
247	GElf_Phdr *phdr;
248	Elf *elf;
249	size_t i, phnum;
250
251	elf = elf_begin(kd->pmfd, ELF_C_READ, NULL);
252	if (elf == NULL) {
253		_kvm_err(kd, kd->program, "%s", elf_errmsg(0));
254		return (-1);
255	}
256	if (elf_kind(elf) != ELF_K_ELF) {
257		_kvm_err(kd, kd->program, "invalid core");
258		goto bad;
259	}
260	if (gelf_getclass(elf) != kd->nlehdr.e_ident[EI_CLASS]) {
261		_kvm_err(kd, kd->program, "invalid core");
262		goto bad;
263	}
264	if (gelf_getehdr(elf, &ehdr) == NULL) {
265		_kvm_err(kd, kd->program, "%s", elf_errmsg(0));
266		goto bad;
267	}
268	if (ehdr.e_type != ET_CORE) {
269		_kvm_err(kd, kd->program, "invalid core");
270		goto bad;
271	}
272	if (ehdr.e_machine != kd->nlehdr.e_machine) {
273		_kvm_err(kd, kd->program, "invalid core");
274		goto bad;
275	}
276
277	if (elf_getphdrnum(elf, &phnum) == -1) {
278		_kvm_err(kd, kd->program, "%s", elf_errmsg(0));
279		goto bad;
280	}
281
282	phdr = calloc(phnum, sizeof(*phdr));
283	if (phdr == NULL) {
284		_kvm_err(kd, kd->program, "failed to allocate phdrs");
285		goto bad;
286	}
287
288	for (i = 0; i < phnum; i++) {
289		if (gelf_getphdr(elf, i, &phdr[i]) == NULL) {
290			_kvm_err(kd, kd->program, "%s", elf_errmsg(0));
291			goto bad;
292		}
293	}
294	elf_end(elf);
295	*phnump = phnum;
296	*phdrp = phdr;
297	return (0);
298
299bad:
300	elf_end(elf);
301	return (-1);
302}
303
304static void
305_kvm_hpt_insert(struct hpt *hpt, uint64_t pa, off_t off)
306{
307	struct hpte *hpte;
308	uint32_t fnv = FNV1_32_INIT;
309
310	fnv = fnv_32_buf(&pa, sizeof(pa), fnv);
311	fnv &= (HPT_SIZE - 1);
312	hpte = malloc(sizeof(*hpte));
313	hpte->pa = pa;
314	hpte->off = off;
315	hpte->next = hpt->hpt_head[fnv];
316	hpt->hpt_head[fnv] = hpte;
317}
318
319void
320_kvm_hpt_init(kvm_t *kd, struct hpt *hpt, void *base, size_t len, off_t off,
321    int page_size, int word_size)
322{
323	uint64_t bits, idx, pa;
324	uint64_t *base64;
325	uint32_t *base32;
326
327	base64 = base;
328	base32 = base;
329	for (idx = 0; idx < len / word_size; idx++) {
330		if (word_size == sizeof(uint64_t))
331			bits = _kvm64toh(kd, base64[idx]);
332		else
333			bits = _kvm32toh(kd, base32[idx]);
334		pa = idx * word_size * NBBY * page_size;
335		for (; bits != 0; bits >>= 1, pa += page_size) {
336			if ((bits & 1) == 0)
337				continue;
338			_kvm_hpt_insert(hpt, pa, off);
339			off += page_size;
340		}
341	}
342}
343
344off_t
345_kvm_hpt_find(struct hpt *hpt, uint64_t pa)
346{
347	struct hpte *hpte;
348	uint32_t fnv = FNV1_32_INIT;
349
350	fnv = fnv_32_buf(&pa, sizeof(pa), fnv);
351	fnv &= (HPT_SIZE - 1);
352	for (hpte = hpt->hpt_head[fnv]; hpte != NULL; hpte = hpte->next) {
353		if (pa == hpte->pa)
354			return (hpte->off);
355	}
356	return (-1);
357}
358
359void
360_kvm_hpt_free(struct hpt *hpt)
361{
362	struct hpte *hpte, *next;
363	int i;
364
365	for (i = 0; i < HPT_SIZE; i++) {
366		for (hpte = hpt->hpt_head[i]; hpte != NULL; hpte = next) {
367			next = hpte->next;
368			free(hpte);
369		}
370	}
371}
372
373static kvm_t *
374_kvm_open(kvm_t *kd, const char *uf, const char *mf, int flag, char *errout)
375{
376	struct kvm_arch **parch;
377	struct stat st;
378
379	kd->vmfd = -1;
380	kd->pmfd = -1;
381	kd->nlfd = -1;
382	kd->vmst = 0;
383	kd->procbase = 0;
384	kd->argspc = 0;
385	kd->argv = 0;
386
387	if (uf == 0)
388		uf = getbootfile();
389	else if (strlen(uf) >= MAXPATHLEN) {
390		_kvm_err(kd, kd->program, "exec file name too long");
391		goto failed;
392	}
393	if (flag & ~O_RDWR) {
394		_kvm_err(kd, kd->program, "bad flags arg");
395		goto failed;
396	}
397	if (mf == 0)
398		mf = _PATH_MEM;
399
400	if ((kd->pmfd = open(mf, flag | O_CLOEXEC, 0)) < 0) {
401		_kvm_syserr(kd, kd->program, "%s", mf);
402		goto failed;
403	}
404	if (fstat(kd->pmfd, &st) < 0) {
405		_kvm_syserr(kd, kd->program, "%s", mf);
406		goto failed;
407	}
408	if (S_ISREG(st.st_mode) && st.st_size <= 0) {
409		errno = EINVAL;
410		_kvm_syserr(kd, kd->program, "empty file");
411		goto failed;
412	}
413	if (S_ISCHR(st.st_mode)) {
414		/*
415		 * If this is a character special device, then check that
416		 * it's /dev/mem.  If so, open kmem too.  (Maybe we should
417		 * make it work for either /dev/mem or /dev/kmem -- in either
418		 * case you're working with a live kernel.)
419		 */
420		if (strcmp(mf, _PATH_DEVNULL) == 0) {
421			kd->vmfd = open(_PATH_DEVNULL, O_RDONLY | O_CLOEXEC);
422			return (kd);
423		} else if (strcmp(mf, _PATH_MEM) == 0) {
424			if ((kd->vmfd = open(_PATH_KMEM, flag | O_CLOEXEC)) <
425			    0) {
426				_kvm_syserr(kd, kd->program, "%s", _PATH_KMEM);
427				goto failed;
428			}
429			return (kd);
430		}
431	}
432	/*
433	 * This is a crash dump.
434	 * Open the namelist fd and determine the architecture.
435	 */
436	if ((kd->nlfd = open(uf, O_RDONLY | O_CLOEXEC, 0)) < 0) {
437		_kvm_syserr(kd, kd->program, "%s", uf);
438		goto failed;
439	}
440	if (_kvm_read_kernel_ehdr(kd) < 0)
441		goto failed;
442	if (strncmp(mf, _PATH_FWMEM, strlen(_PATH_FWMEM)) == 0)
443		kd->rawdump = 1;
444	SET_FOREACH(parch, kvm_arch) {
445		if ((*parch)->ka_probe(kd)) {
446			kd->arch = *parch;
447			break;
448		}
449	}
450	if (kd->arch == NULL) {
451		_kvm_err(kd, kd->program, "unsupported architecture");
452		goto failed;
453	}
454
455	/*
456	 * Non-native kernels require a symbol resolver.
457	 */
458	if (!kd->arch->ka_native(kd) && kd->resolve_symbol == NULL) {
459		_kvm_err(kd, kd->program,
460		    "non-native kernel requires a symbol resolver");
461		goto failed;
462	}
463
464	/*
465	 * Initialize the virtual address translation machinery.
466	 */
467	if (kd->arch->ka_initvtop(kd) < 0)
468		goto failed;
469	return (kd);
470failed:
471	/*
472	 * Copy out the error if doing sane error semantics.
473	 */
474	if (errout != 0)
475		strlcpy(errout, kd->errbuf, _POSIX2_LINE_MAX);
476	(void)kvm_close(kd);
477	return (0);
478}
479
480kvm_t *
481kvm_openfiles(const char *uf, const char *mf, const char *sf __unused, int flag,
482    char *errout)
483{
484	kvm_t *kd;
485
486	if ((kd = calloc(1, sizeof(*kd))) == NULL) {
487		(void)strlcpy(errout, strerror(errno), _POSIX2_LINE_MAX);
488		return (0);
489	}
490	return (_kvm_open(kd, uf, mf, flag, errout));
491}
492
493kvm_t *
494kvm_open(const char *uf, const char *mf, const char *sf __unused, int flag,
495    const char *errstr)
496{
497	kvm_t *kd;
498
499	if ((kd = calloc(1, sizeof(*kd))) == NULL) {
500		if (errstr != NULL)
501			(void)fprintf(stderr, "%s: %s\n",
502				      errstr, strerror(errno));
503		return (0);
504	}
505	kd->program = errstr;
506	return (_kvm_open(kd, uf, mf, flag, NULL));
507}
508
509kvm_t *
510kvm_open2(const char *uf, const char *mf, int flag, char *errout,
511    int (*resolver)(const char *, kvaddr_t *))
512{
513	kvm_t *kd;
514
515	if ((kd = calloc(1, sizeof(*kd))) == NULL) {
516		(void)strlcpy(errout, strerror(errno), _POSIX2_LINE_MAX);
517		return (0);
518	}
519	kd->resolve_symbol = resolver;
520	return (_kvm_open(kd, uf, mf, flag, errout));
521}
522
523int
524kvm_close(kvm_t *kd)
525{
526	int error = 0;
527
528	if (kd->vmst != NULL)
529		kd->arch->ka_freevtop(kd);
530	if (kd->pmfd >= 0)
531		error |= close(kd->pmfd);
532	if (kd->vmfd >= 0)
533		error |= close(kd->vmfd);
534	if (kd->nlfd >= 0)
535		error |= close(kd->nlfd);
536	if (kd->procbase != 0)
537		free((void *)kd->procbase);
538	if (kd->argbuf != 0)
539		free((void *) kd->argbuf);
540	if (kd->argspc != 0)
541		free((void *) kd->argspc);
542	if (kd->argv != 0)
543		free((void *)kd->argv);
544	free((void *)kd);
545
546	return (0);
547}
548
549/*
550 * Walk the list of unresolved symbols, generate a new list and prefix the
551 * symbol names, try again, and merge back what we could resolve.
552 */
553static int
554kvm_fdnlist_prefix(kvm_t *kd, struct kvm_nlist *nl, int missing,
555    const char *prefix, kvaddr_t (*validate_fn)(kvm_t *, kvaddr_t))
556{
557	struct kvm_nlist *n, *np, *p;
558	char *cp, *ce;
559	const char *ccp;
560	size_t len;
561	int slen, unresolved;
562
563	/*
564	 * Calculate the space we need to malloc for nlist and names.
565	 * We are going to store the name twice for later lookups: once
566	 * with the prefix and once the unmodified name delmited by \0.
567	 */
568	len = 0;
569	unresolved = 0;
570	for (p = nl; p->n_name && p->n_name[0]; ++p) {
571		if (p->n_type != N_UNDF)
572			continue;
573		len += sizeof(struct kvm_nlist) + strlen(prefix) +
574		    2 * (strlen(p->n_name) + 1);
575		unresolved++;
576	}
577	if (unresolved == 0)
578		return (unresolved);
579	/* Add space for the terminating nlist entry. */
580	len += sizeof(struct kvm_nlist);
581	unresolved++;
582
583	/* Alloc one chunk for (nlist, [names]) and setup pointers. */
584	n = np = malloc(len);
585	bzero(n, len);
586	if (n == NULL)
587		return (missing);
588	cp = ce = (char *)np;
589	cp += unresolved * sizeof(struct kvm_nlist);
590	ce += len;
591
592	/* Generate shortened nlist with special prefix. */
593	unresolved = 0;
594	for (p = nl; p->n_name && p->n_name[0]; ++p) {
595		if (p->n_type != N_UNDF)
596			continue;
597		*np = *p;
598		/* Save the new\0orig. name so we can later match it again. */
599		slen = snprintf(cp, ce - cp, "%s%s%c%s", prefix,
600		    (prefix[0] != '\0' && p->n_name[0] == '_') ?
601			(p->n_name + 1) : p->n_name, '\0', p->n_name);
602		if (slen < 0 || slen >= ce - cp)
603			continue;
604		np->n_name = cp;
605		cp += slen + 1;
606		np++;
607		unresolved++;
608	}
609
610	/* Do lookup on the reduced list. */
611	np = n;
612	unresolved = kvm_fdnlist(kd, np);
613
614	/* Check if we could resolve further symbols and update the list. */
615	if (unresolved >= 0 && unresolved < missing) {
616		/* Find the first freshly resolved entry. */
617		for (; np->n_name && np->n_name[0]; np++)
618			if (np->n_type != N_UNDF)
619				break;
620		/*
621		 * The lists are both in the same order,
622		 * so we can walk them in parallel.
623		 */
624		for (p = nl; np->n_name && np->n_name[0] &&
625		    p->n_name && p->n_name[0]; ++p) {
626			if (p->n_type != N_UNDF)
627				continue;
628			/* Skip expanded name and compare to orig. one. */
629			ccp = np->n_name + strlen(np->n_name) + 1;
630			if (strcmp(ccp, p->n_name) != 0)
631				continue;
632			/* Update nlist with new, translated results. */
633			p->n_type = np->n_type;
634			if (validate_fn)
635				p->n_value = (*validate_fn)(kd, np->n_value);
636			else
637				p->n_value = np->n_value;
638			missing--;
639			/* Find next freshly resolved entry. */
640			for (np++; np->n_name && np->n_name[0]; np++)
641				if (np->n_type != N_UNDF)
642					break;
643		}
644	}
645	/* We could assert missing = unresolved here. */
646
647	free(n);
648	return (unresolved);
649}
650
651int
652_kvm_nlist(kvm_t *kd, struct kvm_nlist *nl, int initialize)
653{
654	struct kvm_nlist *p;
655	int nvalid;
656	struct kld_sym_lookup lookup;
657	int error;
658	const char *prefix = "";
659	char symname[1024]; /* XXX-BZ symbol name length limit? */
660	int tried_vnet, tried_dpcpu;
661
662	/*
663	 * If we can't use the kld symbol lookup, revert to the
664	 * slow library call.
665	 */
666	if (!ISALIVE(kd)) {
667		error = kvm_fdnlist(kd, nl);
668		if (error <= 0)			/* Hard error or success. */
669			return (error);
670
671		if (_kvm_vnet_initialized(kd, initialize))
672			error = kvm_fdnlist_prefix(kd, nl, error,
673			    VNET_SYMPREFIX, _kvm_vnet_validaddr);
674
675		if (error > 0 && _kvm_dpcpu_initialized(kd, initialize))
676			error = kvm_fdnlist_prefix(kd, nl, error,
677			    DPCPU_SYMPREFIX, _kvm_dpcpu_validaddr);
678
679		return (error);
680	}
681
682	/*
683	 * We can use the kld lookup syscall.  Go through each nlist entry
684	 * and look it up with a kldsym(2) syscall.
685	 */
686	nvalid = 0;
687	tried_vnet = 0;
688	tried_dpcpu = 0;
689again:
690	for (p = nl; p->n_name && p->n_name[0]; ++p) {
691		if (p->n_type != N_UNDF)
692			continue;
693
694		lookup.version = sizeof(lookup);
695		lookup.symvalue = 0;
696		lookup.symsize = 0;
697
698		error = snprintf(symname, sizeof(symname), "%s%s", prefix,
699		    (prefix[0] != '\0' && p->n_name[0] == '_') ?
700			(p->n_name + 1) : p->n_name);
701		if (error < 0 || error >= (int)sizeof(symname))
702			continue;
703		lookup.symname = symname;
704		if (lookup.symname[0] == '_')
705			lookup.symname++;
706
707		if (kldsym(0, KLDSYM_LOOKUP, &lookup) != -1) {
708			p->n_type = N_TEXT;
709			if (_kvm_vnet_initialized(kd, initialize) &&
710			    strcmp(prefix, VNET_SYMPREFIX) == 0)
711				p->n_value =
712				    _kvm_vnet_validaddr(kd, lookup.symvalue);
713			else if (_kvm_dpcpu_initialized(kd, initialize) &&
714			    strcmp(prefix, DPCPU_SYMPREFIX) == 0)
715				p->n_value =
716				    _kvm_dpcpu_validaddr(kd, lookup.symvalue);
717			else
718				p->n_value = lookup.symvalue;
719			++nvalid;
720			/* lookup.symsize */
721		}
722	}
723
724	/*
725	 * Check the number of entries that weren't found. If they exist,
726	 * try again with a prefix for virtualized or DPCPU symbol names.
727	 */
728	error = ((p - nl) - nvalid);
729	if (error && _kvm_vnet_initialized(kd, initialize) && !tried_vnet) {
730		tried_vnet = 1;
731		prefix = VNET_SYMPREFIX;
732		goto again;
733	}
734	if (error && _kvm_dpcpu_initialized(kd, initialize) && !tried_dpcpu) {
735		tried_dpcpu = 1;
736		prefix = DPCPU_SYMPREFIX;
737		goto again;
738	}
739
740	/*
741	 * Return the number of entries that weren't found. If they exist,
742	 * also fill internal error buffer.
743	 */
744	error = ((p - nl) - nvalid);
745	if (error)
746		_kvm_syserr(kd, kd->program, "kvm_nlist");
747	return (error);
748}
749
750int
751kvm_nlist2(kvm_t *kd, struct kvm_nlist *nl)
752{
753
754	/*
755	 * If called via the public interface, permit intialization of
756	 * further virtualized modules on demand.
757	 */
758	return (_kvm_nlist(kd, nl, 1));
759}
760
761int
762kvm_nlist(kvm_t *kd, struct nlist *nl)
763{
764	struct kvm_nlist *kl;
765	int count, i, nfail;
766
767	/*
768	 * Avoid reporting truncated addresses by failing for non-native
769	 * cores.
770	 */
771	if (!kvm_native(kd)) {
772		_kvm_err(kd, kd->program, "kvm_nlist of non-native vmcore");
773		return (-1);
774	}
775
776	for (count = 0; nl[count].n_name != NULL && nl[count].n_name[0] != '\0';
777	     count++)
778		;
779	if (count == 0)
780		return (0);
781	kl = calloc(count + 1, sizeof(*kl));
782	for (i = 0; i < count; i++)
783		kl[i].n_name = nl[i].n_name;
784	nfail = kvm_nlist2(kd, kl);
785	for (i = 0; i < count; i++) {
786		nl[i].n_type = kl[i].n_type;
787		nl[i].n_other = 0;
788		nl[i].n_desc = 0;
789		nl[i].n_value = kl[i].n_value;
790	}
791	return (nfail);
792}
793
794ssize_t
795kvm_read(kvm_t *kd, u_long kva, void *buf, size_t len)
796{
797
798	return (kvm_read2(kd, kva, buf, len));
799}
800
801ssize_t
802kvm_read2(kvm_t *kd, kvaddr_t kva, void *buf, size_t len)
803{
804	int cc;
805	ssize_t cr;
806	off_t pa;
807	char *cp;
808
809	if (ISALIVE(kd)) {
810		/*
811		 * We're using /dev/kmem.  Just read straight from the
812		 * device and let the active kernel do the address translation.
813		 */
814		errno = 0;
815		if (lseek(kd->vmfd, (off_t)kva, 0) == -1 && errno != 0) {
816			_kvm_err(kd, 0, "invalid address (0x%jx)",
817			    (uintmax_t)kva);
818			return (-1);
819		}
820		cr = read(kd->vmfd, buf, len);
821		if (cr < 0) {
822			_kvm_syserr(kd, 0, "kvm_read");
823			return (-1);
824		} else if (cr < (ssize_t)len)
825			_kvm_err(kd, kd->program, "short read");
826		return (cr);
827	}
828
829	cp = buf;
830	while (len > 0) {
831		cc = kd->arch->ka_kvatop(kd, kva, &pa);
832		if (cc == 0)
833			return (-1);
834		if (cc > (ssize_t)len)
835			cc = len;
836		errno = 0;
837		if (lseek(kd->pmfd, pa, 0) == -1 && errno != 0) {
838			_kvm_syserr(kd, 0, _PATH_MEM);
839			break;
840		}
841		cr = read(kd->pmfd, cp, cc);
842		if (cr < 0) {
843			_kvm_syserr(kd, kd->program, "kvm_read");
844			break;
845		}
846		/*
847		 * If ka_kvatop returns a bogus value or our core file is
848		 * truncated, we might wind up seeking beyond the end of the
849		 * core file in which case the read will return 0 (EOF).
850		 */
851		if (cr == 0)
852			break;
853		cp += cr;
854		kva += cr;
855		len -= cr;
856	}
857
858	return (cp - (char *)buf);
859}
860
861ssize_t
862kvm_write(kvm_t *kd, u_long kva, const void *buf, size_t len)
863{
864	int cc;
865
866	if (ISALIVE(kd)) {
867		/*
868		 * Just like kvm_read, only we write.
869		 */
870		errno = 0;
871		if (lseek(kd->vmfd, (off_t)kva, 0) == -1 && errno != 0) {
872			_kvm_err(kd, 0, "invalid address (%lx)", kva);
873			return (-1);
874		}
875		cc = write(kd->vmfd, buf, len);
876		if (cc < 0) {
877			_kvm_syserr(kd, 0, "kvm_write");
878			return (-1);
879		} else if ((size_t)cc < len)
880			_kvm_err(kd, kd->program, "short write");
881		return (cc);
882	} else {
883		_kvm_err(kd, kd->program,
884		    "kvm_write not implemented for dead kernels");
885		return (-1);
886	}
887	/* NOTREACHED */
888}
889
890int
891kvm_native(kvm_t *kd)
892{
893
894	if (ISALIVE(kd))
895		return (1);
896	return (kd->arch->ka_native(kd));
897}
898