xref: /netbsd-src/lib/libkvm/kvm.c (revision ae9172d6cd9432a6a1a56760d86b32c57a66c39c)
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  * 3. All advertising materials mentioning features or use of this software
18  *    must display the following acknowledgement:
19  *	This product includes software developed by the University of
20  *	California, Berkeley and its contributors.
21  * 4. Neither the name of the University nor the names of its contributors
22  *    may be used to endorse or promote products derived from this software
23  *    without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  */
37 
38 #if defined(LIBC_SCCS) && !defined(lint)
39 static char sccsid[] = "@(#)kvm.c	8.2 (Berkeley) 2/13/94";
40 #endif /* LIBC_SCCS and not lint */
41 
42 #include <sys/param.h>
43 #include <sys/user.h>
44 #include <sys/proc.h>
45 #include <sys/ioctl.h>
46 #include <sys/stat.h>
47 #include <sys/sysctl.h>
48 
49 #include <vm/vm.h>
50 #include <vm/vm_param.h>
51 #include <vm/swap_pager.h>
52 
53 #include <machine/vmparam.h>
54 
55 #include <ctype.h>
56 #include <db.h>
57 #include <fcntl.h>
58 #include <kvm.h>
59 #include <limits.h>
60 #include <nlist.h>
61 #include <paths.h>
62 #include <stdio.h>
63 #include <stdlib.h>
64 #include <string.h>
65 #include <unistd.h>
66 
67 #include "kvm_private.h"
68 
69 static int kvm_dbopen __P((kvm_t *, const char *));
70 
71 char *
72 kvm_geterr(kd)
73 	kvm_t *kd;
74 {
75 	return (kd->errbuf);
76 }
77 
78 #if __STDC__
79 #include <stdarg.h>
80 #else
81 #include <varargs.h>
82 #endif
83 
84 /*
85  * Report an error using printf style arguments.  "program" is kd->program
86  * on hard errors, and 0 on soft errors, so that under sun error emulation,
87  * only hard errors are printed out (otherwise, programs like gdb will
88  * generate tons of error messages when trying to access bogus pointers).
89  */
90 void
91 #if __STDC__
92 _kvm_err(kvm_t *kd, const char *program, const char *fmt, ...)
93 #else
94 _kvm_err(kd, program, fmt, va_alist)
95 	kvm_t *kd;
96 	char *program, *fmt;
97 	va_dcl
98 #endif
99 {
100 	va_list ap;
101 
102 #ifdef __STDC__
103 	va_start(ap, fmt);
104 #else
105 	va_start(ap);
106 #endif
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), (char *)fmt, ap);
114 
115 	va_end(ap);
116 }
117 
118 void
119 #if __STDC__
120 _kvm_syserr(kvm_t *kd, const char *program, const char *fmt, ...)
121 #else
122 _kvm_syserr(kd, program, fmt, va_alist)
123 	kvm_t *kd;
124 	char *program, *fmt;
125 	va_dcl
126 #endif
127 {
128 	va_list ap;
129 	register int n;
130 
131 #if __STDC__
132 	va_start(ap, fmt);
133 #else
134 	va_start(ap);
135 #endif
136 	if (program != NULL) {
137 		(void)fprintf(stderr, "%s: ", program);
138 		(void)vfprintf(stderr, fmt, ap);
139 		(void)fprintf(stderr, ": %s\n", strerror(errno));
140 	} else {
141 		register char *cp = kd->errbuf;
142 
143 		(void)vsnprintf(cp, sizeof(kd->errbuf), (char *)fmt, ap);
144 		n = strlen(cp);
145 		(void)snprintf(&cp[n], sizeof(kd->errbuf) - n, ": %s",
146 		    strerror(errno));
147 	}
148 	va_end(ap);
149 }
150 
151 void *
152 _kvm_malloc(kd, n)
153 	register kvm_t *kd;
154 	register size_t n;
155 {
156 	void *p;
157 
158 	if ((p = malloc(n)) == NULL)
159 		_kvm_err(kd, kd->program, strerror(errno));
160 	return (p);
161 }
162 
163 static kvm_t *
164 _kvm_open(kd, uf, mf, sf, flag, errout)
165 	register kvm_t *kd;
166 	const char *uf;
167 	const char *mf;
168 	const char *sf;
169 	int flag;
170 	char *errout;
171 {
172 	struct stat st;
173 
174 	kd->vmfd = -1;
175 	kd->pmfd = -1;
176 	kd->swfd = -1;
177 	kd->nlfd = -1;
178 	kd->vmst = 0;
179 	kd->db = 0;
180 	kd->procbase = 0;
181 	kd->nbpg = getpagesize();
182 	kd->swapspc = 0;
183 	kd->argspc = 0;
184 	kd->argv = 0;
185 
186 	if (uf == 0)
187 		uf = _PATH_UNIX;
188 	else if (strlen(uf) >= MAXPATHLEN) {
189 		_kvm_err(kd, kd->program, "exec file name too long");
190 		goto failed;
191 	}
192 	if (flag & ~O_RDWR) {
193 		_kvm_err(kd, kd->program, "bad flags arg");
194 		goto failed;
195 	}
196 	if (mf == 0)
197 		mf = _PATH_MEM;
198 	if (sf == 0)
199 		sf = _PATH_DRUM;
200 
201 	if ((kd->pmfd = open(mf, flag, 0)) < 0) {
202 		_kvm_syserr(kd, kd->program, "%s", mf);
203 		goto failed;
204 	}
205 	if (fstat(kd->pmfd, &st) < 0) {
206 		_kvm_syserr(kd, kd->program, "%s", mf);
207 		goto failed;
208 	}
209 	if (S_ISCHR(st.st_mode)) {
210 		/*
211 		 * If this is a character special device, then check that
212 		 * it's /dev/mem.  If so, open kmem too.  (Maybe we should
213 		 * make it work for either /dev/mem or /dev/kmem -- in either
214 		 * case you're working with a live kernel.)
215 		 */
216 		if (strcmp(mf, _PATH_MEM) != 0) {	/* XXX */
217 			_kvm_err(kd, kd->program,
218 				 "%s: not physical memory device", mf);
219 			goto failed;
220 		}
221 		if ((kd->vmfd = open(_PATH_KMEM, flag)) < 0) {
222 			_kvm_syserr(kd, kd->program, "%s", _PATH_KMEM);
223 			goto failed;
224 		}
225 		if ((kd->swfd = open(sf, flag, 0)) < 0) {
226 			_kvm_syserr(kd, kd->program, "%s", sf);
227 			goto failed;
228 		}
229 		/*
230 		 * Open kvm nlist database.  We go ahead and do this
231 		 * here so that we don't have to hold on to the vmunix
232 		 * path name.  Since a kvm application will surely do
233 		 * a kvm_nlist(), this probably won't be a wasted effort.
234 		 * If the database cannot be opened, open the namelist
235 		 * argument so we revert to slow nlist() calls.
236 		 */
237 		if (kvm_dbopen(kd, uf) < 0 &&
238 		    (kd->nlfd = open(uf, O_RDONLY, 0)) < 0) {
239 			_kvm_syserr(kd, kd->program, "%s", uf);
240 			goto failed;
241 		}
242 	} else {
243 		/*
244 		 * This is a crash dump.
245 		 * Initalize the virtual address translation machinery,
246 		 * but first setup the namelist fd.
247 		 */
248 		if ((kd->nlfd = open(uf, O_RDONLY, 0)) < 0) {
249 			_kvm_syserr(kd, kd->program, "%s", uf);
250 			goto failed;
251 		}
252 		if (_kvm_initvtop(kd) < 0)
253 			goto failed;
254 	}
255 	return (kd);
256 failed:
257 	/*
258 	 * Copy out the error if doing sane error semantics.
259 	 */
260 	if (errout != 0)
261 		strcpy(errout, kd->errbuf);
262 	(void)kvm_close(kd);
263 	return (0);
264 }
265 
266 kvm_t *
267 kvm_openfiles(uf, mf, sf, flag, errout)
268 	const char *uf;
269 	const char *mf;
270 	const char *sf;
271 	int flag;
272 	char *errout;
273 {
274 	register kvm_t *kd;
275 
276 	if ((kd = malloc(sizeof(*kd))) == NULL) {
277 		(void)strcpy(errout, strerror(errno));
278 		return (0);
279 	}
280 	kd->program = 0;
281 	return (_kvm_open(kd, uf, mf, sf, flag, errout));
282 }
283 
284 kvm_t *
285 kvm_open(uf, mf, sf, flag, program)
286 	const char *uf;
287 	const char *mf;
288 	const char *sf;
289 	int flag;
290 	const char *program;
291 {
292 	register kvm_t *kd;
293 
294 	if ((kd = malloc(sizeof(*kd))) == NULL && program != NULL) {
295 		(void)fprintf(stderr, "%s: %s\n", strerror(errno));
296 		return (0);
297 	}
298 	kd->program = program;
299 	return (_kvm_open(kd, uf, mf, sf, flag, NULL));
300 }
301 
302 int
303 kvm_close(kd)
304 	kvm_t *kd;
305 {
306 	register int error = 0;
307 
308 	if (kd->pmfd >= 0)
309 		error |= close(kd->pmfd);
310 	if (kd->vmfd >= 0)
311 		error |= close(kd->vmfd);
312 	if (kd->nlfd >= 0)
313 		error |= close(kd->nlfd);
314 	if (kd->swfd >= 0)
315 		error |= close(kd->swfd);
316 	if (kd->db != 0)
317 		error |= (kd->db->close)(kd->db);
318 	if (kd->vmst)
319 		_kvm_freevtop(kd);
320 	if (kd->procbase != 0)
321 		free((void *)kd->procbase);
322 	if (kd->swapspc != 0)
323 		free((void *)kd->swapspc);
324 	if (kd->argspc != 0)
325 		free((void *)kd->argspc);
326 	if (kd->argv != 0)
327 		free((void *)kd->argv);
328 	free((void *)kd);
329 
330 	return (0);
331 }
332 
333 /*
334  * Set up state necessary to do queries on the kernel namelist
335  * data base.  If the data base is out-of-data/incompatible with
336  * given executable, set up things so we revert to standard nlist call.
337  * Only called for live kernels.  Return 0 on success, -1 on failure.
338  */
339 static int
340 kvm_dbopen(kd, uf)
341 	kvm_t *kd;
342 	const char *uf;
343 {
344 	char *cp;
345 	DBT rec;
346 	int dbversionlen;
347 	struct nlist nitem;
348 	char dbversion[_POSIX2_LINE_MAX];
349 	char kversion[_POSIX2_LINE_MAX];
350 	char dbname[MAXPATHLEN];
351 
352 	if ((cp = rindex(uf, '/')) != 0)
353 		uf = cp + 1;
354 
355 	(void)snprintf(dbname, sizeof(dbname), "%skvm_%s.db", _PATH_VARDB, uf);
356 	kd->db = dbopen(dbname, O_RDONLY, 0, DB_HASH, NULL);
357 	if (kd->db == 0)
358 		return (-1);
359 	/*
360 	 * read version out of database
361 	 */
362 	rec.data = VRS_KEY;
363 	rec.size = sizeof(VRS_KEY) - 1;
364 	if ((kd->db->get)(kd->db, (DBT *)&rec, (DBT *)&rec, 0))
365 		goto close;
366 	if (rec.data == 0 || rec.size > sizeof(dbversion))
367 		goto close;
368 
369 	bcopy(rec.data, dbversion, rec.size);
370 	dbversionlen = rec.size;
371 	/*
372 	 * Read version string from kernel memory.
373 	 * Since we are dealing with a live kernel, we can call kvm_read()
374 	 * at this point.
375 	 */
376 	rec.data = VRS_SYM;
377 	rec.size = sizeof(VRS_SYM) - 1;
378 	if ((kd->db->get)(kd->db, (DBT *)&rec, (DBT *)&rec, 0))
379 		goto close;
380 	if (rec.data == 0 || rec.size != sizeof(struct nlist))
381 		goto close;
382 	bcopy((char *)rec.data, (char *)&nitem, sizeof(nitem));
383 	if (kvm_read(kd, (u_long)nitem.n_value, kversion, dbversionlen) !=
384 	    dbversionlen)
385 		goto close;
386 	/*
387 	 * If they match, we win - otherwise clear out kd->db so
388 	 * we revert to slow nlist().
389 	 */
390 	if (bcmp(dbversion, kversion, dbversionlen) == 0)
391 		return (0);
392 close:
393 	(void)(kd->db->close)(kd->db);
394 	kd->db = 0;
395 
396 	return (-1);
397 }
398 
399 int
400 kvm_nlist(kd, nl)
401 	kvm_t *kd;
402 	struct nlist *nl;
403 {
404 	register struct nlist *p;
405 	register int nvalid;
406 
407 	/*
408 	 * If we can't use the data base, revert to the
409 	 * slow library call.
410 	 */
411 	if (kd->db == 0)
412 		return (__fdnlist(kd->nlfd, nl));
413 
414 	/*
415 	 * We can use the kvm data base.  Go through each nlist entry
416 	 * and look it up with a db query.
417 	 */
418 	nvalid = 0;
419 	for (p = nl; p->n_name && p->n_name[0]; ++p) {
420 		register int len;
421 		DBT rec;
422 
423 		if ((len = strlen(p->n_name)) > 4096) {
424 			/* sanity */
425 			_kvm_err(kd, kd->program, "symbol too large");
426 			return (-1);
427 		}
428 		rec.data = p->n_name;
429 		rec.size = len;
430 		if ((kd->db->get)(kd->db, (DBT *)&rec, (DBT *)&rec, 0))
431 			continue;
432 		if (rec.data == 0 || rec.size != sizeof(struct nlist))
433 			continue;
434 		++nvalid;
435 		/*
436 		 * Avoid alignment issues.
437 		 */
438 		bcopy((char *)&((struct nlist *)rec.data)->n_type,
439 		      (char *)&p->n_type,
440 		      sizeof(p->n_type));
441 		bcopy((char *)&((struct nlist *)rec.data)->n_value,
442 		      (char *)&p->n_value,
443 		      sizeof(p->n_value));
444 	}
445 	/*
446 	 * Return the number of entries that weren't found.
447 	 */
448 	return ((p - nl) - nvalid);
449 }
450 
451 ssize_t
452 kvm_read(kd, kva, buf, len)
453 	kvm_t *kd;
454 	register u_long kva;
455 	register void *buf;
456 	register size_t len;
457 {
458 	register int cc;
459 	register void *cp;
460 
461 	if (ISALIVE(kd)) {
462 		/*
463 		 * We're using /dev/kmem.  Just read straight from the
464 		 * device and let the active kernel do the address translation.
465 		 */
466 		errno = 0;
467 		if (lseek(kd->vmfd, (off_t)kva, 0) == -1 && errno != 0) {
468 			_kvm_err(kd, 0, "invalid address (%x)", kva);
469 			return (0);
470 		}
471 		cc = read(kd->vmfd, buf, len);
472 		if (cc < 0) {
473 			_kvm_syserr(kd, 0, "kvm_read");
474 			return (0);
475 		} else if (cc < len)
476 			_kvm_err(kd, kd->program, "short read");
477 		return (cc);
478 	} else {
479 		cp = buf;
480 		while (len > 0) {
481 			u_long pa;
482 
483 			cc = _kvm_kvatop(kd, kva, &pa);
484 			if (cc == 0)
485 				return (0);
486 			if (cc > len)
487 				cc = len;
488 			errno = 0;
489 			if (lseek(kd->pmfd, (off_t)pa, 0) == -1 && errno != 0) {
490 				_kvm_syserr(kd, 0, _PATH_MEM);
491 				break;
492 			}
493 			cc = read(kd->pmfd, cp, cc);
494 			if (cc < 0) {
495 				_kvm_syserr(kd, kd->program, "kvm_read");
496 				break;
497 			}
498 			/*
499 			 * If kvm_kvatop returns a bogus value or our core
500 			 * file is truncated, we might wind up seeking beyond
501 			 * the end of the core file in which case the read will
502 			 * return 0 (EOF).
503 			 */
504 			if (cc == 0)
505 				break;
506 			(char *)cp += cc;
507 			kva += cc;
508 			len -= cc;
509 		}
510 		return ((char *)cp - (char *)buf);
511 	}
512 	/* NOTREACHED */
513 }
514 
515 ssize_t
516 kvm_write(kd, kva, buf, len)
517 	kvm_t *kd;
518 	register u_long kva;
519 	register const void *buf;
520 	register size_t len;
521 {
522 	register int cc;
523 
524 	if (ISALIVE(kd)) {
525 		/*
526 		 * Just like kvm_read, only we write.
527 		 */
528 		errno = 0;
529 		if (lseek(kd->vmfd, (off_t)kva, 0) == -1 && errno != 0) {
530 			_kvm_err(kd, 0, "invalid address (%x)", kva);
531 			return (0);
532 		}
533 		cc = write(kd->vmfd, buf, len);
534 		if (cc < 0) {
535 			_kvm_syserr(kd, 0, "kvm_write");
536 			return (0);
537 		} else if (cc < len)
538 			_kvm_err(kd, kd->program, "short write");
539 		return (cc);
540 	} else {
541 		_kvm_err(kd, kd->program,
542 		    "kvm_write not implemented for dead kernels");
543 		return (0);
544 	}
545 	/* NOTREACHED */
546 }
547