xref: /dragonfly/lib/libkvm/kvm_proc.c (revision d14dcb45)
1 /*-
2  * Copyright (c) 1989, 1992, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software developed by the Computer Systems
6  * Engineering group at Lawrence Berkeley Laboratory under DARPA contract
7  * BG 91-66 and contributed to Berkeley.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * $FreeBSD: src/lib/libkvm/kvm_proc.c,v 1.25.2.3 2002/08/24 07:27:46 kris Exp $
34  *
35  * @(#)kvm_proc.c	8.3 (Berkeley) 9/23/93
36  */
37 
38 /*
39  * Proc traversal interface for kvm.  ps and w are (probably) the exclusive
40  * users of this code, so we've factored it out into a separate module.
41  * Thus, we keep this grunge out of the other kvm applications (i.e.,
42  * most other applications are interested only in open/close/read/nlist).
43  */
44 
45 #include <sys/user.h>	/* MUST BE FIRST */
46 #include <sys/conf.h>
47 #include <sys/param.h>
48 #include <sys/proc.h>
49 #include <sys/exec.h>
50 #include <sys/stat.h>
51 #include <sys/globaldata.h>
52 #include <sys/ioctl.h>
53 #include <sys/tty.h>
54 #include <sys/file.h>
55 #include <sys/jail.h>
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <stddef.h>
59 #include <unistd.h>
60 #include <nlist.h>
61 
62 #include <cpu/pmap.h>
63 #include <vm/vm.h>
64 #include <vm/vm_param.h>
65 #include <vm/swap_pager.h>
66 
67 #include <sys/sysctl.h>
68 
69 #include <limits.h>
70 #include <memory.h>
71 #include <paths.h>
72 
73 #include "kvm.h"
74 #include "kvm_private.h"
75 
76 dev_t	dev2udev(cdev_t dev);
77 
78 #define KREAD(kd, addr, obj) \
79 	(kvm_read(kd, addr, (char *)(obj), sizeof(*obj)) != sizeof(*obj))
80 #define KREADSTR(kd, addr) \
81 	kvm_readstr(kd, (u_long)addr, NULL, NULL)
82 
83 static struct kinfo_proc *
84 kinfo_resize_proc(kvm_t *kd, struct kinfo_proc *bp)
85 {
86 	if (bp < kd->procend)
87 		return bp;
88 
89 	size_t pos = bp - kd->procend;
90 	size_t size = kd->procend - kd->procbase;
91 
92 	if (size == 0)
93 		size = 8;
94 	else
95 		size *= 2;
96 	kd->procbase = _kvm_realloc(kd, kd->procbase, sizeof(*bp) * size);
97 	if (kd->procbase == NULL)
98 		return NULL;
99 	kd->procend = kd->procbase + size;
100 	bp = kd->procbase + pos;
101 	return bp;
102 }
103 
104 /*
105  * note: this function is also used by /usr/src/sys/kern/kern_kinfo.c as
106  * compiled by userland.
107  */
108 dev_t
109 dev2udev(cdev_t dev)
110 {
111 	if (dev == NULL)
112 		return NOUDEV;
113 	if ((dev->si_umajor & 0xffffff00) ||
114 	    (dev->si_uminor & 0x0000ff00)) {
115 		return NOUDEV;
116 	}
117 	return((dev->si_umajor << 8) | dev->si_uminor);
118 }
119 
120 /*
121  * Helper routine which traverses the left hand side of a red-black sub-tree.
122  */
123 static uintptr_t
124 kvm_lwptraverse(kvm_t *kd, struct lwp *lwp, uintptr_t lwppos)
125 {
126 	for (;;) {
127 		if (KREAD(kd, lwppos, lwp)) {
128 			_kvm_err(kd, kd->program, "can't read lwp at %p",
129 				 (void *)lwppos);
130 			return ((uintptr_t)-1);
131 		}
132 		if (lwp->u.lwp_rbnode.rbe_left == NULL)
133 			break;
134 		lwppos = (uintptr_t)lwp->u.lwp_rbnode.rbe_left;
135 	}
136 	return(lwppos);
137 }
138 
139 /*
140  * Iterate LWPs in a process.
141  *
142  * The first lwp in a red-black tree is a left-side traversal of the tree.
143  */
144 static uintptr_t
145 kvm_firstlwp(kvm_t *kd, struct lwp *lwp, struct proc *proc)
146 {
147 	return(kvm_lwptraverse(kd, lwp, (uintptr_t)proc->p_lwp_tree.rbh_root));
148 }
149 
150 /*
151  * If the current element is the left side of the parent the next element
152  * will be a left side traversal of the parent's right side.  If the parent
153  * has no right side the next element will be the parent.
154  *
155  * If the current element is the right side of the parent the next element
156  * is the parent.
157  *
158  * If the parent is NULL we are done.
159  */
160 static uintptr_t
161 kvm_nextlwp(kvm_t *kd, uintptr_t lwppos, struct lwp *lwp)
162 {
163 	uintptr_t nextpos;
164 
165 	nextpos = (uintptr_t)lwp->u.lwp_rbnode.rbe_parent;
166 	if (nextpos) {
167 		if (KREAD(kd, nextpos, lwp)) {
168 			_kvm_err(kd, kd->program, "can't read lwp at %p",
169 				 (void *)lwppos);
170 			return ((uintptr_t)-1);
171 		}
172 		if (lwppos == (uintptr_t)lwp->u.lwp_rbnode.rbe_left) {
173 			/*
174 			 * If we had gone down the left side the next element
175 			 * is a left hand traversal of the parent's right
176 			 * side, or the parent itself if there is no right
177 			 * side.
178 			 */
179 			lwppos = (uintptr_t)lwp->u.lwp_rbnode.rbe_right;
180 			if (lwppos)
181 				nextpos = kvm_lwptraverse(kd, lwp, lwppos);
182 		} else {
183 			/*
184 			 * If we had gone down the right side the next
185 			 * element is the parent.
186 			 */
187 			/* nextpos = nextpos */
188 		}
189 	}
190 	return(nextpos);
191 }
192 
193 /*
194  * Read proc's from memory file into buffer bp, which has space to hold
195  * at most maxcnt procs.
196  */
197 static int
198 kvm_proclist(kvm_t *kd, int what, int arg, struct proc *p,
199 	     struct kinfo_proc *bp)
200 {
201 	struct pgrp pgrp;
202 	struct pgrp tpgrp;
203 	struct globaldata gdata;
204 	struct session sess;
205 	struct session tsess;
206 	struct tty tty;
207 	struct proc proc;
208 	struct ucred ucred;
209 	struct thread thread;
210 	struct proc pproc;
211 	struct cdev cdev;
212 	struct vmspace vmspace;
213 	struct prison prison;
214 	struct sigacts sigacts;
215 	struct lwp lwp;
216 	uintptr_t lwppos;
217 	int count;
218 	char *wmesg;
219 
220 	count = 0;
221 
222 	for (; p != NULL; p = proc.p_list.le_next) {
223 		if (KREAD(kd, (u_long)p, &proc)) {
224 			_kvm_err(kd, kd->program, "can't read proc at %p", p);
225 			return (-1);
226 		}
227 		if (KREAD(kd, (u_long)proc.p_ucred, &ucred)) {
228 			_kvm_err(kd, kd->program, "can't read ucred at %p",
229 				 proc.p_ucred);
230 			return (-1);
231 		}
232 		proc.p_ucred = &ucred;
233 
234 		switch(what & ~KERN_PROC_FLAGMASK) {
235 
236 		case KERN_PROC_PID:
237 			if (proc.p_pid != (pid_t)arg)
238 				continue;
239 			break;
240 
241 		case KERN_PROC_UID:
242 			if (ucred.cr_uid != (uid_t)arg)
243 				continue;
244 			break;
245 
246 		case KERN_PROC_RUID:
247 			if (ucred.cr_ruid != (uid_t)arg)
248 				continue;
249 			break;
250 		}
251 
252 		if (KREAD(kd, (u_long)proc.p_pgrp, &pgrp)) {
253 			_kvm_err(kd, kd->program, "can't read pgrp at %p",
254 				 proc.p_pgrp);
255 			return (-1);
256 		}
257 		proc.p_pgrp = &pgrp;
258 		if (proc.p_pptr) {
259 		  if (KREAD(kd, (u_long)proc.p_pptr, &pproc)) {
260 			_kvm_err(kd, kd->program, "can't read pproc at %p",
261 				 proc.p_pptr);
262 			return (-1);
263 		  }
264 		  proc.p_pptr = &pproc;
265 		}
266 
267 		if (proc.p_sigacts) {
268 			if (KREAD(kd, (u_long)proc.p_sigacts, &sigacts)) {
269 				_kvm_err(kd, kd->program,
270 					 "can't read sigacts at %p",
271 					 proc.p_sigacts);
272 				return (-1);
273 			}
274 			proc.p_sigacts = &sigacts;
275 		}
276 
277 		if (KREAD(kd, (u_long)pgrp.pg_session, &sess)) {
278 			_kvm_err(kd, kd->program, "can't read session at %p",
279 				pgrp.pg_session);
280 			return (-1);
281 		}
282 		pgrp.pg_session = &sess;
283 
284 		if ((proc.p_flags & P_CONTROLT) && sess.s_ttyp != NULL) {
285 			if (KREAD(kd, (u_long)sess.s_ttyp, &tty)) {
286 				_kvm_err(kd, kd->program,
287 					 "can't read tty at %p", sess.s_ttyp);
288 				return (-1);
289 			}
290 			sess.s_ttyp = &tty;
291 			if (tty.t_dev != NULL) {
292 				if (KREAD(kd, (u_long)tty.t_dev, &cdev))
293 					tty.t_dev = NULL;
294 				else
295 					tty.t_dev = &cdev;
296 			}
297 			if (tty.t_pgrp != NULL) {
298 				if (KREAD(kd, (u_long)tty.t_pgrp, &tpgrp)) {
299 					_kvm_err(kd, kd->program,
300 						 "can't read tpgrp at %p",
301 						tty.t_pgrp);
302 					return (-1);
303 				}
304 				tty.t_pgrp = &tpgrp;
305 			}
306 			if (tty.t_session != NULL) {
307 				if (KREAD(kd, (u_long)tty.t_session, &tsess)) {
308 					_kvm_err(kd, kd->program,
309 						 "can't read tsess at %p",
310 						tty.t_session);
311 					return (-1);
312 				}
313 				tty.t_session = &tsess;
314 			}
315 		}
316 
317 		if (KREAD(kd, (u_long)proc.p_vmspace, &vmspace)) {
318 			_kvm_err(kd, kd->program, "can't read vmspace at %p",
319 				 proc.p_vmspace);
320 			return (-1);
321 		}
322 		proc.p_vmspace = &vmspace;
323 
324 		if (ucred.cr_prison != NULL) {
325 			if (KREAD(kd, (u_long)ucred.cr_prison, &prison)) {
326 				_kvm_err(kd, kd->program, "can't read prison at %p",
327 					 ucred.cr_prison);
328 				return (-1);
329 			}
330 			ucred.cr_prison = &prison;
331 		}
332 
333 		switch (what & ~KERN_PROC_FLAGMASK) {
334 
335 		case KERN_PROC_PGRP:
336 			if (proc.p_pgrp->pg_id != (pid_t)arg)
337 				continue;
338 			break;
339 
340 		case KERN_PROC_TTY:
341 			if ((proc.p_flags & P_CONTROLT) == 0 ||
342 			    dev2udev(proc.p_pgrp->pg_session->s_ttyp->t_dev)
343 					!= (dev_t)arg)
344 				continue;
345 			break;
346 		}
347 
348 		if ((bp = kinfo_resize_proc(kd, bp)) == NULL)
349 			return (-1);
350 		fill_kinfo_proc(&proc, bp);
351 		bp->kp_paddr = (uintptr_t)p;
352 
353 		lwppos = kvm_firstlwp(kd, &lwp, &proc);
354 		if (lwppos == 0) {
355 			bp++;		/* Just export the proc then */
356 			count++;
357 		}
358 		while (lwppos && lwppos != (uintptr_t)-1) {
359 			if (p != lwp.lwp_proc) {
360 				_kvm_err(kd, kd->program, "lwp has wrong parent");
361 				return (-1);
362 			}
363 			lwp.lwp_proc = &proc;
364 			if (KREAD(kd, (u_long)lwp.lwp_thread, &thread)) {
365 				_kvm_err(kd, kd->program, "can't read thread at %p",
366 				    lwp.lwp_thread);
367 				return (-1);
368 			}
369 			lwp.lwp_thread = &thread;
370 
371 			if (thread.td_gd) {
372 				if (KREAD(kd, (u_long)thread.td_gd, &gdata)) {
373 					_kvm_err(kd, kd->program, "can't read"
374 						  " gd at %p",
375 						  thread.td_gd);
376 					return(-1);
377 				}
378 				thread.td_gd = &gdata;
379 			}
380 			if (thread.td_wmesg) {
381 				wmesg = (void *)KREADSTR(kd, thread.td_wmesg);
382 				if (wmesg == NULL) {
383 					_kvm_err(kd, kd->program, "can't read"
384 						  " wmesg %p",
385 						  thread.td_wmesg);
386 					return(-1);
387 				}
388 				thread.td_wmesg = wmesg;
389 			} else {
390 				wmesg = NULL;
391 			}
392 
393 			if ((bp = kinfo_resize_proc(kd, bp)) == NULL)
394 				return (-1);
395 			fill_kinfo_proc(&proc, bp);
396 			fill_kinfo_lwp(&lwp, &bp->kp_lwp);
397 			bp->kp_paddr = (uintptr_t)p;
398 			bp++;
399 			count++;
400 			if (wmesg)
401 				free(wmesg);
402 			if ((what & KERN_PROC_FLAG_LWP) == 0)
403 				break;
404 			lwppos = kvm_nextlwp(kd, lwppos, &lwp);
405 		}
406 		if (lwppos == (uintptr_t)-1)
407 			return(-1);
408 	}
409 	return (count);
410 }
411 
412 /*
413  * Build proc info array by reading in proc list from a crash dump.
414  * We reallocate kd->procbase as necessary.
415  */
416 static int
417 kvm_deadprocs(kvm_t *kd, int what, int arg, int allproc_hsize)
418 {
419 	struct kinfo_proc *bp;
420 	struct proc *p;
421 	struct proclist **pl;
422 	int cnt, partcnt, n;
423 	u_long nextoff;
424 	u_long a_allproc;
425 
426 	cnt = partcnt = 0;
427 	nextoff = 0;
428 
429 	/*
430 	 * Dynamically allocate space for all the elements of the
431 	 * allprocs array and KREAD() them.
432 	 */
433 	pl = _kvm_malloc(kd, allproc_hsize * sizeof(struct proclist *));
434 	for (n = 0; n < allproc_hsize; n++) {
435 		pl[n] = _kvm_malloc(kd, sizeof(struct proclist));
436 		a_allproc = sizeof(struct procglob) * n +
437 			    offsetof(struct procglob, allproc);
438 		nextoff = a_allproc;
439 		if (KREAD(kd, (u_long)nextoff, pl[n])) {
440 			_kvm_err(kd, kd->program, "can't read proclist at 0x%lx",
441 				a_allproc);
442 			return (-1);
443 		}
444 
445 		/* Ignore empty proclists */
446 		if (LIST_EMPTY(pl[n]))
447 			continue;
448 
449 		bp = kd->procbase + cnt;
450 		p = pl[n]->lh_first;
451 		partcnt = kvm_proclist(kd, what, arg, p, bp);
452 		if (partcnt < 0) {
453 			free(pl[n]);
454 			return (partcnt);
455 		}
456 
457 		cnt += partcnt;
458 		free(pl[n]);
459 	}
460 
461 	return (cnt);
462 }
463 
464 struct kinfo_proc *
465 kvm_getprocs(kvm_t *kd, int op, int arg, int *cnt)
466 {
467 	int mib[4], st, nprocs, allproc_hsize;
468 	int miblen = ((op & ~KERN_PROC_FLAGMASK) == KERN_PROC_ALL) ? 3 : 4;
469 	size_t size;
470 
471 	if (kd->procbase != NULL) {
472 		free(kd->procbase);
473 		kd->procbase = NULL;
474 	}
475 	if (kvm_ishost(kd)) {
476 		size = 0;
477 		mib[0] = CTL_KERN;
478 		mib[1] = KERN_PROC;
479 		mib[2] = op;
480 		mib[3] = arg;
481 		st = sysctl(mib, miblen, NULL, &size, NULL, 0);
482 		if (st == -1) {
483 			_kvm_syserr(kd, kd->program, "kvm_getprocs");
484 			return (0);
485 		}
486 		do {
487 			size += size / 10;
488 			kd->procbase = (struct kinfo_proc *)
489 			    _kvm_realloc(kd, kd->procbase, size);
490 			if (kd->procbase == 0)
491 				return (0);
492 			st = sysctl(mib, miblen, kd->procbase, &size, NULL, 0);
493 		} while (st == -1 && errno == ENOMEM);
494 		if (st == -1) {
495 			_kvm_syserr(kd, kd->program, "kvm_getprocs");
496 			return (0);
497 		}
498 		if (size % sizeof(struct kinfo_proc) != 0) {
499 			_kvm_err(kd, kd->program,
500 				"proc size mismatch (%zd total, %zd chunks)",
501 				size, sizeof(struct kinfo_proc));
502 			return (0);
503 		}
504 		nprocs = size / sizeof(struct kinfo_proc);
505 	} else {
506 		struct nlist nl[4], *p;
507 
508 		nl[0].n_name = "_nprocs";
509 		nl[1].n_name = "_procglob";
510 		nl[2].n_name = "_allproc_hsize";
511 		nl[3].n_name = 0;
512 
513 		if (kvm_nlist(kd, nl) != 0) {
514 			for (p = nl; p->n_type != 0; ++p)
515 				;
516 			_kvm_err(kd, kd->program,
517 				 "%s: no such symbol", p->n_name);
518 			return (0);
519 		}
520 		if (KREAD(kd, nl[0].n_value, &nprocs)) {
521 			_kvm_err(kd, kd->program, "can't read nprocs");
522 			return (0);
523 		}
524 		if (KREAD(kd, nl[2].n_value, &allproc_hsize)) {
525 			_kvm_err(kd, kd->program, "can't read allproc_hsize");
526 			return (0);
527 		}
528 		nprocs = kvm_deadprocs(kd, op, arg, allproc_hsize);
529 #ifdef notdef
530 		size = nprocs * sizeof(struct kinfo_proc);
531 		(void)realloc(kd->procbase, size);
532 #endif
533 	}
534 	*cnt = nprocs;
535 	return (kd->procbase);
536 }
537 
538 void
539 _kvm_freeprocs(kvm_t *kd)
540 {
541 	if (kd->procbase) {
542 		free(kd->procbase);
543 		kd->procbase = 0;
544 	}
545 }
546 
547 void *
548 _kvm_realloc(kvm_t *kd, void *p, size_t n)
549 {
550 	void *np = (void *)realloc(p, n);
551 
552 	if (np == NULL) {
553 		free(p);
554 		_kvm_err(kd, kd->program, "out of memory");
555 	}
556 	return (np);
557 }
558 
559 #ifndef MAX
560 #define MAX(a, b) ((a) > (b) ? (a) : (b))
561 #endif
562 
563 /*
564  * Read in an argument vector from the user address space of process pid.
565  * addr if the user-space base address of narg null-terminated contiguous
566  * strings.  This is used to read in both the command arguments and
567  * environment strings.  Read at most maxcnt characters of strings.
568  */
569 static char **
570 kvm_argv(kvm_t *kd, pid_t pid, u_long addr, int narg, int maxcnt)
571 {
572 	char *np, *cp, *ep, *ap;
573 	u_long oaddr = -1;
574 	u_long addr_min = VM_MIN_USER_ADDRESS;
575 	u_long addr_max = VM_MAX_USER_ADDRESS;
576 	int len, cc;
577 	char **argv;
578 
579 	/*
580 	 * Check that there aren't an unreasonable number of agruments,
581 	 * and that the address is in user space.
582 	 */
583 	if (narg > 512 || addr < addr_min || addr >= addr_max)
584 		return (0);
585 
586 	/*
587 	 * kd->argv : work space for fetching the strings from the target
588 	 *            process's space, and is converted for returning to caller
589 	 */
590 	if (kd->argv == 0) {
591 		/*
592 		 * Try to avoid reallocs.
593 		 */
594 		kd->argc = MAX(narg + 1, 32);
595 		kd->argv = (char **)_kvm_malloc(kd, kd->argc *
596 						sizeof(*kd->argv));
597 		if (kd->argv == 0)
598 			return (0);
599 	} else if (narg + 1 > kd->argc) {
600 		kd->argc = MAX(2 * kd->argc, narg + 1);
601 		kd->argv = (char **)_kvm_realloc(kd, kd->argv, kd->argc *
602 						sizeof(*kd->argv));
603 		if (kd->argv == 0)
604 			return (0);
605 	}
606 	/*
607 	 * kd->argspc : returned to user, this is where the kd->argv
608 	 *              arrays are left pointing to the collected strings.
609 	 */
610 	if (kd->argspc == 0) {
611 		kd->argspc = (char *)_kvm_malloc(kd, PAGE_SIZE);
612 		if (kd->argspc == 0)
613 			return (0);
614 		kd->arglen = PAGE_SIZE;
615 	}
616 	/*
617 	 * kd->argbuf : used to pull in pages from the target process.
618 	 *              the strings are copied out of here.
619 	 */
620 	if (kd->argbuf == 0) {
621 		kd->argbuf = (char *)_kvm_malloc(kd, PAGE_SIZE);
622 		if (kd->argbuf == 0)
623 			return (0);
624 	}
625 
626 	/* Pull in the target process'es argv vector */
627 	cc = sizeof(char *) * narg;
628 	if (kvm_uread(kd, pid, addr, (char *)kd->argv, cc) != cc)
629 		return (0);
630 	/*
631 	 * ap : saved start address of string we're working on in kd->argspc
632 	 * np : pointer to next place to write in kd->argspc
633 	 * len: length of data in kd->argspc
634 	 * argv: pointer to the argv vector that we are hunting around the
635 	 *       target process space for, and converting to addresses in
636 	 *       our address space (kd->argspc).
637 	 */
638 	ap = np = kd->argspc;
639 	argv = kd->argv;
640 	len = 0;
641 	/*
642 	 * Loop over pages, filling in the argument vector.
643 	 * Note that the argv strings could be pointing *anywhere* in
644 	 * the user address space and are no longer contiguous.
645 	 * Note that *argv is modified when we are going to fetch a string
646 	 * that crosses a page boundary.  We copy the next part of the string
647 	 * into to "np" and eventually convert the pointer.
648 	 */
649 	while (argv < kd->argv + narg && *argv != NULL) {
650 
651 		/* get the address that the current argv string is on */
652 		addr = rounddown2((u_long)*argv, PAGE_SIZE);
653 
654 		/* is it the same page as the last one? */
655 		if (addr != oaddr) {
656 			if (kvm_uread(kd, pid, addr, kd->argbuf, PAGE_SIZE) !=
657 			    PAGE_SIZE)
658 				return (0);
659 			oaddr = addr;
660 		}
661 
662 		/* offset within the page... kd->argbuf */
663 		addr = (u_long)*argv & (PAGE_SIZE - 1);
664 
665 		/* cp = start of string, cc = count of chars in this chunk */
666 		cp = kd->argbuf + addr;
667 		cc = PAGE_SIZE - addr;
668 
669 		/* dont get more than asked for by user process */
670 		if (maxcnt > 0 && cc > maxcnt - len)
671 			cc = maxcnt - len;
672 
673 		/* pointer to end of string if we found it in this page */
674 		ep = memchr(cp, '\0', cc);
675 		if (ep != NULL)
676 			cc = ep - cp + 1;
677 		/*
678 		 * at this point, cc is the count of the chars that we are
679 		 * going to retrieve this time. we may or may not have found
680 		 * the end of it.  (ep points to the null if the end is known)
681 		 */
682 
683 		/* will we exceed the malloc/realloced buffer? */
684 		if (len + cc > kd->arglen) {
685 			size_t off;
686 			char **pp;
687 			char *op = kd->argspc;
688 
689 			kd->arglen *= 2;
690 			kd->argspc = (char *)_kvm_realloc(kd, kd->argspc,
691 							  kd->arglen);
692 			if (kd->argspc == 0)
693 				return (0);
694 			/*
695 			 * Adjust argv pointers in case realloc moved
696 			 * the string space.
697 			 */
698 			off = kd->argspc - op;
699 			for (pp = kd->argv; pp < argv; pp++)
700 				*pp += off;
701 			ap += off;
702 			np += off;
703 		}
704 		/* np = where to put the next part of the string in kd->argspc*/
705 		/* np is kinda redundant.. could use "kd->argspc + len" */
706 		memcpy(np, cp, cc);
707 		np += cc;	/* inc counters */
708 		len += cc;
709 
710 		/*
711 		 * if end of string found, set the *argv pointer to the
712 		 * saved beginning of string, and advance. argv points to
713 		 * somewhere in kd->argv..  This is initially relative
714 		 * to the target process, but when we close it off, we set
715 		 * it to point in our address space.
716 		 */
717 		if (ep != NULL) {
718 			*argv++ = ap;
719 			ap = np;
720 		} else {
721 			/* update the address relative to the target process */
722 			*argv += cc;
723 		}
724 
725 		if (maxcnt > 0 && len >= maxcnt) {
726 			/*
727 			 * We're stopping prematurely.  Terminate the
728 			 * current string.
729 			 */
730 			if (ep == NULL) {
731 				*np = '\0';
732 				*argv++ = ap;
733 			}
734 			break;
735 		}
736 	}
737 	/* Make sure argv is terminated. */
738 	*argv = NULL;
739 	return (kd->argv);
740 }
741 
742 static void
743 ps_str_a(struct ps_strings *p, u_long *addr, int *n)
744 {
745 	*addr = (u_long)p->ps_argvstr;
746 	*n = p->ps_nargvstr;
747 }
748 
749 static void
750 ps_str_e(struct ps_strings *p, u_long *addr, int *n)
751 {
752 	*addr = (u_long)p->ps_envstr;
753 	*n = p->ps_nenvstr;
754 }
755 
756 /*
757  * Determine if the proc indicated by p is still active.
758  * This test is not 100% foolproof in theory, but chances of
759  * being wrong are very low.
760  */
761 static int
762 proc_verify(const struct kinfo_proc *p)
763 {
764 	struct kinfo_proc kp;
765 	int mib[4];
766 	size_t len;
767 	int error;
768 
769 	mib[0] = CTL_KERN;
770 	mib[1] = KERN_PROC;
771 	mib[2] = KERN_PROC_PID;
772 	mib[3] = p->kp_pid;
773 
774 	len = sizeof(kp);
775 	error = sysctl(mib, 4, &kp, &len, NULL, 0);
776 	if (error)
777 		return (0);
778 
779 	error = (p->kp_pid == kp.kp_pid &&
780 	    (kp.kp_stat != SZOMB || p->kp_stat == SZOMB));
781 	return (error);
782 }
783 
784 static char **
785 kvm_doargv(kvm_t *kd, const struct kinfo_proc *kp, int nchr,
786 	   void (*info)(struct ps_strings *, u_long *, int *))
787 {
788 	char **ap;
789 	u_long addr;
790 	int cnt;
791 	static struct ps_strings arginfo;
792 	static u_long ps_strings;
793 	size_t len;
794 
795 	if (ps_strings == 0) {
796 		len = sizeof(ps_strings);
797 		if (sysctlbyname("kern.ps_strings", &ps_strings, &len, NULL,
798 		    0) == -1)
799 			ps_strings = PS_STRINGS;
800 	}
801 
802 	/*
803 	 * Pointers are stored at the top of the user stack.
804 	 */
805 	if (kp->kp_stat == SZOMB ||
806 	    kvm_uread(kd, kp->kp_pid, ps_strings, (char *)&arginfo,
807 		      sizeof(arginfo)) != sizeof(arginfo))
808 		return (0);
809 
810 	(*info)(&arginfo, &addr, &cnt);
811 	if (cnt == 0)
812 		return (0);
813 	ap = kvm_argv(kd, kp->kp_pid, addr, cnt, nchr);
814 	/*
815 	 * For live kernels, make sure this process didn't go away.
816 	 */
817 	if (ap != NULL && (kvm_ishost(kd) || kvm_isvkernel(kd)) &&
818 	    !proc_verify(kp))
819 		ap = NULL;
820 	return (ap);
821 }
822 
823 /*
824  * Get the command args.  This code is now machine independent.
825  */
826 char **
827 kvm_getargv(kvm_t *kd, const struct kinfo_proc *kp, int nchr)
828 {
829 	int oid[8];
830 	int i;
831 	size_t bufsz;
832 	static unsigned long buflen;
833 	static char *buf, *p;
834 	static char **bufp;
835 	static int argc;
836 
837 	if (!kvm_ishost(kd)) { /* XXX: vkernels */
838 		_kvm_err(kd, kd->program,
839 		    "cannot read user space from dead kernel");
840 		return (0);
841 	}
842 
843 	if (!buflen) {
844 		bufsz = sizeof(buflen);
845 		i = sysctlbyname("kern.ps_arg_cache_limit",
846 				 &buflen, &bufsz, NULL, 0);
847 		if (i == -1) {
848 			buflen = 0;
849 		} else {
850 			buf = malloc(buflen);
851 			if (buf == NULL)
852 				buflen = 0;
853 			argc = 32;
854 			bufp = malloc(sizeof(char *) * argc);
855 		}
856 	}
857 	if (buf != NULL) {
858 		oid[0] = CTL_KERN;
859 		oid[1] = KERN_PROC;
860 		oid[2] = KERN_PROC_ARGS;
861 		oid[3] = kp->kp_pid;
862 		oid[4] = kp->kp_lwp.kl_tid;
863 
864 		/*
865 		 * sysctl can take a pid in 5.7 or earlier.  In late
866 		 * 5.7 the sysctl can take a pid (4 args) or pid + tid
867 		 * (5 args).
868 		 */
869 		i = -1;
870 		if (kp->kp_lwp.kl_tid > 0) {
871 			bufsz = buflen;
872 			i = sysctl(oid, 5, buf, &bufsz, 0, 0);
873 		}
874 		if (i < 0) {
875 			bufsz = buflen;
876 			i = sysctl(oid, 4, buf, &bufsz, 0, 0);
877 		}
878 
879 		if (i == 0 && bufsz > 0) {
880 			i = 0;
881 			p = buf;
882 			do {
883 				bufp[i++] = p;
884 				p += strlen(p) + 1;
885 				if (i >= argc) {
886 					argc += argc;
887 					bufp = realloc(bufp,
888 					    sizeof(char *) * argc);
889 				}
890 			} while (p < buf + bufsz);
891 			bufp[i++] = NULL;
892 			return (bufp);
893 		}
894 	}
895 	if (kp->kp_flags & P_SYSTEM)
896 		return (NULL);
897 	return (kvm_doargv(kd, kp, nchr, ps_str_a));
898 }
899 
900 char **
901 kvm_getenvv(kvm_t *kd, const struct kinfo_proc *kp, int nchr)
902 {
903 	return (kvm_doargv(kd, kp, nchr, ps_str_e));
904 }
905 
906 /*
907  * Read from user space.  The user context is given by pid.
908  */
909 ssize_t
910 kvm_uread(kvm_t *kd, pid_t pid, u_long uva, char *buf, size_t len)
911 {
912 	char *cp;
913 	char procfile[MAXPATHLEN];
914 	ssize_t amount;
915 	int fd;
916 
917 	if (!kvm_ishost(kd)) { /* XXX: vkernels */
918 		_kvm_err(kd, kd->program,
919 		    "cannot read user space from dead kernel");
920 		return (0);
921 	}
922 
923 	sprintf(procfile, "/proc/%d/mem", pid);
924 	fd = open(procfile, O_RDONLY, 0);
925 	if (fd < 0) {
926 		_kvm_err(kd, kd->program, "cannot open %s", procfile);
927 		close(fd);
928 		return (0);
929 	}
930 
931 	cp = buf;
932 	while (len > 0) {
933 		errno = 0;
934 		if (lseek(fd, (off_t)uva, 0) == -1 && errno != 0) {
935 			_kvm_err(kd, kd->program, "invalid address (%lx) in %s",
936 			    uva, procfile);
937 			break;
938 		}
939 		amount = read(fd, cp, len);
940 		if (amount < 0) {
941 			_kvm_syserr(kd, kd->program, "error reading %s",
942 			    procfile);
943 			break;
944 		}
945 		if (amount == 0) {
946 			_kvm_err(kd, kd->program, "EOF reading %s", procfile);
947 			break;
948 		}
949 		cp += amount;
950 		uva += amount;
951 		len -= amount;
952 	}
953 
954 	close(fd);
955 	return ((ssize_t)(cp - buf));
956 }
957