xref: /freebsd/lib/libkvm/kvm_proc.c (revision 0b87f79976047c8f4332bbf7dc03146f6b0de79f)
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. All advertising materials mentioning features or use of this software
18  *    must display the following acknowledgement:
19  *	This product includes software developed by the University of
20  *	California, Berkeley and its contributors.
21  * 4. Neither the name of the University nor the names of its contributors
22  *    may be used to endorse or promote products derived from this software
23  *    without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  *
37  * $FreeBSD$
38  */
39 
40 #include <sys/cdefs.h>
41 __FBSDID("$FreeBSD$");
42 
43 #if defined(LIBC_SCCS) && !defined(lint)
44 static char sccsid[] = "@(#)kvm_proc.c	8.3 (Berkeley) 9/23/93";
45 #endif /* LIBC_SCCS and not lint */
46 
47 /*
48  * Proc traversal interface for kvm.  ps and w are (probably) the exclusive
49  * users of this code, so we've factored it out into a separate module.
50  * Thus, we keep this grunge out of the other kvm applications (i.e.,
51  * most other applications are interested only in open/close/read/nlist).
52  */
53 
54 #include <sys/param.h>
55 #include <sys/user.h>
56 #include <sys/proc.h>
57 #include <sys/exec.h>
58 #include <sys/stat.h>
59 #include <sys/ioctl.h>
60 #include <sys/tty.h>
61 #include <sys/file.h>
62 #include <stdio.h>
63 #include <stdlib.h>
64 #include <unistd.h>
65 #include <nlist.h>
66 #include <kvm.h>
67 
68 #include <vm/vm.h>
69 #include <vm/vm_param.h>
70 #include <vm/swap_pager.h>
71 
72 #include <sys/sysctl.h>
73 
74 #include <limits.h>
75 #include <memory.h>
76 #include <paths.h>
77 
78 #include "kvm_private.h"
79 
80 #if used
81 static char *
82 kvm_readswap(kd, p, va, cnt)
83 	kvm_t *kd;
84 	const struct proc *p;
85 	u_long va;
86 	u_long *cnt;
87 {
88 #ifdef __FreeBSD__
89 	/* XXX Stubbed out, our vm system is differnet */
90 	_kvm_err(kd, kd->program, "kvm_readswap not implemented");
91 	return(0);
92 #endif	/* __FreeBSD__ */
93 }
94 #endif
95 
96 #define KREAD(kd, addr, obj) \
97 	(kvm_read(kd, addr, (char *)(obj), sizeof(*obj)) != sizeof(*obj))
98 
99 /*
100  * Read proc's from memory file into buffer bp, which has space to hold
101  * at most maxcnt procs.
102  */
103 static int
104 kvm_proclist(kd, what, arg, p, bp, maxcnt)
105 	kvm_t *kd;
106 	int what, arg;
107 	struct proc *p;
108 	struct kinfo_proc *bp;
109 	int maxcnt;
110 {
111 	int cnt = 0;
112 	struct kinfo_proc kinfo_proc, *kp;
113 	struct pgrp pgrp;
114 	struct session sess;
115 	struct tty tty;
116 	struct vmspace vmspace;
117 	struct procsig procsig;
118 	struct pstats pstats;
119 	struct ucred ucred;
120 	struct thread mainthread;
121 	struct proc proc;
122 	struct proc pproc;
123 	struct timeval tv;
124 
125 	kp = &kinfo_proc;
126 	kp->ki_structsize = sizeof(kinfo_proc);
127 	for (; cnt < maxcnt && p != NULL; p = LIST_NEXT(&proc, p_list)) {
128 		memset(kp, 0, sizeof *kp);
129 		if (KREAD(kd, (u_long)p, &proc)) {
130 			_kvm_err(kd, kd->program, "can't read proc at %x", p);
131 			return (-1);
132 		}
133 		if (proc.p_state != PRS_ZOMBIE) {
134 			if (KREAD(kd, (u_long)TAILQ_FIRST(&proc.p_threads),
135 			    &mainthread)) {
136 				_kvm_err(kd, kd->program,
137 				    "can't read thread at %x",
138 				    TAILQ_FIRST(&proc.p_threads));
139 				return (-1);
140 			}
141 		}
142 		if (KREAD(kd, (u_long)proc.p_ucred, &ucred) == 0) {
143 			kp->ki_ruid = ucred.cr_ruid;
144 			kp->ki_svuid = ucred.cr_svuid;
145 			kp->ki_rgid = ucred.cr_rgid;
146 			kp->ki_svgid = ucred.cr_svgid;
147 			kp->ki_ngroups = ucred.cr_ngroups;
148 			bcopy(ucred.cr_groups, kp->ki_groups,
149 			    NGROUPS * sizeof(gid_t));
150 			kp->ki_uid = ucred.cr_uid;
151 		}
152 
153 		switch(what) {
154 
155 		case KERN_PROC_PID:
156 			if (proc.p_pid != (pid_t)arg)
157 				continue;
158 			break;
159 
160 		case KERN_PROC_UID:
161 			if (kp->ki_uid != (uid_t)arg)
162 				continue;
163 			break;
164 
165 		case KERN_PROC_RUID:
166 			if (kp->ki_ruid != (uid_t)arg)
167 				continue;
168 			break;
169 		}
170 		/*
171 		 * We're going to add another proc to the set.  If this
172 		 * will overflow the buffer, assume the reason is because
173 		 * nprocs (or the proc list) is corrupt and declare an error.
174 		 */
175 		if (cnt >= maxcnt) {
176 			_kvm_err(kd, kd->program, "nprocs corrupt");
177 			return (-1);
178 		}
179 		/*
180 		 * gather kinfo_proc
181 		 */
182 		kp->ki_paddr = p;
183 		kp->ki_addr = proc.p_uarea;
184 		/* kp->ki_kstack = proc.p_thread.td_kstack; XXXKSE */
185 		kp->ki_args = proc.p_args;
186 		kp->ki_tracep = proc.p_tracep;
187 		kp->ki_textvp = proc.p_textvp;
188 		kp->ki_fd = proc.p_fd;
189 		kp->ki_vmspace = proc.p_vmspace;
190 		if (proc.p_procsig != NULL) {
191 			if (KREAD(kd, (u_long)proc.p_procsig, &procsig)) {
192 				_kvm_err(kd, kd->program,
193 				    "can't read procsig at %x", proc.p_procsig);
194 				return (-1);
195 			}
196 			kp->ki_sigignore = procsig.ps_sigignore;
197 			kp->ki_sigcatch = procsig.ps_sigcatch;
198 		}
199 		if ((proc.p_sflag & PS_INMEM) && proc.p_stats != NULL) {
200 			if (KREAD(kd, (u_long)proc.p_stats, &pstats)) {
201 				_kvm_err(kd, kd->program,
202 				    "can't read stats at %x", proc.p_stats);
203 				return (-1);
204 			}
205 			kp->ki_start = pstats.p_start;
206 			kp->ki_rusage = pstats.p_ru;
207 			kp->ki_childtime.tv_sec = pstats.p_cru.ru_utime.tv_sec +
208 			    pstats.p_cru.ru_stime.tv_sec;
209 			kp->ki_childtime.tv_usec =
210 			    pstats.p_cru.ru_utime.tv_usec +
211 			    pstats.p_cru.ru_stime.tv_usec;
212 		}
213 		if (proc.p_oppid)
214 			kp->ki_ppid = proc.p_oppid;
215 		else if (proc.p_pptr) {
216 			if (KREAD(kd, (u_long)proc.p_pptr, &pproc)) {
217 				_kvm_err(kd, kd->program,
218 				    "can't read pproc at %x", proc.p_pptr);
219 				return (-1);
220 			}
221 			kp->ki_ppid = pproc.p_pid;
222 		} else
223 			kp->ki_ppid = 0;
224 		if (proc.p_pgrp == NULL)
225 			goto nopgrp;
226 		if (KREAD(kd, (u_long)proc.p_pgrp, &pgrp)) {
227 			_kvm_err(kd, kd->program, "can't read pgrp at %x",
228 				 proc.p_pgrp);
229 			return (-1);
230 		}
231 		kp->ki_pgid = pgrp.pg_id;
232 		kp->ki_jobc = pgrp.pg_jobc;
233 		if (KREAD(kd, (u_long)pgrp.pg_session, &sess)) {
234 			_kvm_err(kd, kd->program, "can't read session at %x",
235 				pgrp.pg_session);
236 			return (-1);
237 		}
238 		kp->ki_sid = sess.s_sid;
239 		(void)memcpy(kp->ki_login, sess.s_login,
240 						sizeof(kp->ki_login));
241 		kp->ki_kiflag = sess.s_ttyvp ? KI_CTTY : 0;
242 		if (sess.s_leader == p)
243 			kp->ki_kiflag |= KI_SLEADER;
244 		if ((proc.p_flag & P_CONTROLT) && sess.s_ttyp != NULL) {
245 			if (KREAD(kd, (u_long)sess.s_ttyp, &tty)) {
246 				_kvm_err(kd, kd->program,
247 					 "can't read tty at %x", sess.s_ttyp);
248 				return (-1);
249 			}
250 			kp->ki_tdev = tty.t_dev;
251 			if (tty.t_pgrp != NULL) {
252 				if (KREAD(kd, (u_long)tty.t_pgrp, &pgrp)) {
253 					_kvm_err(kd, kd->program,
254 						 "can't read tpgrp at &x",
255 						tty.t_pgrp);
256 					return (-1);
257 				}
258 				kp->ki_tpgid = pgrp.pg_id;
259 			} else
260 				kp->ki_tpgid = -1;
261 			if (tty.t_session != NULL) {
262 				if (KREAD(kd, (u_long)tty.t_session, &sess)) {
263 					_kvm_err(kd, kd->program,
264 					    "can't read session at %x",
265 					    tty.t_session);
266 					return (-1);
267 				}
268 				kp->ki_tsid = sess.s_sid;
269 			}
270 		} else {
271 nopgrp:
272 			kp->ki_tdev = NODEV;
273 		}
274 		if ((proc.p_state != PRS_ZOMBIE) && mainthread.td_wmesg)
275 			(void)kvm_read(kd, (u_long)mainthread.td_wmesg,
276 			    kp->ki_wmesg, WMESGLEN);
277 
278 #ifdef sparc
279 		(void)kvm_read(kd, (u_long)&proc.p_vmspace->vm_rssize,
280 		    (char *)&kp->ki_rssize,
281 		    sizeof(kp->ki_rssize));
282 		(void)kvm_read(kd, (u_long)&proc.p_vmspace->vm_tsize,
283 		    (char *)&kp->ki_tsize,
284 		    3 * sizeof(kp->ki_rssize));	/* XXX */
285 #else
286 		(void)kvm_read(kd, (u_long)proc.p_vmspace,
287 		    (char *)&vmspace, sizeof(vmspace));
288 		kp->ki_size = vmspace.vm_map.size;
289 		kp->ki_rssize = vmspace.vm_swrss; /* XXX */
290 		kp->ki_swrss = vmspace.vm_swrss;
291 		kp->ki_tsize = vmspace.vm_tsize;
292 		kp->ki_dsize = vmspace.vm_dsize;
293 		kp->ki_ssize = vmspace.vm_ssize;
294 #endif
295 
296 		switch (what) {
297 
298 		case KERN_PROC_PGRP:
299 			if (kp->ki_pgid != (pid_t)arg)
300 				continue;
301 			break;
302 
303 		case KERN_PROC_TTY:
304 			if ((proc.p_flag & P_CONTROLT) == 0 ||
305 			     kp->ki_tdev != (dev_t)arg)
306 				continue;
307 			break;
308 		}
309 		if (proc.p_comm[0] != 0) {
310 			strncpy(kp->ki_comm, proc.p_comm, MAXCOMLEN);
311 			kp->ki_comm[MAXCOMLEN] = 0;
312 		}
313 		if ((proc.p_state != PRS_ZOMBIE) &&
314 		    (mainthread.td_blocked != 0)) {
315 			kp->ki_kiflag |= KI_MTXBLOCK;
316 			if (mainthread.td_mtxname)
317 				(void)kvm_read(kd,
318 				    (u_long)mainthread.td_mtxname,
319 				    kp->ki_mtxname, MTXNAMELEN);
320 			kp->ki_mtxname[MTXNAMELEN] = 0;
321 		}
322 		bintime2timeval(&proc.p_runtime, &tv);
323 		kp->ki_runtime = (u_int64_t)tv.tv_sec * 1000000 + tv.tv_usec;
324 		kp->ki_pid = proc.p_pid;
325 		kp->ki_siglist = proc.p_siglist;
326 		kp->ki_sigmask = proc.p_sigmask;
327 		kp->ki_xstat = proc.p_xstat;
328 		kp->ki_acflag = proc.p_acflag;
329 		if (proc.p_state != PRS_ZOMBIE) {
330 			kp->ki_pctcpu = proc.p_kse.ke_pctcpu;
331 			kp->ki_estcpu = proc.p_ksegrp.kg_estcpu;
332 			kp->ki_slptime = proc.p_kse.ke_slptime;
333 			kp->ki_swtime = proc.p_swtime;
334 			kp->ki_flag = proc.p_flag;
335 			kp->ki_sflag = proc.p_sflag;
336 			kp->ki_wchan = mainthread.td_wchan;
337 			kp->ki_traceflag = proc.p_traceflag;
338 			if (proc.p_state == PRS_NORMAL) {
339 				if ((mainthread.td_state == TDS_RUNQ) ||
340 				    (mainthread.td_state == TDS_RUNNING)) {
341 					kp->ki_stat = SRUN;
342 				} else if (mainthread.td_state == TDS_SLP) {
343 					kp->ki_stat = SSLEEP;
344 				} else if (P_SHOULDSTOP(&proc)) {
345 					kp->ki_stat = SSTOP;
346 				} else if (mainthread.td_state == TDS_MTX) {
347 					kp->ki_stat = SMTX;
348 				} else {
349 					kp->ki_stat = SWAIT;
350 				}
351 			} else {
352 				kp->ki_stat = SIDL;
353 			}
354 			kp->ki_pri.pri_class = proc.p_ksegrp.kg_pri_class;
355 			kp->ki_pri.pri_user = proc.p_ksegrp.kg_user_pri;
356 			kp->ki_pri.pri_level = mainthread.td_priority;
357 			kp->ki_pri.pri_native = mainthread.td_base_pri;
358 			kp->ki_nice = proc.p_ksegrp.kg_nice;
359 			kp->ki_lock = proc.p_lock;
360 			kp->ki_rqindex = proc.p_kse.ke_rqindex;
361 			kp->ki_oncpu = proc.p_kse.ke_oncpu;
362 			kp->ki_lastcpu = mainthread.td_lastcpu;
363 		} else {
364 			kp->ki_stat = SZOMB;
365 		}
366 		bcopy(&kinfo_proc, bp, sizeof(kinfo_proc));
367 		++bp;
368 		++cnt;
369 	}
370 	return (cnt);
371 }
372 
373 /*
374  * Build proc info array by reading in proc list from a crash dump.
375  * Return number of procs read.  maxcnt is the max we will read.
376  */
377 static int
378 kvm_deadprocs(kd, what, arg, a_allproc, a_zombproc, maxcnt)
379 	kvm_t *kd;
380 	int what, arg;
381 	u_long a_allproc;
382 	u_long a_zombproc;
383 	int maxcnt;
384 {
385 	struct kinfo_proc *bp = kd->procbase;
386 	int acnt, zcnt;
387 	struct proc *p;
388 
389 	if (KREAD(kd, a_allproc, &p)) {
390 		_kvm_err(kd, kd->program, "cannot read allproc");
391 		return (-1);
392 	}
393 	acnt = kvm_proclist(kd, what, arg, p, bp, maxcnt);
394 	if (acnt < 0)
395 		return (acnt);
396 
397 	if (KREAD(kd, a_zombproc, &p)) {
398 		_kvm_err(kd, kd->program, "cannot read zombproc");
399 		return (-1);
400 	}
401 	zcnt = kvm_proclist(kd, what, arg, p, bp + acnt, maxcnt - acnt);
402 	if (zcnt < 0)
403 		zcnt = 0;
404 
405 	return (acnt + zcnt);
406 }
407 
408 struct kinfo_proc *
409 kvm_getprocs(kd, op, arg, cnt)
410 	kvm_t *kd;
411 	int op, arg;
412 	int *cnt;
413 {
414 	int mib[4], st, nprocs;
415 	size_t size;
416 
417 	if (kd->procbase != 0) {
418 		free((void *)kd->procbase);
419 		/*
420 		 * Clear this pointer in case this call fails.  Otherwise,
421 		 * kvm_close() will free it again.
422 		 */
423 		kd->procbase = 0;
424 	}
425 	if (ISALIVE(kd)) {
426 		size = 0;
427 		mib[0] = CTL_KERN;
428 		mib[1] = KERN_PROC;
429 		mib[2] = op;
430 		mib[3] = arg;
431 		st = sysctl(mib, op == KERN_PROC_ALL ? 3 : 4, NULL, &size, NULL, 0);
432 		if (st == -1) {
433 			_kvm_syserr(kd, kd->program, "kvm_getprocs");
434 			return (0);
435 		}
436 		/*
437 		 * We can't continue with a size of 0 because we pass
438 		 * it to realloc() (via _kvm_realloc()), and passing 0
439 		 * to realloc() results in undefined behavior.
440 		 */
441 		if (size == 0) {
442 			/*
443 			 * XXX: We should probably return an invalid,
444 			 * but non-NULL, pointer here so any client
445 			 * program trying to dereference it will
446 			 * crash.  However, _kvm_freeprocs() calls
447 			 * free() on kd->procbase if it isn't NULL,
448 			 * and free()'ing a junk pointer isn't good.
449 			 * Then again, _kvm_freeprocs() isn't used
450 			 * anywhere . . .
451 			 */
452 			kd->procbase = _kvm_malloc(kd, 1);
453 			goto liveout;
454 		}
455 		do {
456 			size += size / 10;
457 			kd->procbase = (struct kinfo_proc *)
458 			    _kvm_realloc(kd, kd->procbase, size);
459 			if (kd->procbase == 0)
460 				return (0);
461 			st = sysctl(mib, op == KERN_PROC_ALL ? 3 : 4,
462 			    kd->procbase, &size, NULL, 0);
463 		} while (st == -1 && errno == ENOMEM);
464 		if (st == -1) {
465 			_kvm_syserr(kd, kd->program, "kvm_getprocs");
466 			return (0);
467 		}
468 		/*
469 		 * We have to check the size again because sysctl()
470 		 * may "round up" oldlenp if oldp is NULL; hence it
471 		 * might've told us that there was data to get when
472 		 * there really isn't any.
473 		 */
474 		if (size > 0 &&
475 		    kd->procbase->ki_structsize != sizeof(struct kinfo_proc)) {
476 			_kvm_err(kd, kd->program,
477 			    "kinfo_proc size mismatch (expected %d, got %d)",
478 			    sizeof(struct kinfo_proc),
479 			    kd->procbase->ki_structsize);
480 			return (0);
481 		}
482 liveout:
483 		nprocs = size == 0 ? 0 : size / kd->procbase->ki_structsize;
484 	} else {
485 		struct nlist nl[4], *p;
486 
487 		nl[0].n_name = "_nprocs";
488 		nl[1].n_name = "_allproc";
489 		nl[2].n_name = "_zombproc";
490 		nl[3].n_name = 0;
491 
492 		if (kvm_nlist(kd, nl) != 0) {
493 			for (p = nl; p->n_type != 0; ++p)
494 				;
495 			_kvm_err(kd, kd->program,
496 				 "%s: no such symbol", p->n_name);
497 			return (0);
498 		}
499 		if (KREAD(kd, nl[0].n_value, &nprocs)) {
500 			_kvm_err(kd, kd->program, "can't read nprocs");
501 			return (0);
502 		}
503 		size = nprocs * sizeof(struct kinfo_proc);
504 		kd->procbase = (struct kinfo_proc *)_kvm_malloc(kd, size);
505 		if (kd->procbase == 0)
506 			return (0);
507 
508 		nprocs = kvm_deadprocs(kd, op, arg, nl[1].n_value,
509 				      nl[2].n_value, nprocs);
510 #ifdef notdef
511 		size = nprocs * sizeof(struct kinfo_proc);
512 		(void)realloc(kd->procbase, size);
513 #endif
514 	}
515 	*cnt = nprocs;
516 	return (kd->procbase);
517 }
518 
519 void
520 _kvm_freeprocs(kd)
521 	kvm_t *kd;
522 {
523 	if (kd->procbase) {
524 		free(kd->procbase);
525 		kd->procbase = 0;
526 	}
527 }
528 
529 void *
530 _kvm_realloc(kd, p, n)
531 	kvm_t *kd;
532 	void *p;
533 	size_t n;
534 {
535 	void *np = (void *)realloc(p, n);
536 
537 	if (np == 0) {
538 		free(p);
539 		_kvm_err(kd, kd->program, "out of memory");
540 	}
541 	return (np);
542 }
543 
544 #ifndef MAX
545 #define MAX(a, b) ((a) > (b) ? (a) : (b))
546 #endif
547 
548 /*
549  * Read in an argument vector from the user address space of process kp.
550  * addr if the user-space base address of narg null-terminated contiguous
551  * strings.  This is used to read in both the command arguments and
552  * environment strings.  Read at most maxcnt characters of strings.
553  */
554 static char **
555 kvm_argv(kd, kp, addr, narg, maxcnt)
556 	kvm_t *kd;
557 	struct kinfo_proc *kp;
558 	u_long addr;
559 	int narg;
560 	int maxcnt;
561 {
562 	char *np, *cp, *ep, *ap;
563 	u_long oaddr = -1;
564 	int len, cc;
565 	char **argv;
566 
567 	/*
568 	 * Check that there aren't an unreasonable number of agruments,
569 	 * and that the address is in user space.
570 	 */
571 	if (narg > 512 || addr < VM_MIN_ADDRESS || addr >= VM_MAXUSER_ADDRESS)
572 		return (0);
573 
574 	/*
575 	 * kd->argv : work space for fetching the strings from the target
576 	 *            process's space, and is converted for returning to caller
577 	 */
578 	if (kd->argv == 0) {
579 		/*
580 		 * Try to avoid reallocs.
581 		 */
582 		kd->argc = MAX(narg + 1, 32);
583 		kd->argv = (char **)_kvm_malloc(kd, kd->argc *
584 						sizeof(*kd->argv));
585 		if (kd->argv == 0)
586 			return (0);
587 	} else if (narg + 1 > kd->argc) {
588 		kd->argc = MAX(2 * kd->argc, narg + 1);
589 		kd->argv = (char **)_kvm_realloc(kd, kd->argv, kd->argc *
590 						sizeof(*kd->argv));
591 		if (kd->argv == 0)
592 			return (0);
593 	}
594 	/*
595 	 * kd->argspc : returned to user, this is where the kd->argv
596 	 *              arrays are left pointing to the collected strings.
597 	 */
598 	if (kd->argspc == 0) {
599 		kd->argspc = (char *)_kvm_malloc(kd, PAGE_SIZE);
600 		if (kd->argspc == 0)
601 			return (0);
602 		kd->arglen = PAGE_SIZE;
603 	}
604 	/*
605 	 * kd->argbuf : used to pull in pages from the target process.
606 	 *              the strings are copied out of here.
607 	 */
608 	if (kd->argbuf == 0) {
609 		kd->argbuf = (char *)_kvm_malloc(kd, PAGE_SIZE);
610 		if (kd->argbuf == 0)
611 			return (0);
612 	}
613 
614 	/* Pull in the target process'es argv vector */
615 	cc = sizeof(char *) * narg;
616 	if (kvm_uread(kd, kp, addr, (char *)kd->argv, cc) != cc)
617 		return (0);
618 	/*
619 	 * ap : saved start address of string we're working on in kd->argspc
620 	 * np : pointer to next place to write in kd->argspc
621 	 * len: length of data in kd->argspc
622 	 * argv: pointer to the argv vector that we are hunting around the
623 	 *       target process space for, and converting to addresses in
624 	 *       our address space (kd->argspc).
625 	 */
626 	ap = np = kd->argspc;
627 	argv = kd->argv;
628 	len = 0;
629 	/*
630 	 * Loop over pages, filling in the argument vector.
631 	 * Note that the argv strings could be pointing *anywhere* in
632 	 * the user address space and are no longer contiguous.
633 	 * Note that *argv is modified when we are going to fetch a string
634 	 * that crosses a page boundary.  We copy the next part of the string
635 	 * into to "np" and eventually convert the pointer.
636 	 */
637 	while (argv < kd->argv + narg && *argv != 0) {
638 
639 		/* get the address that the current argv string is on */
640 		addr = (u_long)*argv & ~(PAGE_SIZE - 1);
641 
642 		/* is it the same page as the last one? */
643 		if (addr != oaddr) {
644 			if (kvm_uread(kd, kp, addr, kd->argbuf, PAGE_SIZE) !=
645 			    PAGE_SIZE)
646 				return (0);
647 			oaddr = addr;
648 		}
649 
650 		/* offset within the page... kd->argbuf */
651 		addr = (u_long)*argv & (PAGE_SIZE - 1);
652 
653 		/* cp = start of string, cc = count of chars in this chunk */
654 		cp = kd->argbuf + addr;
655 		cc = PAGE_SIZE - addr;
656 
657 		/* dont get more than asked for by user process */
658 		if (maxcnt > 0 && cc > maxcnt - len)
659 			cc = maxcnt - len;
660 
661 		/* pointer to end of string if we found it in this page */
662 		ep = memchr(cp, '\0', cc);
663 		if (ep != 0)
664 			cc = ep - cp + 1;
665 		/*
666 		 * at this point, cc is the count of the chars that we are
667 		 * going to retrieve this time. we may or may not have found
668 		 * the end of it.  (ep points to the null if the end is known)
669 		 */
670 
671 		/* will we exceed the malloc/realloced buffer? */
672 		if (len + cc > kd->arglen) {
673 			int off;
674 			char **pp;
675 			char *op = kd->argspc;
676 
677 			kd->arglen *= 2;
678 			kd->argspc = (char *)_kvm_realloc(kd, kd->argspc,
679 							  kd->arglen);
680 			if (kd->argspc == 0)
681 				return (0);
682 			/*
683 			 * Adjust argv pointers in case realloc moved
684 			 * the string space.
685 			 */
686 			off = kd->argspc - op;
687 			for (pp = kd->argv; pp < argv; pp++)
688 				*pp += off;
689 			ap += off;
690 			np += off;
691 		}
692 		/* np = where to put the next part of the string in kd->argspc*/
693 		/* np is kinda redundant.. could use "kd->argspc + len" */
694 		memcpy(np, cp, cc);
695 		np += cc;	/* inc counters */
696 		len += cc;
697 
698 		/*
699 		 * if end of string found, set the *argv pointer to the
700 		 * saved beginning of string, and advance. argv points to
701 		 * somewhere in kd->argv..  This is initially relative
702 		 * to the target process, but when we close it off, we set
703 		 * it to point in our address space.
704 		 */
705 		if (ep != 0) {
706 			*argv++ = ap;
707 			ap = np;
708 		} else {
709 			/* update the address relative to the target process */
710 			*argv += cc;
711 		}
712 
713 		if (maxcnt > 0 && len >= maxcnt) {
714 			/*
715 			 * We're stopping prematurely.  Terminate the
716 			 * current string.
717 			 */
718 			if (ep == 0) {
719 				*np = '\0';
720 				*argv++ = ap;
721 			}
722 			break;
723 		}
724 	}
725 	/* Make sure argv is terminated. */
726 	*argv = 0;
727 	return (kd->argv);
728 }
729 
730 static void
731 ps_str_a(p, addr, n)
732 	struct ps_strings *p;
733 	u_long *addr;
734 	int *n;
735 {
736 	*addr = (u_long)p->ps_argvstr;
737 	*n = p->ps_nargvstr;
738 }
739 
740 static void
741 ps_str_e(p, addr, n)
742 	struct ps_strings *p;
743 	u_long *addr;
744 	int *n;
745 {
746 	*addr = (u_long)p->ps_envstr;
747 	*n = p->ps_nenvstr;
748 }
749 
750 /*
751  * Determine if the proc indicated by p is still active.
752  * This test is not 100% foolproof in theory, but chances of
753  * being wrong are very low.
754  */
755 static int
756 proc_verify(curkp)
757 	struct kinfo_proc *curkp;
758 {
759 	struct kinfo_proc newkp;
760 	int mib[4];
761 	size_t len;
762 
763 	mib[0] = CTL_KERN;
764 	mib[1] = KERN_PROC;
765 	mib[2] = KERN_PROC_PID;
766 	mib[3] = curkp->ki_pid;
767 	len = sizeof(newkp);
768 	if (sysctl(mib, 4, &newkp, &len, NULL, 0) == -1)
769 		return (0);
770 	return (curkp->ki_pid == newkp.ki_pid &&
771 	    (newkp.ki_stat != SZOMB || curkp->ki_stat == SZOMB));
772 }
773 
774 static char **
775 kvm_doargv(kd, kp, nchr, info)
776 	kvm_t *kd;
777 	struct kinfo_proc *kp;
778 	int nchr;
779 	void (*info)(struct ps_strings *, u_long *, int *);
780 {
781 	char **ap;
782 	u_long addr;
783 	int cnt;
784 	static struct ps_strings arginfo;
785 	static u_long ps_strings;
786 	size_t len;
787 
788 	if (ps_strings == NULL) {
789 		len = sizeof(ps_strings);
790 		if (sysctlbyname("kern.ps_strings", &ps_strings, &len, NULL,
791 		    0) == -1)
792 			ps_strings = PS_STRINGS;
793 	}
794 
795 	/*
796 	 * Pointers are stored at the top of the user stack.
797 	 */
798 	if (kp->ki_stat == SZOMB ||
799 	    kvm_uread(kd, kp, ps_strings, (char *)&arginfo,
800 		      sizeof(arginfo)) != sizeof(arginfo))
801 		return (0);
802 
803 	(*info)(&arginfo, &addr, &cnt);
804 	if (cnt == 0)
805 		return (0);
806 	ap = kvm_argv(kd, kp, addr, cnt, nchr);
807 	/*
808 	 * For live kernels, make sure this process didn't go away.
809 	 */
810 	if (ap != 0 && ISALIVE(kd) && !proc_verify(kp))
811 		ap = 0;
812 	return (ap);
813 }
814 
815 /*
816  * Get the command args.  This code is now machine independent.
817  */
818 char **
819 kvm_getargv(kd, kp, nchr)
820 	kvm_t *kd;
821 	const struct kinfo_proc *kp;
822 	int nchr;
823 {
824 	int oid[4];
825 	int i;
826 	size_t bufsz;
827 	static unsigned long buflen;
828 	static char *buf, *p;
829 	static char **bufp;
830 	static int argc;
831 
832 	if (!ISALIVE(kd)) {
833 		_kvm_err(kd, kd->program,
834 		    "cannot read user space from dead kernel");
835 		return (0);
836 	}
837 
838 	if (!buflen) {
839 		bufsz = sizeof(buflen);
840 		i = sysctlbyname("kern.ps_arg_cache_limit",
841 		    &buflen, &bufsz, NULL, 0);
842 		if (i == -1) {
843 			buflen = 0;
844 		} else {
845 			buf = malloc(buflen);
846 			if (buf == NULL)
847 				buflen = 0;
848 			argc = 32;
849 			bufp = malloc(sizeof(char *) * argc);
850 		}
851 	}
852 	if (buf != NULL) {
853 		oid[0] = CTL_KERN;
854 		oid[1] = KERN_PROC;
855 		oid[2] = KERN_PROC_ARGS;
856 		oid[3] = kp->ki_pid;
857 		bufsz = buflen;
858 		i = sysctl(oid, 4, buf, &bufsz, 0, 0);
859 		if (i == 0 && bufsz > 0) {
860 			i = 0;
861 			p = buf;
862 			do {
863 				bufp[i++] = p;
864 				p += strlen(p) + 1;
865 				if (i >= argc) {
866 					argc += argc;
867 					bufp = realloc(bufp,
868 					    sizeof(char *) * argc);
869 				}
870 			} while (p < buf + bufsz);
871 			bufp[i++] = 0;
872 			return (bufp);
873 		}
874 	}
875 	if (kp->ki_flag & P_SYSTEM)
876 		return (NULL);
877 	return (kvm_doargv(kd, kp, nchr, ps_str_a));
878 }
879 
880 char **
881 kvm_getenvv(kd, kp, nchr)
882 	kvm_t *kd;
883 	const struct kinfo_proc *kp;
884 	int nchr;
885 {
886 	return (kvm_doargv(kd, kp, nchr, ps_str_e));
887 }
888 
889 /*
890  * Read from user space.  The user context is given by p.
891  */
892 ssize_t
893 kvm_uread(kd, kp, uva, buf, len)
894 	kvm_t *kd;
895 	struct kinfo_proc *kp;
896 	u_long uva;
897 	char *buf;
898 	size_t len;
899 {
900 	char *cp;
901 	char procfile[MAXPATHLEN];
902 	ssize_t amount;
903 	int fd;
904 
905 	if (!ISALIVE(kd)) {
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", kp->ki_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 (%x) 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