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