xref: /freebsd/lib/libkvm/kvm_proc.c (revision d0b2dbfa0ecf2bbc9709efc5e20baf8e4b44bbbf)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1989, 1992, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software developed by the Computer Systems
8  * Engineering group at Lawrence Berkeley Laboratory under DARPA contract
9  * BG 91-66 and contributed to Berkeley.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 
36 #include <sys/cdefs.h>
37 __SCCSID("@(#)kvm_proc.c	8.3 (Berkeley) 9/23/93");
38 
39 /*
40  * Proc traversal interface for kvm.  ps and w are (probably) the exclusive
41  * users of this code, so we've factored it out into a separate module.
42  * Thus, we keep this grunge out of the other kvm applications (i.e.,
43  * most other applications are interested only in open/close/read/nlist).
44  */
45 
46 #include <sys/param.h>
47 #define	_WANT_UCRED	/* make ucred.h give us 'struct ucred' */
48 #include <sys/ucred.h>
49 #include <sys/queue.h>
50 #include <sys/_lock.h>
51 #include <sys/_mutex.h>
52 #include <sys/_task.h>
53 #include <sys/cpuset.h>
54 #include <sys/user.h>
55 #include <sys/proc.h>
56 #define	_WANT_PRISON	/* make jail.h give us 'struct prison' */
57 #include <sys/jail.h>
58 #include <sys/exec.h>
59 #include <sys/stat.h>
60 #include <sys/sysent.h>
61 #include <sys/ioctl.h>
62 #include <sys/tty.h>
63 #include <sys/file.h>
64 #include <sys/conf.h>
65 #define	_WANT_KW_EXITCODE
66 #include <sys/wait.h>
67 #include <stdio.h>
68 #include <stdlib.h>
69 #include <stdbool.h>
70 #include <unistd.h>
71 #include <nlist.h>
72 #include <kvm.h>
73 
74 #include <sys/sysctl.h>
75 
76 #include <limits.h>
77 #include <memory.h>
78 #include <paths.h>
79 
80 #include "kvm_private.h"
81 
82 #define KREAD(kd, addr, obj) \
83 	(kvm_read(kd, addr, (char *)(obj), sizeof(*obj)) != sizeof(*obj))
84 
85 static int ticks;
86 static int hz;
87 static uint64_t cpu_tick_frequency;
88 
89 /*
90  * From sys/kern/kern_tc.c. Depends on cpu_tick_frequency, which is
91  * read/initialized before this function is ever called.
92  */
93 static uint64_t
94 cputick2usec(uint64_t tick)
95 {
96 	if (cpu_tick_frequency == 0)
97 		return (0);
98 	return ((tick / cpu_tick_frequency) * 1000000ULL) +
99 	    ((tick % cpu_tick_frequency) * 1000000ULL) / cpu_tick_frequency;
100 }
101 
102 /*
103  * Read proc's from memory file into buffer bp, which has space to hold
104  * at most maxcnt procs.
105  */
106 static int
107 kvm_proclist(kvm_t *kd, int what, int arg, struct proc *p,
108     struct kinfo_proc *bp, int maxcnt)
109 {
110 	int cnt = 0;
111 	struct kinfo_proc kinfo_proc, *kp;
112 	struct pgrp pgrp;
113 	struct session sess;
114 	struct cdev t_cdev;
115 	struct tty tty;
116 	struct vmspace vmspace;
117 	struct sigacts sigacts;
118 #if 0
119 	struct pstats pstats;
120 #endif
121 	struct ucred ucred;
122 	struct prison pr;
123 	struct thread mtd;
124 	struct proc proc;
125 	struct proc pproc;
126 	struct sysentvec sysent;
127 	char svname[KI_EMULNAMELEN];
128 	struct thread *td = NULL;
129 	bool first_thread;
130 
131 	kp = &kinfo_proc;
132 	kp->ki_structsize = sizeof(kinfo_proc);
133 	/*
134 	 * Loop on the processes, then threads within the process if requested.
135 	 */
136 	if (what == KERN_PROC_ALL)
137 		what |= KERN_PROC_INC_THREAD;
138 	for (; cnt < maxcnt && p != NULL; p = LIST_NEXT(&proc, p_list)) {
139 		memset(kp, 0, sizeof *kp);
140 		if (KREAD(kd, (u_long)p, &proc)) {
141 			_kvm_err(kd, kd->program, "can't read proc at %p", p);
142 			return (-1);
143 		}
144 		if (proc.p_state == PRS_NEW)
145 			continue;
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_cr_flags = ucred.cr_flags;
152 			if (ucred.cr_ngroups > KI_NGROUPS) {
153 				kp->ki_ngroups = KI_NGROUPS;
154 				kp->ki_cr_flags |= KI_CRF_GRP_OVERFLOW;
155 			} else
156 				kp->ki_ngroups = ucred.cr_ngroups;
157 			kvm_read(kd, (u_long)ucred.cr_groups, kp->ki_groups,
158 			    kp->ki_ngroups * sizeof(gid_t));
159 			kp->ki_uid = ucred.cr_uid;
160 			if (ucred.cr_prison != NULL) {
161 				if (KREAD(kd, (u_long)ucred.cr_prison, &pr)) {
162 					_kvm_err(kd, kd->program,
163 					    "can't read prison at %p",
164 					    ucred.cr_prison);
165 					return (-1);
166 				}
167 				kp->ki_jid = pr.pr_id;
168 			}
169 		}
170 
171 		switch(what & ~KERN_PROC_INC_THREAD) {
172 
173 		case KERN_PROC_GID:
174 			if (kp->ki_groups[0] != (gid_t)arg)
175 				continue;
176 			break;
177 
178 		case KERN_PROC_PID:
179 			if (proc.p_pid != (pid_t)arg)
180 				continue;
181 			break;
182 
183 		case KERN_PROC_RGID:
184 			if (kp->ki_rgid != (gid_t)arg)
185 				continue;
186 			break;
187 
188 		case KERN_PROC_UID:
189 			if (kp->ki_uid != (uid_t)arg)
190 				continue;
191 			break;
192 
193 		case KERN_PROC_RUID:
194 			if (kp->ki_ruid != (uid_t)arg)
195 				continue;
196 			break;
197 		}
198 		/*
199 		 * We're going to add another proc to the set.  If this
200 		 * will overflow the buffer, assume the reason is because
201 		 * nprocs (or the proc list) is corrupt and declare an error.
202 		 */
203 		if (cnt >= maxcnt) {
204 			_kvm_err(kd, kd->program, "nprocs corrupt");
205 			return (-1);
206 		}
207 		/*
208 		 * gather kinfo_proc
209 		 */
210 		kp->ki_paddr = p;
211 		kp->ki_addr = 0;	/* XXX uarea */
212 		/* kp->ki_kstack = proc.p_thread.td_kstack; XXXKSE */
213 		kp->ki_args = proc.p_args;
214 		kp->ki_numthreads = proc.p_numthreads;
215 		kp->ki_tracep = NULL;	/* XXXKIB do not expose ktr_io_params */
216 		kp->ki_textvp = proc.p_textvp;
217 		kp->ki_fd = proc.p_fd;
218 		kp->ki_pd = proc.p_pd;
219 		kp->ki_vmspace = proc.p_vmspace;
220 		if (proc.p_sigacts != NULL) {
221 			if (KREAD(kd, (u_long)proc.p_sigacts, &sigacts)) {
222 				_kvm_err(kd, kd->program,
223 				    "can't read sigacts at %p", proc.p_sigacts);
224 				return (-1);
225 			}
226 			kp->ki_sigignore = sigacts.ps_sigignore;
227 			kp->ki_sigcatch = sigacts.ps_sigcatch;
228 		}
229 #if 0
230 		if ((proc.p_flag & P_INMEM) && proc.p_stats != NULL) {
231 			if (KREAD(kd, (u_long)proc.p_stats, &pstats)) {
232 				_kvm_err(kd, kd->program,
233 				    "can't read stats at %x", proc.p_stats);
234 				return (-1);
235 			}
236 			kp->ki_start = pstats.p_start;
237 
238 			/*
239 			 * XXX: The times here are probably zero and need
240 			 * to be calculated from the raw data in p_rux and
241 			 * p_crux.
242 			 */
243 			kp->ki_rusage = pstats.p_ru;
244 			kp->ki_childstime = pstats.p_cru.ru_stime;
245 			kp->ki_childutime = pstats.p_cru.ru_utime;
246 			/* Some callers want child-times in a single value */
247 			timeradd(&kp->ki_childstime, &kp->ki_childutime,
248 			    &kp->ki_childtime);
249 		}
250 #endif
251 		if (proc.p_oppid)
252 			kp->ki_ppid = proc.p_oppid;
253 		else if (proc.p_pptr) {
254 			if (KREAD(kd, (u_long)proc.p_pptr, &pproc)) {
255 				_kvm_err(kd, kd->program,
256 				    "can't read pproc at %p", proc.p_pptr);
257 				return (-1);
258 			}
259 			kp->ki_ppid = pproc.p_pid;
260 		} else
261 			kp->ki_ppid = 0;
262 		if (proc.p_pgrp == NULL)
263 			goto nopgrp;
264 		if (KREAD(kd, (u_long)proc.p_pgrp, &pgrp)) {
265 			_kvm_err(kd, kd->program, "can't read pgrp at %p",
266 				 proc.p_pgrp);
267 			return (-1);
268 		}
269 		kp->ki_pgid = pgrp.pg_id;
270 		kp->ki_jobc = -1;	/* Or calculate?  Arguably not. */
271 		if (KREAD(kd, (u_long)pgrp.pg_session, &sess)) {
272 			_kvm_err(kd, kd->program, "can't read session at %p",
273 				pgrp.pg_session);
274 			return (-1);
275 		}
276 		kp->ki_sid = sess.s_sid;
277 		(void)memcpy(kp->ki_login, sess.s_login,
278 						sizeof(kp->ki_login));
279 		if ((proc.p_flag & P_CONTROLT) && sess.s_ttyp != NULL) {
280 			if (KREAD(kd, (u_long)sess.s_ttyp, &tty)) {
281 				_kvm_err(kd, kd->program,
282 					 "can't read tty at %p", sess.s_ttyp);
283 				return (-1);
284 			}
285 			if (tty.t_dev != NULL) {
286 				if (KREAD(kd, (u_long)tty.t_dev, &t_cdev)) {
287 					_kvm_err(kd, kd->program,
288 						 "can't read cdev at %p",
289 						tty.t_dev);
290 					return (-1);
291 				}
292 #if 0
293 				kp->ki_tdev = t_cdev.si_udev;
294 #else
295 				kp->ki_tdev = NODEV;
296 #endif
297 			}
298 			if (tty.t_pgrp != NULL) {
299 				if (KREAD(kd, (u_long)tty.t_pgrp, &pgrp)) {
300 					_kvm_err(kd, kd->program,
301 						 "can't read tpgrp at %p",
302 						tty.t_pgrp);
303 					return (-1);
304 				}
305 				kp->ki_tpgid = pgrp.pg_id;
306 			} else
307 				kp->ki_tpgid = -1;
308 			if (tty.t_session != NULL) {
309 				if (KREAD(kd, (u_long)tty.t_session, &sess)) {
310 					_kvm_err(kd, kd->program,
311 					    "can't read session at %p",
312 					    tty.t_session);
313 					return (-1);
314 				}
315 				kp->ki_tsid = sess.s_sid;
316 			}
317 		} else {
318 nopgrp:
319 			kp->ki_tdev = NODEV;
320 		}
321 
322 		(void)kvm_read(kd, (u_long)proc.p_vmspace,
323 		    (char *)&vmspace, sizeof(vmspace));
324 		kp->ki_size = vmspace.vm_map.size;
325 		/*
326 		 * Approximate the kernel's method of calculating
327 		 * this field.
328 		 */
329 #define		pmap_resident_count(pm) ((pm)->pm_stats.resident_count)
330 		kp->ki_rssize = pmap_resident_count(&vmspace.vm_pmap);
331 		kp->ki_swrss = vmspace.vm_swrss;
332 		kp->ki_tsize = vmspace.vm_tsize;
333 		kp->ki_dsize = vmspace.vm_dsize;
334 		kp->ki_ssize = vmspace.vm_ssize;
335 
336 		switch (what & ~KERN_PROC_INC_THREAD) {
337 
338 		case KERN_PROC_PGRP:
339 			if (kp->ki_pgid != (pid_t)arg)
340 				continue;
341 			break;
342 
343 		case KERN_PROC_SESSION:
344 			if (kp->ki_sid != (pid_t)arg)
345 				continue;
346 			break;
347 
348 		case KERN_PROC_TTY:
349 			if ((proc.p_flag & P_CONTROLT) == 0 ||
350 			     kp->ki_tdev != (dev_t)arg)
351 				continue;
352 			break;
353 		}
354 		if (proc.p_comm[0] != 0)
355 			strlcpy(kp->ki_comm, proc.p_comm, MAXCOMLEN);
356 		(void)kvm_read(kd, (u_long)proc.p_sysent, (char *)&sysent,
357 		    sizeof(sysent));
358 		(void)kvm_read(kd, (u_long)sysent.sv_name, (char *)&svname,
359 		    sizeof(svname));
360 		if (svname[0] != 0)
361 			strlcpy(kp->ki_emul, svname, KI_EMULNAMELEN);
362 		kp->ki_runtime = cputick2usec(proc.p_rux.rux_runtime);
363 		kp->ki_pid = proc.p_pid;
364 		kp->ki_xstat = KW_EXITCODE(proc.p_xexit, proc.p_xsig);
365 		kp->ki_acflag = proc.p_acflag;
366 		kp->ki_lock = proc.p_lock;
367 		kp->ki_tdev_freebsd11 = kp->ki_tdev; /* truncate */
368 
369 		/* Per-thread items; iterate as appropriate. */
370 		td = TAILQ_FIRST(&proc.p_threads);
371 		for (first_thread = true; cnt < maxcnt && td != NULL &&
372 		    (first_thread || (what & KERN_PROC_INC_THREAD));
373 		    first_thread = false) {
374 			if (proc.p_state != PRS_ZOMBIE) {
375 				if (KREAD(kd, (u_long)td, &mtd)) {
376 					_kvm_err(kd, kd->program,
377 					    "can't read thread at %p", td);
378 					return (-1);
379 				}
380 				if (what & KERN_PROC_INC_THREAD)
381 					td = TAILQ_NEXT(&mtd, td_plist);
382 			} else
383 				td = NULL;
384 			if ((proc.p_state != PRS_ZOMBIE) && mtd.td_wmesg)
385 				(void)kvm_read(kd, (u_long)mtd.td_wmesg,
386 				    kp->ki_wmesg, WMESGLEN);
387 			else
388 				memset(kp->ki_wmesg, 0, WMESGLEN);
389 			if (proc.p_pgrp == NULL) {
390 				kp->ki_kiflag = 0;
391 			} else {
392 				kp->ki_kiflag = sess.s_ttyvp ? KI_CTTY : 0;
393 				if (sess.s_leader == p)
394 					kp->ki_kiflag |= KI_SLEADER;
395 			}
396 			if ((proc.p_state != PRS_ZOMBIE) &&
397 			    (mtd.td_blocked != 0)) {
398 				kp->ki_kiflag |= KI_LOCKBLOCK;
399 				if (mtd.td_lockname)
400 					(void)kvm_read(kd,
401 					    (u_long)mtd.td_lockname,
402 					    kp->ki_lockname, LOCKNAMELEN);
403 				else
404 					memset(kp->ki_lockname, 0,
405 					    LOCKNAMELEN);
406 				kp->ki_lockname[LOCKNAMELEN] = 0;
407 			} else
408 				kp->ki_kiflag &= ~KI_LOCKBLOCK;
409 			kp->ki_siglist = proc.p_siglist;
410 			if (proc.p_state != PRS_ZOMBIE) {
411 				SIGSETOR(kp->ki_siglist, mtd.td_siglist);
412 				kp->ki_sigmask = mtd.td_sigmask;
413 				kp->ki_swtime = (ticks - proc.p_swtick) / hz;
414 				kp->ki_flag = proc.p_flag;
415 				kp->ki_sflag = 0;
416 				kp->ki_nice = proc.p_nice;
417 				kp->ki_traceflag = proc.p_traceflag;
418 				if (proc.p_state == PRS_NORMAL) {
419 					if (TD_ON_RUNQ(&mtd) ||
420 					    TD_CAN_RUN(&mtd) ||
421 					    TD_IS_RUNNING(&mtd)) {
422 						kp->ki_stat = SRUN;
423 					} else if (TD_GET_STATE(&mtd) ==
424 					    TDS_INHIBITED) {
425 						if (P_SHOULDSTOP(&proc)) {
426 							kp->ki_stat = SSTOP;
427 						} else if (
428 						    TD_IS_SLEEPING(&mtd)) {
429 							kp->ki_stat = SSLEEP;
430 						} else if (TD_ON_LOCK(&mtd)) {
431 							kp->ki_stat = SLOCK;
432 						} else {
433 							kp->ki_stat = SWAIT;
434 						}
435 					}
436 				} else {
437 					kp->ki_stat = SIDL;
438 				}
439 				/* Stuff from the thread */
440 				kp->ki_pri.pri_level = mtd.td_priority;
441 				kp->ki_pri.pri_native = mtd.td_base_pri;
442 				kp->ki_lastcpu = mtd.td_lastcpu;
443 				kp->ki_wchan = mtd.td_wchan;
444 				kp->ki_oncpu = mtd.td_oncpu;
445 				if (mtd.td_name[0] != '\0')
446 					strlcpy(kp->ki_tdname, mtd.td_name,
447 					    sizeof(kp->ki_tdname));
448 				else
449 					memset(kp->ki_tdname, 0,
450 					    sizeof(kp->ki_tdname));
451 				kp->ki_pctcpu = 0;
452 				kp->ki_rqindex = 0;
453 
454 				/*
455 				 * Note: legacy fields; wraps at NO_CPU_OLD
456 				 * or the old max CPU value as appropriate
457 				 */
458 				if (mtd.td_lastcpu == NOCPU)
459 					kp->ki_lastcpu_old = NOCPU_OLD;
460 				else if (mtd.td_lastcpu > MAXCPU_OLD)
461 					kp->ki_lastcpu_old = MAXCPU_OLD;
462 				else
463 					kp->ki_lastcpu_old = mtd.td_lastcpu;
464 
465 				if (mtd.td_oncpu == NOCPU)
466 					kp->ki_oncpu_old = NOCPU_OLD;
467 				else if (mtd.td_oncpu > MAXCPU_OLD)
468 					kp->ki_oncpu_old = MAXCPU_OLD;
469 				else
470 					kp->ki_oncpu_old = mtd.td_oncpu;
471 				kp->ki_tid = mtd.td_tid;
472 			} else {
473 				memset(&kp->ki_sigmask, 0,
474 				    sizeof(kp->ki_sigmask));
475 				kp->ki_stat = SZOMB;
476 				kp->ki_tid = 0;
477 			}
478 
479 			bcopy(&kinfo_proc, bp, sizeof(kinfo_proc));
480 			++bp;
481 			++cnt;
482 		}
483 	}
484 	return (cnt);
485 }
486 
487 /*
488  * Build proc info array by reading in proc list from a crash dump.
489  * Return number of procs read.  maxcnt is the max we will read.
490  */
491 static int
492 kvm_deadprocs(kvm_t *kd, int what, int arg, u_long a_allproc,
493     u_long a_zombproc, int maxcnt)
494 {
495 	struct kinfo_proc *bp = kd->procbase;
496 	int acnt, zcnt = 0;
497 	struct proc *p;
498 
499 	if (KREAD(kd, a_allproc, &p)) {
500 		_kvm_err(kd, kd->program, "cannot read allproc");
501 		return (-1);
502 	}
503 	acnt = kvm_proclist(kd, what, arg, p, bp, maxcnt);
504 	if (acnt < 0)
505 		return (acnt);
506 
507 	if (a_zombproc != 0) {
508 		if (KREAD(kd, a_zombproc, &p)) {
509 			_kvm_err(kd, kd->program, "cannot read zombproc");
510 			return (-1);
511 		}
512 		zcnt = kvm_proclist(kd, what, arg, p, bp + acnt, maxcnt - acnt);
513 		if (zcnt < 0)
514 			zcnt = 0;
515 	}
516 
517 	return (acnt + zcnt);
518 }
519 
520 struct kinfo_proc *
521 kvm_getprocs(kvm_t *kd, int op, int arg, int *cnt)
522 {
523 	int mib[4], st, nprocs;
524 	size_t size, osize;
525 	int temp_op;
526 
527 	if (kd->procbase != 0) {
528 		free((void *)kd->procbase);
529 		/*
530 		 * Clear this pointer in case this call fails.  Otherwise,
531 		 * kvm_close() will free it again.
532 		 */
533 		kd->procbase = 0;
534 	}
535 	if (ISALIVE(kd)) {
536 		size = 0;
537 		mib[0] = CTL_KERN;
538 		mib[1] = KERN_PROC;
539 		mib[2] = op;
540 		mib[3] = arg;
541 		temp_op = op & ~KERN_PROC_INC_THREAD;
542 		st = sysctl(mib,
543 		    temp_op == KERN_PROC_ALL || temp_op == KERN_PROC_PROC ?
544 		    3 : 4, NULL, &size, NULL, 0);
545 		if (st == -1) {
546 			_kvm_syserr(kd, kd->program, "kvm_getprocs");
547 			return (0);
548 		}
549 		/*
550 		 * We can't continue with a size of 0 because we pass
551 		 * it to realloc() (via _kvm_realloc()), and passing 0
552 		 * to realloc() results in undefined behavior.
553 		 */
554 		if (size == 0) {
555 			/*
556 			 * XXX: We should probably return an invalid,
557 			 * but non-NULL, pointer here so any client
558 			 * program trying to dereference it will
559 			 * crash.  However, _kvm_freeprocs() calls
560 			 * free() on kd->procbase if it isn't NULL,
561 			 * and free()'ing a junk pointer isn't good.
562 			 * Then again, _kvm_freeprocs() isn't used
563 			 * anywhere . . .
564 			 */
565 			kd->procbase = _kvm_malloc(kd, 1);
566 			goto liveout;
567 		}
568 		do {
569 			size += size / 10;
570 			kd->procbase = (struct kinfo_proc *)
571 			    _kvm_realloc(kd, kd->procbase, size);
572 			if (kd->procbase == NULL)
573 				return (0);
574 			osize = size;
575 			st = sysctl(mib, temp_op == KERN_PROC_ALL ||
576 			    temp_op == KERN_PROC_PROC ? 3 : 4,
577 			    kd->procbase, &size, NULL, 0);
578 		} while (st == -1 && errno == ENOMEM && size == osize);
579 		if (st == -1) {
580 			_kvm_syserr(kd, kd->program, "kvm_getprocs");
581 			return (0);
582 		}
583 		/*
584 		 * We have to check the size again because sysctl()
585 		 * may "round up" oldlenp if oldp is NULL; hence it
586 		 * might've told us that there was data to get when
587 		 * there really isn't any.
588 		 */
589 		if (size > 0 &&
590 		    kd->procbase->ki_structsize != sizeof(struct kinfo_proc)) {
591 			_kvm_err(kd, kd->program,
592 			    "kinfo_proc size mismatch (expected %zu, got %d)",
593 			    sizeof(struct kinfo_proc),
594 			    kd->procbase->ki_structsize);
595 			return (0);
596 		}
597 liveout:
598 		nprocs = size == 0 ? 0 : size / kd->procbase->ki_structsize;
599 	} else {
600 		struct nlist nl[6], *p;
601 		struct nlist nlz[2];
602 
603 		nl[0].n_name = "_nprocs";
604 		nl[1].n_name = "_allproc";
605 		nl[2].n_name = "_ticks";
606 		nl[3].n_name = "_hz";
607 		nl[4].n_name = "_cpu_tick_frequency";
608 		nl[5].n_name = 0;
609 
610 		nlz[0].n_name = "_zombproc";
611 		nlz[1].n_name = 0;
612 
613 		if (!kd->arch->ka_native(kd)) {
614 			_kvm_err(kd, kd->program,
615 			    "cannot read procs from non-native core");
616 			return (0);
617 		}
618 
619 		if (kvm_nlist(kd, nl) != 0) {
620 			for (p = nl; p->n_type != 0; ++p)
621 				;
622 			_kvm_err(kd, kd->program,
623 				 "%s: no such symbol", p->n_name);
624 			return (0);
625 		}
626 		(void) kvm_nlist(kd, nlz);	/* attempt to get zombproc */
627 		if (KREAD(kd, nl[0].n_value, &nprocs)) {
628 			_kvm_err(kd, kd->program, "can't read nprocs");
629 			return (0);
630 		}
631 		/*
632 		 * If returning all threads, we don't know how many that
633 		 * might be.  Presume that there are, on average, no more
634 		 * than 10 threads per process.
635 		 */
636 		if (op == KERN_PROC_ALL || (op & KERN_PROC_INC_THREAD))
637 			nprocs *= 10;		/* XXX */
638 		if (KREAD(kd, nl[2].n_value, &ticks)) {
639 			_kvm_err(kd, kd->program, "can't read ticks");
640 			return (0);
641 		}
642 		if (KREAD(kd, nl[3].n_value, &hz)) {
643 			_kvm_err(kd, kd->program, "can't read hz");
644 			return (0);
645 		}
646 		if (KREAD(kd, nl[4].n_value, &cpu_tick_frequency)) {
647 			_kvm_err(kd, kd->program,
648 			    "can't read cpu_tick_frequency");
649 			return (0);
650 		}
651 		size = nprocs * sizeof(struct kinfo_proc);
652 		kd->procbase = (struct kinfo_proc *)_kvm_malloc(kd, size);
653 		if (kd->procbase == NULL)
654 			return (0);
655 
656 		nprocs = kvm_deadprocs(kd, op, arg, nl[1].n_value,
657 				      nlz[0].n_value, nprocs);
658 		if (nprocs <= 0) {
659 			_kvm_freeprocs(kd);
660 			nprocs = 0;
661 		}
662 #ifdef notdef
663 		else {
664 			size = nprocs * sizeof(struct kinfo_proc);
665 			kd->procbase = realloc(kd->procbase, size);
666 		}
667 #endif
668 	}
669 	*cnt = nprocs;
670 	return (kd->procbase);
671 }
672 
673 void
674 _kvm_freeprocs(kvm_t *kd)
675 {
676 
677 	free(kd->procbase);
678 	kd->procbase = NULL;
679 }
680 
681 void *
682 _kvm_realloc(kvm_t *kd, void *p, size_t n)
683 {
684 	void *np;
685 
686 	np = reallocf(p, n);
687 	if (np == NULL)
688 		_kvm_err(kd, kd->program, "out of memory");
689 	return (np);
690 }
691 
692 /*
693  * Get the command args or environment.
694  */
695 static char **
696 kvm_argv(kvm_t *kd, const struct kinfo_proc *kp, int env, int nchr)
697 {
698 	int oid[4];
699 	int i;
700 	size_t bufsz;
701 	static int buflen;
702 	static char *buf, *p;
703 	static char **bufp;
704 	static int argc;
705 	char **nbufp;
706 
707 	if (!ISALIVE(kd)) {
708 		_kvm_err(kd, kd->program,
709 		    "cannot read user space from dead kernel");
710 		return (NULL);
711 	}
712 
713 	if (nchr == 0 || nchr > ARG_MAX)
714 		nchr = ARG_MAX;
715 	if (buflen == 0) {
716 		buf = malloc(nchr);
717 		if (buf == NULL) {
718 			_kvm_err(kd, kd->program, "cannot allocate memory");
719 			return (NULL);
720 		}
721 		argc = 32;
722 		bufp = malloc(sizeof(char *) * argc);
723 		if (bufp == NULL) {
724 			free(buf);
725 			buf = NULL;
726 			_kvm_err(kd, kd->program, "cannot allocate memory");
727 			return (NULL);
728 		}
729 		buflen = nchr;
730 	} else if (nchr > buflen) {
731 		p = realloc(buf, nchr);
732 		if (p != NULL) {
733 			buf = p;
734 			buflen = nchr;
735 		}
736 	}
737 	oid[0] = CTL_KERN;
738 	oid[1] = KERN_PROC;
739 	oid[2] = env ? KERN_PROC_ENV : KERN_PROC_ARGS;
740 	oid[3] = kp->ki_pid;
741 	bufsz = buflen;
742 	if (sysctl(oid, 4, buf, &bufsz, 0, 0) == -1) {
743 		/*
744 		 * If the supplied buf is too short to hold the requested
745 		 * value the sysctl returns with ENOMEM. The buf is filled
746 		 * with the truncated value and the returned bufsz is equal
747 		 * to the requested len.
748 		 */
749 		if (errno != ENOMEM || bufsz != (size_t)buflen)
750 			return (NULL);
751 		buf[bufsz - 1] = '\0';
752 		errno = 0;
753 	} else if (bufsz == 0)
754 		return (NULL);
755 	i = 0;
756 	p = buf;
757 	do {
758 		bufp[i++] = p;
759 		p += strlen(p) + 1;
760 		if (i >= argc) {
761 			argc += argc;
762 			nbufp = realloc(bufp, sizeof(char *) * argc);
763 			if (nbufp == NULL)
764 				return (NULL);
765 			bufp = nbufp;
766 		}
767 	} while (p < buf + bufsz);
768 	bufp[i++] = 0;
769 	return (bufp);
770 }
771 
772 char **
773 kvm_getargv(kvm_t *kd, const struct kinfo_proc *kp, int nchr)
774 {
775 	return (kvm_argv(kd, kp, 0, nchr));
776 }
777 
778 char **
779 kvm_getenvv(kvm_t *kd, const struct kinfo_proc *kp, int nchr)
780 {
781 	return (kvm_argv(kd, kp, 1, nchr));
782 }
783