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