xref: /openbsd-src/lib/libkvm/kvm_proc.c (revision d13be5d47e4149db2549a9828e244d59dbc43f15)
1 /*	$OpenBSD: kvm_proc.c,v 1.44 2011/06/06 17:18:26 ariane Exp $	*/
2 /*	$NetBSD: kvm_proc.c,v 1.30 1999/03/24 05:50:50 mrg Exp $	*/
3 /*-
4  * Copyright (c) 1998 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Charles M. Hannum.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31 /*-
32  * Copyright (c) 1994, 1995 Charles M. Hannum.  All rights reserved.
33  * Copyright (c) 1989, 1992, 1993
34  *	The Regents of the University of California.  All rights reserved.
35  *
36  * This code is derived from software developed by the Computer Systems
37  * Engineering group at Lawrence Berkeley Laboratory under DARPA contract
38  * BG 91-66 and contributed to Berkeley.
39  *
40  * Redistribution and use in source and binary forms, with or without
41  * modification, are permitted provided that the following conditions
42  * are met:
43  * 1. Redistributions of source code must retain the above copyright
44  *    notice, this list of conditions and the following disclaimer.
45  * 2. Redistributions in binary form must reproduce the above copyright
46  *    notice, this list of conditions and the following disclaimer in the
47  *    documentation and/or other materials provided with the distribution.
48  * 3. Neither the name of the University nor the names of its contributors
49  *    may be used to endorse or promote products derived from this software
50  *    without specific prior written permission.
51  *
52  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
53  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
54  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
55  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
56  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
57  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
58  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
59  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
60  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
61  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
62  * SUCH DAMAGE.
63  */
64 
65 /*
66  * Proc traversal interface for kvm.  ps and w are (probably) the exclusive
67  * users of this code, so we've factored it out into a separate module.
68  * Thus, we keep this grunge out of the other kvm applications (i.e.,
69  * most other applications are interested only in open/close/read/nlist).
70  */
71 
72 #include <sys/param.h>
73 #include <sys/user.h>
74 #include <sys/proc.h>
75 #include <sys/exec.h>
76 #include <sys/stat.h>
77 #include <sys/ioctl.h>
78 #include <sys/tty.h>
79 #include <stdlib.h>
80 #include <string.h>
81 #include <unistd.h>
82 #include <nlist.h>
83 #include <kvm.h>
84 
85 #include <uvm/uvm_extern.h>
86 #include <uvm/uvm_amap.h>
87 #include <machine/vmparam.h>
88 #include <machine/pmap.h>
89 
90 #include <sys/sysctl.h>
91 
92 #include <limits.h>
93 #include <db.h>
94 #include <paths.h>
95 
96 #include "kvm_private.h"
97 
98 /*
99  * Common info from kinfo_proc used by helper routines.
100  */
101 struct miniproc {
102 	struct	vmspace *p_vmspace;
103 	char	p_stat;
104 	struct	proc *p_paddr;
105 	pid_t	p_pid;
106 };
107 
108 /*
109  * Convert from struct kinfo_proc to miniproc.
110  */
111 #define KPTOMINI(kp, p) \
112 	do { \
113 		(p)->p_stat = (kp)->p_stat; \
114 		(p)->p_pid = (kp)->p_pid; \
115 		(p)->p_paddr = (void *)(long)(kp)->p_paddr; \
116 		(p)->p_vmspace = (void *)(long)(kp)->p_vmspace; \
117 	} while (/*CONSTCOND*/0);
118 
119 
120 static char	*_kvm_ureadm(kvm_t *, const struct miniproc *, u_long, u_long *);
121 static ssize_t	kvm_ureadm(kvm_t *, const struct miniproc *, u_long, char *, size_t);
122 
123 static char	**kvm_argv(kvm_t *, const struct miniproc *, u_long, int, int);
124 
125 static char	**kvm_doargv(kvm_t *, const struct miniproc *, int,
126 		    void (*)(struct ps_strings *, u_long *, int *));
127 static int	proc_verify(kvm_t *, const struct miniproc *);
128 static void	ps_str_a(struct ps_strings *, u_long *, int *);
129 static void	ps_str_e(struct ps_strings *, u_long *, int *);
130 
131 static char *
132 _kvm_ureadm(kvm_t *kd, const struct miniproc *p, u_long va, u_long *cnt)
133 {
134 	u_long addr, head, offset, slot;
135 	struct vm_anon *anonp, anon;
136 	struct vm_map_entry vme;
137 	struct vm_amap amap;
138 	struct vm_page pg;
139 
140 	if (kd->swapspc == 0) {
141 		kd->swapspc = _kvm_malloc(kd, kd->nbpg);
142 		if (kd->swapspc == 0)
143 			return (0);
144 	}
145 
146 	/*
147 	 * Look through the address map for the memory object
148 	 * that corresponds to the given virtual address.
149 	 * The header just has the entire valid range.
150 	 */
151 	head = (u_long)&p->p_vmspace->vm_map.header;
152 	addr = head;
153 	while (1) {
154 		if (KREAD(kd, addr, &vme))
155 			return (0);
156 
157 		if (va >= vme.start && va < vme.end &&
158 		    vme.aref.ar_amap != NULL)
159 			break;
160 
161 		addr = (u_long)vme.next;
162 		if (addr == head)
163 			return (0);
164 	}
165 
166 	/*
167 	 * we found the map entry, now to find the object...
168 	 */
169 	if (vme.aref.ar_amap == NULL)
170 		return (NULL);
171 
172 	addr = (u_long)vme.aref.ar_amap;
173 	if (KREAD(kd, addr, &amap))
174 		return (NULL);
175 
176 	offset = va - vme.start;
177 	slot = offset / kd->nbpg + vme.aref.ar_pageoff;
178 	/* sanity-check slot number */
179 	if (slot > amap.am_nslot)
180 		return (NULL);
181 
182 	addr = (u_long)amap.am_anon + (offset / kd->nbpg) * sizeof(anonp);
183 	if (KREAD(kd, addr, &anonp))
184 		return (NULL);
185 
186 	addr = (u_long)anonp;
187 	if (KREAD(kd, addr, &anon))
188 		return (NULL);
189 
190 	addr = (u_long)anon.an_page;
191 	if (addr) {
192 		if (KREAD(kd, addr, &pg))
193 			return (NULL);
194 
195 		if (_kvm_pread(kd, kd->pmfd, (void *)kd->swapspc,
196 		    (size_t)kd->nbpg, (off_t)pg.phys_addr) != kd->nbpg)
197 			return (NULL);
198 	} else {
199 		if (kd->swfd == -1 ||
200 		    _kvm_pread(kd, kd->swfd, (void *)kd->swapspc,
201 		    (size_t)kd->nbpg,
202 		    (off_t)(anon.an_swslot * kd->nbpg)) != kd->nbpg)
203 			return (NULL);
204 	}
205 
206 	/* Found the page. */
207 	offset %= kd->nbpg;
208 	*cnt = kd->nbpg - offset;
209 	return (&kd->swapspc[offset]);
210 }
211 
212 void *
213 _kvm_realloc(kvm_t *kd, void *p, size_t n)
214 {
215 	void *np = (void *)realloc(p, n);
216 
217 	if (np == 0)
218 		_kvm_err(kd, kd->program, "out of memory");
219 	return (np);
220 }
221 
222 /*
223  * Read in an argument vector from the user address space of process p.
224  * addr if the user-space base address of narg null-terminated contiguous
225  * strings.  This is used to read in both the command arguments and
226  * environment strings.  Read at most maxcnt characters of strings.
227  */
228 static char **
229 kvm_argv(kvm_t *kd, const struct miniproc *p, u_long addr, int narg,
230     int maxcnt)
231 {
232 	char *np, *cp, *ep, *ap, **argv;
233 	u_long oaddr = -1;
234 	int len, cc;
235 
236 	/*
237 	 * Check that there aren't an unreasonable number of arguments,
238 	 * and that the address is in user space.
239 	 */
240 	if (narg > ARG_MAX || addr < VM_MIN_ADDRESS || addr >= VM_MAXUSER_ADDRESS)
241 		return (0);
242 
243 	if (kd->argv == 0) {
244 		/*
245 		 * Try to avoid reallocs.
246 		 */
247 		kd->argc = MAX(narg + 1, 32);
248 		kd->argv = _kvm_malloc(kd, kd->argc *
249 		    sizeof(*kd->argv));
250 		if (kd->argv == 0)
251 			return (0);
252 	} else if (narg + 1 > kd->argc) {
253 		kd->argc = MAX(2 * kd->argc, narg + 1);
254 		kd->argv = (char **)_kvm_realloc(kd, kd->argv, kd->argc *
255 		    sizeof(*kd->argv));
256 		if (kd->argv == 0)
257 			return (0);
258 	}
259 	if (kd->argspc == 0) {
260 		kd->argspc = _kvm_malloc(kd, kd->nbpg);
261 		if (kd->argspc == 0)
262 			return (0);
263 		kd->arglen = kd->nbpg;
264 	}
265 	if (kd->argbuf == 0) {
266 		kd->argbuf = _kvm_malloc(kd, kd->nbpg);
267 		if (kd->argbuf == 0)
268 			return (0);
269 	}
270 	cc = sizeof(char *) * narg;
271 	if (kvm_ureadm(kd, p, addr, (char *)kd->argv, cc) != cc)
272 		return (0);
273 	ap = np = kd->argspc;
274 	argv = kd->argv;
275 	len = 0;
276 
277 	/*
278 	 * Loop over pages, filling in the argument vector.
279 	 */
280 	while (argv < kd->argv + narg && *argv != 0) {
281 		addr = (u_long)*argv & ~(kd->nbpg - 1);
282 		if (addr != oaddr) {
283 			if (kvm_ureadm(kd, p, addr, kd->argbuf, kd->nbpg) !=
284 			    kd->nbpg)
285 				return (0);
286 			oaddr = addr;
287 		}
288 		addr = (u_long)*argv & (kd->nbpg - 1);
289 		cp = kd->argbuf + addr;
290 		cc = kd->nbpg - addr;
291 		if (maxcnt > 0 && cc > maxcnt - len)
292 			cc = maxcnt - len;
293 		ep = memchr(cp, '\0', cc);
294 		if (ep != 0)
295 			cc = ep - cp + 1;
296 		if (len + cc > kd->arglen) {
297 			int off;
298 			char **pp;
299 			char *op = kd->argspc;
300 
301 			kd->arglen *= 2;
302 			kd->argspc = (char *)_kvm_realloc(kd, kd->argspc,
303 			    kd->arglen);
304 			if (kd->argspc == 0)
305 				return (0);
306 			/*
307 			 * Adjust argv pointers in case realloc moved
308 			 * the string space.
309 			 */
310 			off = kd->argspc - op;
311 			for (pp = kd->argv; pp < argv; pp++)
312 				*pp += off;
313 			ap += off;
314 			np += off;
315 		}
316 		memcpy(np, cp, cc);
317 		np += cc;
318 		len += cc;
319 		if (ep != 0) {
320 			*argv++ = ap;
321 			ap = np;
322 		} else
323 			*argv += cc;
324 		if (maxcnt > 0 && len >= maxcnt) {
325 			/*
326 			 * We're stopping prematurely.  Terminate the
327 			 * current string.
328 			 */
329 			if (ep == 0) {
330 				*np = '\0';
331 				*argv++ = ap;
332 			}
333 			break;
334 		}
335 	}
336 	/* Make sure argv is terminated. */
337 	*argv = 0;
338 	return (kd->argv);
339 }
340 
341 static void
342 ps_str_a(struct ps_strings *p, u_long *addr, int *n)
343 {
344 	*addr = (u_long)p->ps_argvstr;
345 	*n = p->ps_nargvstr;
346 }
347 
348 static void
349 ps_str_e(struct ps_strings *p, u_long *addr, int *n)
350 {
351 	*addr = (u_long)p->ps_envstr;
352 	*n = p->ps_nenvstr;
353 }
354 
355 /*
356  * Determine if the proc indicated by p is still active.
357  * This test is not 100% foolproof in theory, but chances of
358  * being wrong are very low.
359  */
360 static int
361 proc_verify(kvm_t *kd, const struct miniproc *p)
362 {
363 	struct proc kernproc;
364 
365 	/*
366 	 * Just read in the whole proc.  It's not that big relative
367 	 * to the cost of the read system call.
368 	 */
369 	if (kvm_read(kd, (u_long)p->p_paddr, &kernproc, sizeof(kernproc)) !=
370 	    sizeof(kernproc))
371 		return (0);
372 	return (p->p_pid == kernproc.p_pid &&
373 	    (kernproc.p_stat != SZOMB || p->p_stat == SZOMB));
374 }
375 
376 static char **
377 kvm_doargv(kvm_t *kd, const struct miniproc *p, int nchr,
378     void (*info)(struct ps_strings *, u_long *, int *))
379 {
380 	static struct ps_strings *ps;
381 	struct ps_strings arginfo;
382 	u_long addr;
383 	char **ap;
384 	int cnt;
385 
386 	if (ps == NULL) {
387 		struct _ps_strings _ps;
388 		int mib[2];
389 		size_t len;
390 
391 		mib[0] = CTL_VM;
392 		mib[1] = VM_PSSTRINGS;
393 		len = sizeof(_ps);
394 		sysctl(mib, 2, &_ps, &len, NULL, 0);
395 		ps = (struct ps_strings *)_ps.val;
396 	}
397 
398 	/*
399 	 * Pointers are stored at the top of the user stack.
400 	 */
401 	if (p->p_stat == SZOMB ||
402 	    kvm_ureadm(kd, p, (u_long)ps, (char *)&arginfo,
403 	    sizeof(arginfo)) != sizeof(arginfo))
404 		return (0);
405 
406 	(*info)(&arginfo, &addr, &cnt);
407 	if (cnt == 0)
408 		return (0);
409 	ap = kvm_argv(kd, p, addr, cnt, nchr);
410 	/*
411 	 * For live kernels, make sure this process didn't go away.
412 	 */
413 	if (ap != 0 && ISALIVE(kd) && !proc_verify(kd, p))
414 		ap = 0;
415 	return (ap);
416 }
417 
418 static char **
419 kvm_arg_sysctl(kvm_t *kd, pid_t pid, int nchr, int env)
420 {
421 	size_t len, orglen;
422 	int mib[4], ret;
423 	char *buf;
424 
425 	orglen = env ? kd->nbpg : 8 * kd->nbpg;	/* XXX - should be ARG_MAX */
426 	if (kd->argbuf == NULL &&
427 	    (kd->argbuf = _kvm_malloc(kd, orglen)) == NULL)
428 		return (NULL);
429 
430 again:
431 	mib[0] = CTL_KERN;
432 	mib[1] = KERN_PROC_ARGS;
433 	mib[2] = (int)pid;
434 	mib[3] = env ? KERN_PROC_ENV : KERN_PROC_ARGV;
435 
436 	len = orglen;
437 	ret = (sysctl(mib, 4, kd->argbuf, &len, NULL, 0) < 0);
438 	if (ret && errno == ENOMEM) {
439 		orglen *= 2;
440 		buf = _kvm_realloc(kd, kd->argbuf, orglen);
441 		if (buf == NULL)
442 			return (NULL);
443 		kd->argbuf = buf;
444 		goto again;
445 	}
446 
447 	if (ret) {
448 		free(kd->argbuf);
449 		kd->argbuf = NULL;
450 		_kvm_syserr(kd, kd->program, "kvm_arg_sysctl");
451 		return (NULL);
452 	}
453 #if 0
454 	for (argv = (char **)kd->argbuf; *argv != NULL; argv++)
455 		if (strlen(*argv) > nchr)
456 			*argv[nchr] = '\0';
457 #endif
458 
459 	return (char **)(kd->argbuf);
460 }
461 
462 /*
463  * Get the command args.  This code is now machine independent.
464  */
465 char **
466 kvm_getargv(kvm_t *kd, const struct kinfo_proc *kp, int nchr)
467 {
468 	struct miniproc p;
469 
470 	if (ISALIVE(kd))
471 		return (kvm_arg_sysctl(kd, kp->p_pid, nchr, 0));
472 	KPTOMINI(kp, &p);
473 	return (kvm_doargv(kd, &p, nchr, ps_str_a));
474 }
475 
476 char **
477 kvm_getargv2(kvm_t *kd, const struct kinfo_proc *kp, int nchr)
478 {
479 	return (kvm_getargv(kd, kp, nchr));
480 }
481 
482 char **
483 kvm_getenvv(kvm_t *kd, const struct kinfo_proc *kp, int nchr)
484 {
485 	struct miniproc p;
486 
487 	if (ISALIVE(kd))
488 		return (kvm_arg_sysctl(kd, kp->p_pid, nchr, 1));
489 	KPTOMINI(kp, &p);
490 	return (kvm_doargv(kd, &p, nchr, ps_str_e));
491 }
492 
493 char **
494 kvm_getenvv2(kvm_t *kd, const struct kinfo_proc *kp, int nchr)
495 {
496 	return (kvm_getenvv(kd, kp, nchr));
497 }
498 
499 /*
500  * Read from user space.  The user context is given by p.
501  */
502 static ssize_t
503 kvm_ureadm(kvm_t *kd, const struct miniproc *p, u_long uva, char *buf,
504     size_t len)
505 {
506 	char *cp = buf;
507 
508 	while (len > 0) {
509 		u_long cnt;
510 		size_t cc;
511 		char *dp;
512 
513 		dp = _kvm_ureadm(kd, p, uva, &cnt);
514 		if (dp == 0) {
515 			_kvm_err(kd, 0, "invalid address (%lx)", uva);
516 			return (0);
517 		}
518 		cc = (size_t)MIN(cnt, len);
519 		bcopy(dp, cp, cc);
520 		cp += cc;
521 		uva += cc;
522 		len -= cc;
523 	}
524 	return (ssize_t)(cp - buf);
525 }
526