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