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