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