xref: /freebsd/lib/libkvm/kvm.c (revision c4f02a891fe62fe1277c89859922804ea2c27bcd)
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 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD$");
40 
41 #if defined(LIBC_SCCS) && !defined(lint)
42 #if 0
43 static char sccsid[] = "@(#)kvm.c	8.2 (Berkeley) 2/13/94";
44 #endif
45 #endif /* LIBC_SCCS and not lint */
46 
47 #include <sys/param.h>
48 #include <sys/user.h>
49 #include <sys/proc.h>
50 #include <sys/ioctl.h>
51 #include <sys/stat.h>
52 #include <sys/sysctl.h>
53 #include <sys/linker.h>
54 
55 #include <vm/vm.h>
56 #include <vm/vm_param.h>
57 
58 #include <machine/vmparam.h>
59 
60 #include <ctype.h>
61 #include <fcntl.h>
62 #include <kvm.h>
63 #include <limits.h>
64 #include <nlist.h>
65 #include <paths.h>
66 #include <stdio.h>
67 #include <stdlib.h>
68 #include <string.h>
69 #include <unistd.h>
70 
71 #include "kvm_private.h"
72 
73 /* from src/lib/libc/gen/nlist.c */
74 int __fdnlist(int, struct nlist *);
75 
76 char *
77 kvm_geterr(kd)
78 	kvm_t *kd;
79 {
80 	return (kd->errbuf);
81 }
82 
83 #include <stdarg.h>
84 
85 /*
86  * Report an error using printf style arguments.  "program" is kd->program
87  * on hard errors, and 0 on soft errors, so that under sun error emulation,
88  * only hard errors are printed out (otherwise, programs like gdb will
89  * generate tons of error messages when trying to access bogus pointers).
90  */
91 void
92 _kvm_err(kvm_t *kd, const char *program, const char *fmt, ...)
93 {
94 	va_list ap;
95 
96 	va_start(ap, fmt);
97 	if (program != NULL) {
98 		(void)fprintf(stderr, "%s: ", program);
99 		(void)vfprintf(stderr, fmt, ap);
100 		(void)fputc('\n', stderr);
101 	} else
102 		(void)vsnprintf(kd->errbuf,
103 		    sizeof(kd->errbuf), (char *)fmt, ap);
104 
105 	va_end(ap);
106 }
107 
108 void
109 _kvm_syserr(kvm_t *kd, const char *program, const char *fmt, ...)
110 {
111 	va_list ap;
112 	int n;
113 
114 	va_start(ap, fmt);
115 	if (program != NULL) {
116 		(void)fprintf(stderr, "%s: ", program);
117 		(void)vfprintf(stderr, fmt, ap);
118 		(void)fprintf(stderr, ": %s\n", strerror(errno));
119 	} else {
120 		char *cp = kd->errbuf;
121 
122 		(void)vsnprintf(cp, sizeof(kd->errbuf), (char *)fmt, ap);
123 		n = strlen(cp);
124 		(void)snprintf(&cp[n], sizeof(kd->errbuf) - n, ": %s",
125 		    strerror(errno));
126 	}
127 	va_end(ap);
128 }
129 
130 void *
131 _kvm_malloc(kd, n)
132 	kvm_t *kd;
133 	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 %u bytes: %s",
139 			 n, strerror(errno));
140 	return (p);
141 }
142 
143 static kvm_t *
144 _kvm_open(kd, uf, mf, flag, errout)
145 	kvm_t *kd;
146 	const char *uf;
147 	const char *mf;
148 	int flag;
149 	char *errout;
150 {
151 	struct stat st;
152 
153 	kd->vmfd = -1;
154 	kd->pmfd = -1;
155 	kd->nlfd = -1;
156 	kd->vmst = 0;
157 	kd->procbase = 0;
158 	kd->argspc = 0;
159 	kd->argv = 0;
160 
161 	if (uf == 0)
162 		uf = getbootfile();
163 	else if (strlen(uf) >= MAXPATHLEN) {
164 		_kvm_err(kd, kd->program, "exec file name too long");
165 		goto failed;
166 	}
167 	if (flag & ~O_RDWR) {
168 		_kvm_err(kd, kd->program, "bad flags arg");
169 		goto failed;
170 	}
171 	if (mf == 0)
172 		mf = _PATH_MEM;
173 
174 	if ((kd->pmfd = open(mf, flag, 0)) < 0) {
175 		_kvm_syserr(kd, kd->program, "%s", mf);
176 		goto failed;
177 	}
178 	if (fstat(kd->pmfd, &st) < 0) {
179 		_kvm_syserr(kd, kd->program, "%s", mf);
180 		goto failed;
181 	}
182 	if (fcntl(kd->pmfd, F_SETFD, FD_CLOEXEC) < 0) {
183 		_kvm_syserr(kd, kd->program, "%s", mf);
184 		goto failed;
185 	}
186 	if (S_ISCHR(st.st_mode)) {
187 		/*
188 		 * If this is a character special device, then check that
189 		 * it's /dev/mem.  If so, open kmem too.  (Maybe we should
190 		 * make it work for either /dev/mem or /dev/kmem -- in either
191 		 * case you're working with a live kernel.)
192 		 */
193 		if (strcmp(mf, _PATH_DEVNULL) == 0) {
194 			kd->vmfd = open(_PATH_DEVNULL, O_RDONLY);
195 		} else if (strcmp(mf, _PATH_MEM) != 0) {
196 			_kvm_err(kd, kd->program,
197 				 "%s: not physical memory device", mf);
198 			goto failed;
199 		} else {
200 			if ((kd->vmfd = open(_PATH_KMEM, flag)) < 0) {
201 				_kvm_syserr(kd, kd->program, "%s", _PATH_KMEM);
202 				goto failed;
203 			}
204 			if (fcntl(kd->vmfd, F_SETFD, FD_CLOEXEC) < 0) {
205 				_kvm_syserr(kd, kd->program, "%s", _PATH_KMEM);
206 				goto failed;
207 			}
208 		}
209 	} else {
210 		/*
211 		 * This is a crash dump.
212 		 * Initialize the virtual address translation machinery,
213 		 * but first setup the namelist fd.
214 		 */
215 		if ((kd->nlfd = open(uf, O_RDONLY, 0)) < 0) {
216 			_kvm_syserr(kd, kd->program, "%s", uf);
217 			goto failed;
218 		}
219 		if (fcntl(kd->nlfd, F_SETFD, FD_CLOEXEC) < 0) {
220 			_kvm_syserr(kd, kd->program, "%s", uf);
221 			goto failed;
222 		}
223 		if (_kvm_initvtop(kd) < 0)
224 			goto failed;
225 	}
226 	return (kd);
227 failed:
228 	/*
229 	 * Copy out the error if doing sane error semantics.
230 	 */
231 	if (errout != 0)
232 		strlcpy(errout, kd->errbuf, _POSIX2_LINE_MAX);
233 	(void)kvm_close(kd);
234 	return (0);
235 }
236 
237 kvm_t *
238 kvm_openfiles(uf, mf, sf, flag, errout)
239 	const char *uf;
240 	const char *mf;
241 	const char *sf __unused;
242 	int flag;
243 	char *errout;
244 {
245 	kvm_t *kd;
246 
247 	if ((kd = malloc(sizeof(*kd))) == NULL) {
248 		(void)strlcpy(errout, strerror(errno), _POSIX2_LINE_MAX);
249 		return (0);
250 	}
251 	memset(kd, 0, sizeof(*kd));
252 	kd->program = 0;
253 	return (_kvm_open(kd, uf, mf, flag, errout));
254 }
255 
256 kvm_t *
257 kvm_open(uf, mf, sf, flag, errstr)
258 	const char *uf;
259 	const char *mf;
260 	const char *sf __unused;
261 	int flag;
262 	const char *errstr;
263 {
264 	kvm_t *kd;
265 
266 	if ((kd = malloc(sizeof(*kd))) == NULL) {
267 		if (errstr != NULL)
268 			(void)fprintf(stderr, "%s: %s\n",
269 				      errstr, strerror(errno));
270 		return (0);
271 	}
272 	memset(kd, 0, sizeof(*kd));
273 	kd->program = errstr;
274 	return (_kvm_open(kd, uf, mf, flag, NULL));
275 }
276 
277 int
278 kvm_close(kd)
279 	kvm_t *kd;
280 {
281 	int error = 0;
282 
283 	if (kd->pmfd >= 0)
284 		error |= close(kd->pmfd);
285 	if (kd->vmfd >= 0)
286 		error |= close(kd->vmfd);
287 	if (kd->nlfd >= 0)
288 		error |= close(kd->nlfd);
289 	if (kd->vmst)
290 		_kvm_freevtop(kd);
291 	if (kd->procbase != 0)
292 		free((void *)kd->procbase);
293 	if (kd->argv != 0)
294 		free((void *)kd->argv);
295 	free((void *)kd);
296 
297 	return (0);
298 }
299 
300 int
301 kvm_nlist(kd, nl)
302 	kvm_t *kd;
303 	struct nlist *nl;
304 {
305 	struct nlist *p;
306 	int nvalid;
307 	struct kld_sym_lookup lookup;
308 
309 	/*
310 	 * If we can't use the kld symbol lookup, revert to the
311 	 * slow library call.
312 	 */
313 	if (!ISALIVE(kd))
314 		return (__fdnlist(kd->nlfd, nl));
315 
316 	/*
317 	 * We can use the kld lookup syscall.  Go through each nlist entry
318 	 * and look it up with a kldsym(2) syscall.
319 	 */
320 	nvalid = 0;
321 	for (p = nl; p->n_name && p->n_name[0]; ++p) {
322 		lookup.version = sizeof(lookup);
323 		lookup.symname = p->n_name;
324 		lookup.symvalue = 0;
325 		lookup.symsize = 0;
326 
327 		if (lookup.symname[0] == '_')
328 			lookup.symname++;
329 
330 		if (kldsym(0, KLDSYM_LOOKUP, &lookup) != -1) {
331 			p->n_type = N_TEXT;
332 			p->n_other = 0;
333 			p->n_desc = 0;
334 			p->n_value = lookup.symvalue;
335 			++nvalid;
336 			/* lookup.symsize */
337 		}
338 	}
339 	/*
340 	 * Return the number of entries that weren't found.
341 	 */
342 	return ((p - nl) - nvalid);
343 }
344 
345 ssize_t
346 kvm_read(kd, kva, buf, len)
347 	kvm_t *kd;
348 	u_long kva;
349 	void *buf;
350 	size_t len;
351 {
352 	int cc;
353 	void *cp;
354 
355 	if (ISALIVE(kd)) {
356 		/*
357 		 * We're using /dev/kmem.  Just read straight from the
358 		 * device and let the active kernel do the address translation.
359 		 */
360 		errno = 0;
361 		if (lseek(kd->vmfd, (off_t)kva, 0) == -1 && errno != 0) {
362 			_kvm_err(kd, 0, "invalid address (%x)", kva);
363 			return (-1);
364 		}
365 		cc = read(kd->vmfd, buf, len);
366 		if (cc < 0) {
367 			_kvm_syserr(kd, 0, "kvm_read");
368 			return (-1);
369 		} else if (cc < len)
370 			_kvm_err(kd, kd->program, "short read");
371 		return (cc);
372 	} else {
373 		cp = buf;
374 		while (len > 0) {
375 			u_long pa;
376 
377 			cc = _kvm_kvatop(kd, kva, &pa);
378 			if (cc == 0)
379 				return (-1);
380 			if (cc > len)
381 				cc = len;
382 			errno = 0;
383 			if (lseek(kd->pmfd, (off_t)pa, 0) == -1 && errno != 0) {
384 				_kvm_syserr(kd, 0, _PATH_MEM);
385 				break;
386 			}
387 			cc = read(kd->pmfd, cp, cc);
388 			if (cc < 0) {
389 				_kvm_syserr(kd, kd->program, "kvm_read");
390 				break;
391 			}
392 			/*
393 			 * If kvm_kvatop returns a bogus value or our core
394 			 * file is truncated, we might wind up seeking beyond
395 			 * the end of the core file in which case the read will
396 			 * return 0 (EOF).
397 			 */
398 			if (cc == 0)
399 				break;
400 			(char *)cp += cc;
401 			kva += cc;
402 			len -= cc;
403 		}
404 		return ((char *)cp - (char *)buf);
405 	}
406 	/* NOTREACHED */
407 }
408 
409 ssize_t
410 kvm_write(kd, kva, buf, len)
411 	kvm_t *kd;
412 	u_long kva;
413 	const void *buf;
414 	size_t len;
415 {
416 	int cc;
417 
418 	if (ISALIVE(kd)) {
419 		/*
420 		 * Just like kvm_read, only we write.
421 		 */
422 		errno = 0;
423 		if (lseek(kd->vmfd, (off_t)kva, 0) == -1 && errno != 0) {
424 			_kvm_err(kd, 0, "invalid address (%x)", kva);
425 			return (-1);
426 		}
427 		cc = write(kd->vmfd, buf, len);
428 		if (cc < 0) {
429 			_kvm_syserr(kd, 0, "kvm_write");
430 			return (-1);
431 		} else if (cc < len)
432 			_kvm_err(kd, kd->program, "short write");
433 		return (cc);
434 	} else {
435 		_kvm_err(kd, kd->program,
436 		    "kvm_write not implemented for dead kernels");
437 		return (-1);
438 	}
439 	/* NOTREACHED */
440 }
441