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