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