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