xref: /freebsd/lib/libkvm/kvm.c (revision 595e514d0df2bac5b813d35f83e32875dbf16a83)
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 
45 #define	_WANT_VNET
46 
47 #include <sys/user.h>
48 #include <sys/proc.h>
49 #include <sys/ioctl.h>
50 #include <sys/stat.h>
51 #include <sys/sysctl.h>
52 #include <sys/linker.h>
53 #include <sys/pcpu.h>
54 
55 #include <net/vnet.h>
56 
57 #include <vm/vm.h>
58 #include <vm/vm_param.h>
59 
60 #include <machine/vmparam.h>
61 
62 #include <ctype.h>
63 #include <fcntl.h>
64 #include <kvm.h>
65 #include <limits.h>
66 #include <nlist.h>
67 #include <paths.h>
68 #include <stdio.h>
69 #include <stdlib.h>
70 #include <string.h>
71 #include <strings.h>
72 #include <unistd.h>
73 
74 #include "kvm_private.h"
75 
76 /* from src/lib/libc/gen/nlist.c */
77 int __fdnlist(int, struct nlist *);
78 
79 char *
80 kvm_geterr(kvm_t *kd)
81 {
82 	return (kd->errbuf);
83 }
84 
85 #include <stdarg.h>
86 
87 /*
88  * Report an error using printf style arguments.  "program" is kd->program
89  * on hard errors, and 0 on soft errors, so that under sun error emulation,
90  * only hard errors are printed out (otherwise, programs like gdb will
91  * generate tons of error messages when trying to access bogus pointers).
92  */
93 void
94 _kvm_err(kvm_t *kd, const char *program, const char *fmt, ...)
95 {
96 	va_list ap;
97 
98 	va_start(ap, fmt);
99 	if (program != NULL) {
100 		(void)fprintf(stderr, "%s: ", program);
101 		(void)vfprintf(stderr, fmt, ap);
102 		(void)fputc('\n', stderr);
103 	} else
104 		(void)vsnprintf(kd->errbuf,
105 		    sizeof(kd->errbuf), fmt, ap);
106 
107 	va_end(ap);
108 }
109 
110 void
111 _kvm_syserr(kvm_t *kd, const char *program, const char *fmt, ...)
112 {
113 	va_list ap;
114 	int n;
115 
116 	va_start(ap, fmt);
117 	if (program != NULL) {
118 		(void)fprintf(stderr, "%s: ", program);
119 		(void)vfprintf(stderr, fmt, ap);
120 		(void)fprintf(stderr, ": %s\n", strerror(errno));
121 	} else {
122 		char *cp = kd->errbuf;
123 
124 		(void)vsnprintf(cp, sizeof(kd->errbuf), fmt, ap);
125 		n = strlen(cp);
126 		(void)snprintf(&cp[n], sizeof(kd->errbuf) - n, ": %s",
127 		    strerror(errno));
128 	}
129 	va_end(ap);
130 }
131 
132 void *
133 _kvm_malloc(kvm_t *kd, size_t n)
134 {
135 	void *p;
136 
137 	if ((p = calloc(n, sizeof(char))) == NULL)
138 		_kvm_err(kd, kd->program, "can't allocate %zu bytes: %s",
139 			 n, strerror(errno));
140 	return (p);
141 }
142 
143 static kvm_t *
144 _kvm_open(kvm_t *kd, const char *uf, const char *mf, int flag, char *errout)
145 {
146 	struct stat st;
147 
148 	kd->vmfd = -1;
149 	kd->pmfd = -1;
150 	kd->nlfd = -1;
151 	kd->vmst = 0;
152 	kd->procbase = 0;
153 	kd->argspc = 0;
154 	kd->argv = 0;
155 
156 	if (uf == 0)
157 		uf = getbootfile();
158 	else if (strlen(uf) >= MAXPATHLEN) {
159 		_kvm_err(kd, kd->program, "exec file name too long");
160 		goto failed;
161 	}
162 	if (flag & ~O_RDWR) {
163 		_kvm_err(kd, kd->program, "bad flags arg");
164 		goto failed;
165 	}
166 	if (mf == 0)
167 		mf = _PATH_MEM;
168 
169 	if ((kd->pmfd = open(mf, flag | O_CLOEXEC, 0)) < 0) {
170 		_kvm_syserr(kd, kd->program, "%s", mf);
171 		goto failed;
172 	}
173 	if (fstat(kd->pmfd, &st) < 0) {
174 		_kvm_syserr(kd, kd->program, "%s", mf);
175 		goto failed;
176 	}
177 	if (S_ISREG(st.st_mode) && st.st_size <= 0) {
178 		errno = EINVAL;
179 		_kvm_syserr(kd, kd->program, "empty file");
180 		goto failed;
181 	}
182 	if (S_ISCHR(st.st_mode)) {
183 		/*
184 		 * If this is a character special device, then check that
185 		 * it's /dev/mem.  If so, open kmem too.  (Maybe we should
186 		 * make it work for either /dev/mem or /dev/kmem -- in either
187 		 * case you're working with a live kernel.)
188 		 */
189 		if (strcmp(mf, _PATH_DEVNULL) == 0) {
190 			kd->vmfd = open(_PATH_DEVNULL, O_RDONLY | O_CLOEXEC);
191 			return (kd);
192 		} else if (strcmp(mf, _PATH_MEM) == 0) {
193 			if ((kd->vmfd = open(_PATH_KMEM, flag | O_CLOEXEC)) <
194 			    0) {
195 				_kvm_syserr(kd, kd->program, "%s", _PATH_KMEM);
196 				goto failed;
197 			}
198 			return (kd);
199 		}
200 	}
201 	/*
202 	 * This is a crash dump.
203 	 * Initialize the virtual address translation machinery,
204 	 * but first setup the namelist fd.
205 	 */
206 	if ((kd->nlfd = open(uf, O_RDONLY | O_CLOEXEC, 0)) < 0) {
207 		_kvm_syserr(kd, kd->program, "%s", uf);
208 		goto failed;
209 	}
210 	if (strncmp(mf, _PATH_FWMEM, strlen(_PATH_FWMEM)) == 0)
211 		kd->rawdump = 1;
212 	if (_kvm_initvtop(kd) < 0)
213 		goto failed;
214 	return (kd);
215 failed:
216 	/*
217 	 * Copy out the error if doing sane error semantics.
218 	 */
219 	if (errout != 0)
220 		strlcpy(errout, kd->errbuf, _POSIX2_LINE_MAX);
221 	(void)kvm_close(kd);
222 	return (0);
223 }
224 
225 kvm_t *
226 kvm_openfiles(const char *uf, const char *mf, const char *sf __unused, int flag,
227     char *errout)
228 {
229 	kvm_t *kd;
230 
231 	if ((kd = calloc(1, sizeof(*kd))) == NULL) {
232 		(void)strlcpy(errout, strerror(errno), _POSIX2_LINE_MAX);
233 		return (0);
234 	}
235 	kd->program = 0;
236 	return (_kvm_open(kd, uf, mf, flag, errout));
237 }
238 
239 kvm_t *
240 kvm_open(const char *uf, const char *mf, const char *sf __unused, int flag,
241     const char *errstr)
242 {
243 	kvm_t *kd;
244 
245 	if ((kd = calloc(1, sizeof(*kd))) == NULL) {
246 		if (errstr != NULL)
247 			(void)fprintf(stderr, "%s: %s\n",
248 				      errstr, strerror(errno));
249 		return (0);
250 	}
251 	kd->program = errstr;
252 	return (_kvm_open(kd, uf, mf, flag, NULL));
253 }
254 
255 int
256 kvm_close(kvm_t *kd)
257 {
258 	int error = 0;
259 
260 	if (kd->pmfd >= 0)
261 		error |= close(kd->pmfd);
262 	if (kd->vmfd >= 0)
263 		error |= close(kd->vmfd);
264 	if (kd->nlfd >= 0)
265 		error |= close(kd->nlfd);
266 	if (kd->vmst)
267 		_kvm_freevtop(kd);
268 	if (kd->procbase != 0)
269 		free((void *)kd->procbase);
270 	if (kd->argbuf != 0)
271 		free((void *) kd->argbuf);
272 	if (kd->argspc != 0)
273 		free((void *) kd->argspc);
274 	if (kd->argv != 0)
275 		free((void *)kd->argv);
276 	free((void *)kd);
277 
278 	return (0);
279 }
280 
281 /*
282  * Walk the list of unresolved symbols, generate a new list and prefix the
283  * symbol names, try again, and merge back what we could resolve.
284  */
285 static int
286 kvm_fdnlist_prefix(kvm_t *kd, struct nlist *nl, int missing, const char *prefix,
287     uintptr_t (*validate_fn)(kvm_t *, uintptr_t))
288 {
289 	struct nlist *n, *np, *p;
290 	char *cp, *ce;
291 	const char *ccp;
292 	size_t len;
293 	int slen, unresolved;
294 
295 	/*
296 	 * Calculate the space we need to malloc for nlist and names.
297 	 * We are going to store the name twice for later lookups: once
298 	 * with the prefix and once the unmodified name delmited by \0.
299 	 */
300 	len = 0;
301 	unresolved = 0;
302 	for (p = nl; p->n_name && p->n_name[0]; ++p) {
303 		if (p->n_type != N_UNDF)
304 			continue;
305 		len += sizeof(struct nlist) + strlen(prefix) +
306 		    2 * (strlen(p->n_name) + 1);
307 		unresolved++;
308 	}
309 	if (unresolved == 0)
310 		return (unresolved);
311 	/* Add space for the terminating nlist entry. */
312 	len += sizeof(struct nlist);
313 	unresolved++;
314 
315 	/* Alloc one chunk for (nlist, [names]) and setup pointers. */
316 	n = np = malloc(len);
317 	bzero(n, len);
318 	if (n == NULL)
319 		return (missing);
320 	cp = ce = (char *)np;
321 	cp += unresolved * sizeof(struct nlist);
322 	ce += len;
323 
324 	/* Generate shortened nlist with special prefix. */
325 	unresolved = 0;
326 	for (p = nl; p->n_name && p->n_name[0]; ++p) {
327 		if (p->n_type != N_UNDF)
328 			continue;
329 		bcopy(p, np, sizeof(struct nlist));
330 		/* Save the new\0orig. name so we can later match it again. */
331 		slen = snprintf(cp, ce - cp, "%s%s%c%s", prefix,
332 		    (prefix[0] != '\0' && p->n_name[0] == '_') ?
333 			(p->n_name + 1) : p->n_name, '\0', p->n_name);
334 		if (slen < 0 || slen >= ce - cp)
335 			continue;
336 		np->n_name = cp;
337 		cp += slen + 1;
338 		np++;
339 		unresolved++;
340 	}
341 
342 	/* Do lookup on the reduced list. */
343 	np = n;
344 	unresolved = __fdnlist(kd->nlfd, np);
345 
346 	/* Check if we could resolve further symbols and update the list. */
347 	if (unresolved >= 0 && unresolved < missing) {
348 		/* Find the first freshly resolved entry. */
349 		for (; np->n_name && np->n_name[0]; np++)
350 			if (np->n_type != N_UNDF)
351 				break;
352 		/*
353 		 * The lists are both in the same order,
354 		 * so we can walk them in parallel.
355 		 */
356 		for (p = nl; np->n_name && np->n_name[0] &&
357 		    p->n_name && p->n_name[0]; ++p) {
358 			if (p->n_type != N_UNDF)
359 				continue;
360 			/* Skip expanded name and compare to orig. one. */
361 			ccp = np->n_name + strlen(np->n_name) + 1;
362 			if (strcmp(ccp, p->n_name) != 0)
363 				continue;
364 			/* Update nlist with new, translated results. */
365 			p->n_type = np->n_type;
366 			p->n_other = np->n_other;
367 			p->n_desc = np->n_desc;
368 			if (validate_fn)
369 				p->n_value = (*validate_fn)(kd, np->n_value);
370 			else
371 				p->n_value = np->n_value;
372 			missing--;
373 			/* Find next freshly resolved entry. */
374 			for (np++; np->n_name && np->n_name[0]; np++)
375 				if (np->n_type != N_UNDF)
376 					break;
377 		}
378 	}
379 	/* We could assert missing = unresolved here. */
380 
381 	free(n);
382 	return (unresolved);
383 }
384 
385 int
386 _kvm_nlist(kvm_t *kd, struct nlist *nl, int initialize)
387 {
388 	struct nlist *p;
389 	int nvalid;
390 	struct kld_sym_lookup lookup;
391 	int error;
392 	const char *prefix = "";
393 	char symname[1024]; /* XXX-BZ symbol name length limit? */
394 	int tried_vnet, tried_dpcpu;
395 
396 	/*
397 	 * If we can't use the kld symbol lookup, revert to the
398 	 * slow library call.
399 	 */
400 	if (!ISALIVE(kd)) {
401 		error = __fdnlist(kd->nlfd, nl);
402 		if (error <= 0)			/* Hard error or success. */
403 			return (error);
404 
405 		if (_kvm_vnet_initialized(kd, initialize))
406 			error = kvm_fdnlist_prefix(kd, nl, error,
407 			    VNET_SYMPREFIX, _kvm_vnet_validaddr);
408 
409 		if (error > 0 && _kvm_dpcpu_initialized(kd, initialize))
410 			error = kvm_fdnlist_prefix(kd, nl, error,
411 			    DPCPU_SYMPREFIX, _kvm_dpcpu_validaddr);
412 
413 		return (error);
414 	}
415 
416 	/*
417 	 * We can use the kld lookup syscall.  Go through each nlist entry
418 	 * and look it up with a kldsym(2) syscall.
419 	 */
420 	nvalid = 0;
421 	tried_vnet = 0;
422 	tried_dpcpu = 0;
423 again:
424 	for (p = nl; p->n_name && p->n_name[0]; ++p) {
425 		if (p->n_type != N_UNDF)
426 			continue;
427 
428 		lookup.version = sizeof(lookup);
429 		lookup.symvalue = 0;
430 		lookup.symsize = 0;
431 
432 		error = snprintf(symname, sizeof(symname), "%s%s", prefix,
433 		    (prefix[0] != '\0' && p->n_name[0] == '_') ?
434 			(p->n_name + 1) : p->n_name);
435 		if (error < 0 || error >= (int)sizeof(symname))
436 			continue;
437 		lookup.symname = symname;
438 		if (lookup.symname[0] == '_')
439 			lookup.symname++;
440 
441 		if (kldsym(0, KLDSYM_LOOKUP, &lookup) != -1) {
442 			p->n_type = N_TEXT;
443 			p->n_other = 0;
444 			p->n_desc = 0;
445 			if (_kvm_vnet_initialized(kd, initialize) &&
446 			    strcmp(prefix, VNET_SYMPREFIX) == 0)
447 				p->n_value =
448 				    _kvm_vnet_validaddr(kd, lookup.symvalue);
449 			else if (_kvm_dpcpu_initialized(kd, initialize) &&
450 			    strcmp(prefix, DPCPU_SYMPREFIX) == 0)
451 				p->n_value =
452 				    _kvm_dpcpu_validaddr(kd, lookup.symvalue);
453 			else
454 				p->n_value = lookup.symvalue;
455 			++nvalid;
456 			/* lookup.symsize */
457 		}
458 	}
459 
460 	/*
461 	 * Check the number of entries that weren't found. If they exist,
462 	 * try again with a prefix for virtualized or DPCPU symbol names.
463 	 */
464 	error = ((p - nl) - nvalid);
465 	if (error && _kvm_vnet_initialized(kd, initialize) && !tried_vnet) {
466 		tried_vnet = 1;
467 		prefix = VNET_SYMPREFIX;
468 		goto again;
469 	}
470 	if (error && _kvm_dpcpu_initialized(kd, initialize) && !tried_dpcpu) {
471 		tried_dpcpu = 1;
472 		prefix = DPCPU_SYMPREFIX;
473 		goto again;
474 	}
475 
476 	/*
477 	 * Return the number of entries that weren't found. If they exist,
478 	 * also fill internal error buffer.
479 	 */
480 	error = ((p - nl) - nvalid);
481 	if (error)
482 		_kvm_syserr(kd, kd->program, "kvm_nlist");
483 	return (error);
484 }
485 
486 int
487 kvm_nlist(kvm_t *kd, struct nlist *nl)
488 {
489 
490 	/*
491 	 * If called via the public interface, permit intialization of
492 	 * further virtualized modules on demand.
493 	 */
494 	return (_kvm_nlist(kd, nl, 1));
495 }
496 
497 ssize_t
498 kvm_read(kvm_t *kd, u_long kva, void *buf, size_t len)
499 {
500 	int cc;
501 	ssize_t cr;
502 	off_t pa;
503 	char *cp;
504 
505 	if (ISALIVE(kd)) {
506 		/*
507 		 * We're using /dev/kmem.  Just read straight from the
508 		 * device and let the active kernel do the address translation.
509 		 */
510 		errno = 0;
511 		if (lseek(kd->vmfd, (off_t)kva, 0) == -1 && errno != 0) {
512 			_kvm_err(kd, 0, "invalid address (%lx)", kva);
513 			return (-1);
514 		}
515 		cr = read(kd->vmfd, buf, len);
516 		if (cr < 0) {
517 			_kvm_syserr(kd, 0, "kvm_read");
518 			return (-1);
519 		} else if (cr < (ssize_t)len)
520 			_kvm_err(kd, kd->program, "short read");
521 		return (cr);
522 	}
523 
524 	cp = buf;
525 	while (len > 0) {
526 		cc = _kvm_kvatop(kd, kva, &pa);
527 		if (cc == 0)
528 			return (-1);
529 		if (cc > (ssize_t)len)
530 			cc = len;
531 		errno = 0;
532 		if (lseek(kd->pmfd, pa, 0) == -1 && errno != 0) {
533 			_kvm_syserr(kd, 0, _PATH_MEM);
534 			break;
535 		}
536 		cr = read(kd->pmfd, cp, cc);
537 		if (cr < 0) {
538 			_kvm_syserr(kd, kd->program, "kvm_read");
539 			break;
540 		}
541 		/*
542 		 * If kvm_kvatop returns a bogus value or our core file is
543 		 * truncated, we might wind up seeking beyond the end of the
544 		 * core file in which case the read will return 0 (EOF).
545 		 */
546 		if (cr == 0)
547 			break;
548 		cp += cr;
549 		kva += cr;
550 		len -= cr;
551 	}
552 
553 	return (cp - (char *)buf);
554 }
555 
556 ssize_t
557 kvm_write(kvm_t *kd, u_long kva, const void *buf, size_t len)
558 {
559 	int cc;
560 
561 	if (ISALIVE(kd)) {
562 		/*
563 		 * Just like kvm_read, only we write.
564 		 */
565 		errno = 0;
566 		if (lseek(kd->vmfd, (off_t)kva, 0) == -1 && errno != 0) {
567 			_kvm_err(kd, 0, "invalid address (%lx)", kva);
568 			return (-1);
569 		}
570 		cc = write(kd->vmfd, buf, len);
571 		if (cc < 0) {
572 			_kvm_syserr(kd, 0, "kvm_write");
573 			return (-1);
574 		} else if ((size_t)cc < len)
575 			_kvm_err(kd, kd->program, "short write");
576 		return (cc);
577 	} else {
578 		_kvm_err(kd, kd->program,
579 		    "kvm_write not implemented for dead kernels");
580 		return (-1);
581 	}
582 	/* NOTREACHED */
583 }
584