xref: /freebsd/lib/libkvm/kvm.c (revision 3642298923e528d795e3a30ec165d2b469e28b40)
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 			return (kd);
196 		} else if (strcmp(mf, _PATH_MEM) == 0) {
197 			if ((kd->vmfd = open(_PATH_KMEM, flag)) < 0) {
198 				_kvm_syserr(kd, kd->program, "%s", _PATH_KMEM);
199 				goto failed;
200 			}
201 			if (fcntl(kd->vmfd, F_SETFD, FD_CLOEXEC) < 0) {
202 				_kvm_syserr(kd, kd->program, "%s", _PATH_KMEM);
203 				goto failed;
204 			}
205 			return (kd);
206 		}
207 	}
208 	/*
209 	 * This is a crash dump.
210 	 * Initialize the virtual address translation machinery,
211 	 * but first setup the namelist fd.
212 	 */
213 	if ((kd->nlfd = open(uf, O_RDONLY, 0)) < 0) {
214 		_kvm_syserr(kd, kd->program, "%s", uf);
215 		goto failed;
216 	}
217 	if (fcntl(kd->nlfd, F_SETFD, FD_CLOEXEC) < 0) {
218 		_kvm_syserr(kd, kd->program, "%s", uf);
219 		goto failed;
220 	}
221 	if (_kvm_initvtop(kd) < 0)
222 		goto failed;
223 	return (kd);
224 failed:
225 	/*
226 	 * Copy out the error if doing sane error semantics.
227 	 */
228 	if (errout != 0)
229 		strlcpy(errout, kd->errbuf, _POSIX2_LINE_MAX);
230 	(void)kvm_close(kd);
231 	return (0);
232 }
233 
234 kvm_t *
235 kvm_openfiles(uf, mf, sf, flag, errout)
236 	const char *uf;
237 	const char *mf;
238 	const char *sf __unused;
239 	int flag;
240 	char *errout;
241 {
242 	kvm_t *kd;
243 
244 	if ((kd = malloc(sizeof(*kd))) == NULL) {
245 		(void)strlcpy(errout, strerror(errno), _POSIX2_LINE_MAX);
246 		return (0);
247 	}
248 	memset(kd, 0, sizeof(*kd));
249 	kd->program = 0;
250 	return (_kvm_open(kd, uf, mf, flag, errout));
251 }
252 
253 kvm_t *
254 kvm_open(uf, mf, sf, flag, errstr)
255 	const char *uf;
256 	const char *mf;
257 	const char *sf __unused;
258 	int flag;
259 	const char *errstr;
260 {
261 	kvm_t *kd;
262 
263 	if ((kd = malloc(sizeof(*kd))) == NULL) {
264 		if (errstr != NULL)
265 			(void)fprintf(stderr, "%s: %s\n",
266 				      errstr, strerror(errno));
267 		return (0);
268 	}
269 	memset(kd, 0, sizeof(*kd));
270 	kd->program = errstr;
271 	return (_kvm_open(kd, uf, mf, flag, NULL));
272 }
273 
274 int
275 kvm_close(kd)
276 	kvm_t *kd;
277 {
278 	int error = 0;
279 
280 	if (kd->pmfd >= 0)
281 		error |= close(kd->pmfd);
282 	if (kd->vmfd >= 0)
283 		error |= close(kd->vmfd);
284 	if (kd->nlfd >= 0)
285 		error |= close(kd->nlfd);
286 	if (kd->vmst)
287 		_kvm_freevtop(kd);
288 	if (kd->procbase != 0)
289 		free((void *)kd->procbase);
290 	if (kd->argv != 0)
291 		free((void *)kd->argv);
292 	free((void *)kd);
293 
294 	return (0);
295 }
296 
297 int
298 kvm_nlist(kd, nl)
299 	kvm_t *kd;
300 	struct nlist *nl;
301 {
302 	struct nlist *p;
303 	int nvalid;
304 	struct kld_sym_lookup lookup;
305 
306 	/*
307 	 * If we can't use the kld symbol lookup, revert to the
308 	 * slow library call.
309 	 */
310 	if (!ISALIVE(kd))
311 		return (__fdnlist(kd->nlfd, nl));
312 
313 	/*
314 	 * We can use the kld lookup syscall.  Go through each nlist entry
315 	 * and look it up with a kldsym(2) syscall.
316 	 */
317 	nvalid = 0;
318 	for (p = nl; p->n_name && p->n_name[0]; ++p) {
319 		lookup.version = sizeof(lookup);
320 		lookup.symname = p->n_name;
321 		lookup.symvalue = 0;
322 		lookup.symsize = 0;
323 
324 		if (lookup.symname[0] == '_')
325 			lookup.symname++;
326 
327 		if (kldsym(0, KLDSYM_LOOKUP, &lookup) != -1) {
328 			p->n_type = N_TEXT;
329 			p->n_other = 0;
330 			p->n_desc = 0;
331 			p->n_value = lookup.symvalue;
332 			++nvalid;
333 			/* lookup.symsize */
334 		}
335 	}
336 	/*
337 	 * Return the number of entries that weren't found.
338 	 */
339 	return ((p - nl) - nvalid);
340 }
341 
342 ssize_t
343 kvm_read(kd, kva, buf, len)
344 	kvm_t *kd;
345 	u_long kva;
346 	void *buf;
347 	size_t len;
348 {
349 	int cc;
350 	char *cp;
351 
352 	if (ISALIVE(kd)) {
353 		/*
354 		 * We're using /dev/kmem.  Just read straight from the
355 		 * device and let the active kernel do the address translation.
356 		 */
357 		errno = 0;
358 		if (lseek(kd->vmfd, (off_t)kva, 0) == -1 && errno != 0) {
359 			_kvm_err(kd, 0, "invalid address (%x)", kva);
360 			return (-1);
361 		}
362 		cc = read(kd->vmfd, buf, len);
363 		if (cc < 0) {
364 			_kvm_syserr(kd, 0, "kvm_read");
365 			return (-1);
366 		} else if (cc < len)
367 			_kvm_err(kd, kd->program, "short read");
368 		return (cc);
369 	} else {
370 		cp = buf;
371 		while (len > 0) {
372 			off_t pa;
373 
374 			cc = _kvm_kvatop(kd, kva, &pa);
375 			if (cc == 0)
376 				return (-1);
377 			if (cc > len)
378 				cc = len;
379 			errno = 0;
380 			if (lseek(kd->pmfd, pa, 0) == -1 && errno != 0) {
381 				_kvm_syserr(kd, 0, _PATH_MEM);
382 				break;
383 			}
384 			cc = read(kd->pmfd, cp, cc);
385 			if (cc < 0) {
386 				_kvm_syserr(kd, kd->program, "kvm_read");
387 				break;
388 			}
389 			/*
390 			 * If kvm_kvatop returns a bogus value or our core
391 			 * file is truncated, we might wind up seeking beyond
392 			 * the end of the core file in which case the read will
393 			 * return 0 (EOF).
394 			 */
395 			if (cc == 0)
396 				break;
397 			cp += cc;
398 			kva += cc;
399 			len -= cc;
400 		}
401 		return (cp - (char *)buf);
402 	}
403 	/* NOTREACHED */
404 }
405 
406 ssize_t
407 kvm_write(kd, kva, buf, len)
408 	kvm_t *kd;
409 	u_long kva;
410 	const void *buf;
411 	size_t len;
412 {
413 	int cc;
414 
415 	if (ISALIVE(kd)) {
416 		/*
417 		 * Just like kvm_read, only we write.
418 		 */
419 		errno = 0;
420 		if (lseek(kd->vmfd, (off_t)kva, 0) == -1 && errno != 0) {
421 			_kvm_err(kd, 0, "invalid address (%x)", kva);
422 			return (-1);
423 		}
424 		cc = write(kd->vmfd, buf, len);
425 		if (cc < 0) {
426 			_kvm_syserr(kd, 0, "kvm_write");
427 			return (-1);
428 		} else if (cc < len)
429 			_kvm_err(kd, kd->program, "short write");
430 		return (cc);
431 	} else {
432 		_kvm_err(kd, kd->program,
433 		    "kvm_write not implemented for dead kernels");
434 		return (-1);
435 	}
436 	/* NOTREACHED */
437 }
438