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