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