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