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