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