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