xref: /openbsd-src/lib/libkvm/kvm_proc.c (revision 48950c12d106c85f315112191a0228d7b83b9510)
1 /*	$OpenBSD: kvm_proc.c,v 1.48 2013/01/14 06:32:37 guenther 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 static char	*_kvm_ureadm(kvm_t *, const struct kinfo_proc *, u_long, u_long *);
100 static ssize_t	kvm_ureadm(kvm_t *, const struct kinfo_proc *, u_long, char *, size_t);
101 
102 static char	**kvm_argv(kvm_t *, const struct kinfo_proc *, u_long, int, int);
103 
104 static char	**kvm_doargv(kvm_t *, const struct kinfo_proc *, int,
105 		    void (*)(struct ps_strings *, u_long *, int *));
106 static int	proc_verify(kvm_t *, const struct kinfo_proc *);
107 static void	ps_str_a(struct ps_strings *, u_long *, int *);
108 static void	ps_str_e(struct ps_strings *, u_long *, int *);
109 
110 static char *
111 _kvm_ureadm(kvm_t *kd, const struct kinfo_proc *p, u_long va, u_long *cnt)
112 {
113 	u_long addr, offset, slot;
114 	struct vmspace vm;
115 	struct vm_anon *anonp, anon;
116 	struct vm_map_entry vme;
117 	struct vm_amap amap;
118 	struct vm_page pg;
119 
120 	if (kd->swapspc == 0) {
121 		kd->swapspc = _kvm_malloc(kd, kd->nbpg);
122 		if (kd->swapspc == 0)
123 			return (NULL);
124 	}
125 
126 	/*
127 	 * Look through the address map for the memory object
128 	 * that corresponds to the given virtual address.
129 	 */
130 	if (KREAD(kd, (u_long)p->p_vmspace, &vm))
131 		return (NULL);
132 	addr = (u_long)RB_ROOT(&vm.vm_map.addr);
133 	while (1) {
134 		if (addr == 0)
135 			return (NULL);
136 		if (KREAD(kd, addr, &vme))
137 			return (NULL);
138 
139 		if (va < vme.start)
140 			addr = (u_long)RB_LEFT(&vme, daddrs.addr_entry);
141 		else if (va >= vme.end + vme.guard + vme.fspace)
142 			addr = (u_long)RB_RIGHT(&vme, daddrs.addr_entry);
143 		else if (va >= vme.end)
144 			return (NULL);
145 		else
146 			break;
147 	}
148 
149 	/*
150 	 * we found the map entry, now to find the object...
151 	 */
152 	if (vme.aref.ar_amap == NULL)
153 		return (NULL);
154 
155 	addr = (u_long)vme.aref.ar_amap;
156 	if (KREAD(kd, addr, &amap))
157 		return (NULL);
158 
159 	offset = va - vme.start;
160 	slot = offset / kd->nbpg + vme.aref.ar_pageoff;
161 	/* sanity-check slot number */
162 	if (slot > amap.am_nslot)
163 		return (NULL);
164 
165 	addr = (u_long)amap.am_anon + (offset / kd->nbpg) * sizeof(anonp);
166 	if (KREAD(kd, addr, &anonp))
167 		return (NULL);
168 
169 	addr = (u_long)anonp;
170 	if (KREAD(kd, addr, &anon))
171 		return (NULL);
172 
173 	addr = (u_long)anon.an_page;
174 	if (addr) {
175 		if (KREAD(kd, addr, &pg))
176 			return (NULL);
177 
178 		if (_kvm_pread(kd, kd->pmfd, (void *)kd->swapspc,
179 		    (size_t)kd->nbpg, (off_t)pg.phys_addr) != kd->nbpg)
180 			return (NULL);
181 	} else {
182 		if (kd->swfd == -1 ||
183 		    _kvm_pread(kd, kd->swfd, (void *)kd->swapspc,
184 		    (size_t)kd->nbpg,
185 		    (off_t)(anon.an_swslot * kd->nbpg)) != kd->nbpg)
186 			return (NULL);
187 	}
188 
189 	/* Found the page. */
190 	offset %= kd->nbpg;
191 	*cnt = kd->nbpg - offset;
192 	return (&kd->swapspc[offset]);
193 }
194 
195 void *
196 _kvm_realloc(kvm_t *kd, void *p, size_t n)
197 {
198 	void *np = (void *)realloc(p, n);
199 
200 	if (np == 0)
201 		_kvm_err(kd, kd->program, "out of memory");
202 	return (np);
203 }
204 
205 /*
206  * Read in an argument vector from the user address space of process p.
207  * addr if the user-space base address of narg null-terminated contiguous
208  * strings.  This is used to read in both the command arguments and
209  * environment strings.  Read at most maxcnt characters of strings.
210  */
211 static char **
212 kvm_argv(kvm_t *kd, const struct kinfo_proc *p, u_long addr, int narg,
213     int maxcnt)
214 {
215 	char *np, *cp, *ep, *ap, **argv;
216 	u_long oaddr = -1;
217 	int len, cc;
218 
219 	/*
220 	 * Check that there aren't an unreasonable number of arguments,
221 	 * and that the address is in user space.
222 	 */
223 	if (narg > ARG_MAX || addr < VM_MIN_ADDRESS || addr >= VM_MAXUSER_ADDRESS)
224 		return (0);
225 
226 	if (kd->argv == 0) {
227 		/*
228 		 * Try to avoid reallocs.
229 		 */
230 		kd->argc = MAX(narg + 1, 32);
231 		kd->argv = _kvm_malloc(kd, kd->argc *
232 		    sizeof(*kd->argv));
233 		if (kd->argv == 0)
234 			return (0);
235 	} else if (narg + 1 > kd->argc) {
236 		kd->argc = MAX(2 * kd->argc, narg + 1);
237 		kd->argv = (char **)_kvm_realloc(kd, kd->argv, kd->argc *
238 		    sizeof(*kd->argv));
239 		if (kd->argv == 0)
240 			return (0);
241 	}
242 	if (kd->argspc == 0) {
243 		kd->argspc = _kvm_malloc(kd, kd->nbpg);
244 		if (kd->argspc == 0)
245 			return (0);
246 		kd->arglen = kd->nbpg;
247 	}
248 	if (kd->argbuf == 0) {
249 		kd->argbuf = _kvm_malloc(kd, kd->nbpg);
250 		if (kd->argbuf == 0)
251 			return (0);
252 	}
253 	cc = sizeof(char *) * narg;
254 	if (kvm_ureadm(kd, p, addr, (char *)kd->argv, cc) != cc)
255 		return (0);
256 	ap = np = kd->argspc;
257 	argv = kd->argv;
258 	len = 0;
259 
260 	/*
261 	 * Loop over pages, filling in the argument vector.
262 	 */
263 	while (argv < kd->argv + narg && *argv != 0) {
264 		addr = (u_long)*argv & ~(kd->nbpg - 1);
265 		if (addr != oaddr) {
266 			if (kvm_ureadm(kd, p, addr, kd->argbuf, kd->nbpg) !=
267 			    kd->nbpg)
268 				return (0);
269 			oaddr = addr;
270 		}
271 		addr = (u_long)*argv & (kd->nbpg - 1);
272 		cp = kd->argbuf + addr;
273 		cc = kd->nbpg - addr;
274 		if (maxcnt > 0 && cc > maxcnt - len)
275 			cc = maxcnt - len;
276 		ep = memchr(cp, '\0', cc);
277 		if (ep != 0)
278 			cc = ep - cp + 1;
279 		if (len + cc > kd->arglen) {
280 			int off;
281 			char **pp;
282 			char *op = kd->argspc;
283 
284 			kd->arglen *= 2;
285 			kd->argspc = (char *)_kvm_realloc(kd, kd->argspc,
286 			    kd->arglen);
287 			if (kd->argspc == 0)
288 				return (0);
289 			/*
290 			 * Adjust argv pointers in case realloc moved
291 			 * the string space.
292 			 */
293 			off = kd->argspc - op;
294 			for (pp = kd->argv; pp < argv; pp++)
295 				*pp += off;
296 			ap += off;
297 			np += off;
298 		}
299 		memcpy(np, cp, cc);
300 		np += cc;
301 		len += cc;
302 		if (ep != 0) {
303 			*argv++ = ap;
304 			ap = np;
305 		} else
306 			*argv += cc;
307 		if (maxcnt > 0 && len >= maxcnt) {
308 			/*
309 			 * We're stopping prematurely.  Terminate the
310 			 * current string.
311 			 */
312 			if (ep == 0) {
313 				*np = '\0';
314 				*argv++ = ap;
315 			}
316 			break;
317 		}
318 	}
319 	/* Make sure argv is terminated. */
320 	*argv = 0;
321 	return (kd->argv);
322 }
323 
324 static void
325 ps_str_a(struct ps_strings *p, u_long *addr, int *n)
326 {
327 	*addr = (u_long)p->ps_argvstr;
328 	*n = p->ps_nargvstr;
329 }
330 
331 static void
332 ps_str_e(struct ps_strings *p, u_long *addr, int *n)
333 {
334 	*addr = (u_long)p->ps_envstr;
335 	*n = p->ps_nenvstr;
336 }
337 
338 /*
339  * Determine if the proc indicated by p is still active.
340  * This test is not 100% foolproof in theory, but chances of
341  * being wrong are very low.
342  */
343 static int
344 proc_verify(kvm_t *kd, const struct kinfo_proc *p)
345 {
346 	struct proc kernproc;
347 
348 	/*
349 	 * Just read in the whole proc.  It's not that big relative
350 	 * to the cost of the read system call.
351 	 */
352 	if (kvm_read(kd, (u_long)p->p_paddr, &kernproc, sizeof(kernproc)) !=
353 	    sizeof(kernproc))
354 		return (0);
355 	return (p->p_pid == kernproc.p_pid &&
356 	    (kernproc.p_stat != SZOMB || p->p_stat == SZOMB));
357 }
358 
359 static char **
360 kvm_doargv(kvm_t *kd, const struct kinfo_proc *p, int nchr,
361     void (*info)(struct ps_strings *, u_long *, int *))
362 {
363 	static struct ps_strings *ps;
364 	struct ps_strings arginfo;
365 	u_long addr;
366 	char **ap;
367 	int cnt;
368 
369 	if (ps == NULL) {
370 		struct _ps_strings _ps;
371 		int mib[2];
372 		size_t len;
373 
374 		mib[0] = CTL_VM;
375 		mib[1] = VM_PSSTRINGS;
376 		len = sizeof(_ps);
377 		sysctl(mib, 2, &_ps, &len, NULL, 0);
378 		ps = (struct ps_strings *)_ps.val;
379 	}
380 
381 	/*
382 	 * Pointers are stored at the top of the user stack.
383 	 */
384 	if (p->p_stat == SZOMB ||
385 	    kvm_ureadm(kd, p, (u_long)ps, (char *)&arginfo,
386 	    sizeof(arginfo)) != sizeof(arginfo))
387 		return (0);
388 
389 	(*info)(&arginfo, &addr, &cnt);
390 	if (cnt == 0)
391 		return (0);
392 	ap = kvm_argv(kd, p, addr, cnt, nchr);
393 	/*
394 	 * For live kernels, make sure this process didn't go away.
395 	 */
396 	if (ap != 0 && ISALIVE(kd) && !proc_verify(kd, p))
397 		ap = 0;
398 	return (ap);
399 }
400 
401 static char **
402 kvm_arg_sysctl(kvm_t *kd, pid_t pid, int nchr, int env)
403 {
404 	size_t len, orglen;
405 	int mib[4], ret;
406 	char *buf;
407 
408 	orglen = env ? kd->nbpg : 8 * kd->nbpg;	/* XXX - should be ARG_MAX */
409 	if (kd->argbuf == NULL &&
410 	    (kd->argbuf = _kvm_malloc(kd, orglen)) == NULL)
411 		return (NULL);
412 
413 again:
414 	mib[0] = CTL_KERN;
415 	mib[1] = KERN_PROC_ARGS;
416 	mib[2] = (int)pid;
417 	mib[3] = env ? KERN_PROC_ENV : KERN_PROC_ARGV;
418 
419 	len = orglen;
420 	ret = (sysctl(mib, 4, kd->argbuf, &len, NULL, 0) < 0);
421 	if (ret && errno == ENOMEM) {
422 		orglen *= 2;
423 		buf = _kvm_realloc(kd, kd->argbuf, orglen);
424 		if (buf == NULL)
425 			return (NULL);
426 		kd->argbuf = buf;
427 		goto again;
428 	}
429 
430 	if (ret) {
431 		free(kd->argbuf);
432 		kd->argbuf = NULL;
433 		_kvm_syserr(kd, kd->program, "kvm_arg_sysctl");
434 		return (NULL);
435 	}
436 #if 0
437 	for (argv = (char **)kd->argbuf; *argv != NULL; argv++)
438 		if (strlen(*argv) > nchr)
439 			*argv[nchr] = '\0';
440 #endif
441 
442 	return (char **)(kd->argbuf);
443 }
444 
445 /*
446  * Get the command args.  This code is now machine independent.
447  */
448 char **
449 kvm_getargv(kvm_t *kd, const struct kinfo_proc *kp, int nchr)
450 {
451 	if (ISALIVE(kd))
452 		return (kvm_arg_sysctl(kd, kp->p_pid, nchr, 0));
453 	return (kvm_doargv(kd, kp, nchr, ps_str_a));
454 }
455 
456 char **
457 kvm_getenvv(kvm_t *kd, const struct kinfo_proc *kp, int nchr)
458 {
459 	if (ISALIVE(kd))
460 		return (kvm_arg_sysctl(kd, kp->p_pid, nchr, 1));
461 	return (kvm_doargv(kd, kp, nchr, ps_str_e));
462 }
463 
464 /*
465  * Read from user space.  The user context is given by p.
466  */
467 static ssize_t
468 kvm_ureadm(kvm_t *kd, const struct kinfo_proc *p, u_long uva, char *buf,
469     size_t len)
470 {
471 	char *cp = buf;
472 
473 	while (len > 0) {
474 		u_long cnt;
475 		size_t cc;
476 		char *dp;
477 
478 		dp = _kvm_ureadm(kd, p, uva, &cnt);
479 		if (dp == 0) {
480 			_kvm_err(kd, 0, "invalid address (%lx)", uva);
481 			return (0);
482 		}
483 		cc = (size_t)MIN(cnt, len);
484 		bcopy(dp, cp, cc);
485 		cp += cc;
486 		uva += cc;
487 		len -= cc;
488 	}
489 	return (ssize_t)(cp - buf);
490 }
491