kvm_proc.c revision 112891
156055Srwatson/*-
289831Sjedgar * Copyright (c) 1989, 1992, 1993
356055Srwatson *	The Regents of the University of California.  All rights reserved.
456055Srwatson *
556055Srwatson * This code is derived from software developed by the Computer Systems
656055Srwatson * Engineering group at Lawrence Berkeley Laboratory under DARPA contract
756055Srwatson * BG 91-66 and contributed to Berkeley.
856055Srwatson *
956055Srwatson * Redistribution and use in source and binary forms, with or without
1056055Srwatson * modification, are permitted provided that the following conditions
1156055Srwatson * are met:
1256055Srwatson * 1. Redistributions of source code must retain the above copyright
1356055Srwatson *    notice, this list of conditions and the following disclaimer.
1456055Srwatson * 2. Redistributions in binary form must reproduce the above copyright
1556055Srwatson *    notice, this list of conditions and the following disclaimer in the
1656055Srwatson *    documentation and/or other materials provided with the distribution.
1756055Srwatson * 3. All advertising materials mentioning features or use of this software
1856055Srwatson *    must display the following acknowledgement:
1956055Srwatson *	This product includes software developed by the University of
2056055Srwatson *	California, Berkeley and its contributors.
2156055Srwatson * 4. Neither the name of the University nor the names of its contributors
2256055Srwatson *    may be used to endorse or promote products derived from this software
2356055Srwatson *    without specific prior written permission.
2456055Srwatson *
2556055Srwatson * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
2674191Srwatson * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2756055Srwatson * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2856055Srwatson * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
2956055Srwatson * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3056055Srwatson * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3156055Srwatson * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3256055Srwatson * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3356055Srwatson * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3475185Stmm * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3556055Srwatson * SUCH DAMAGE.
3675185Stmm */
3756055Srwatson
3856055Srwatson#if 0
3956055Srwatson#if defined(LIBC_SCCS) && !defined(lint)
4056055Srwatsonstatic char sccsid[] = "@(#)kvm_proc.c	8.3 (Berkeley) 9/23/93";
4156055Srwatson#endif /* LIBC_SCCS and not lint */
4256055Srwatson#endif
4356055Srwatson
4456055Srwatson#include <sys/cdefs.h>
4556055Srwatson__FBSDID("$FreeBSD: head/lib/libkvm/kvm_proc.c 112891 2003-03-31 22:57:55Z jeff $");
4656055Srwatson
4756055Srwatson/*
4856055Srwatson * Proc traversal interface for kvm.  ps and w are (probably) the exclusive
4956625Srwatson * users of this code, so we've factored it out into a separate module.
5056625Srwatson * Thus, we keep this grunge out of the other kvm applications (i.e.,
5156055Srwatson * most other applications are interested only in open/close/read/nlist).
5256055Srwatson */
5356055Srwatson
5456055Srwatson#include <sys/param.h>
5575928Sjedgar#define _WANT_UCRED	/* make ucred.h give us 'struct ucred' */
5675928Sjedgar#include <sys/ucred.h>
5775928Sjedgar#include <sys/user.h>
5875928Sjedgar#include <sys/proc.h>
5975928Sjedgar#include <sys/exec.h>
6075928Sjedgar#include <sys/stat.h>
6175928Sjedgar#include <sys/ioctl.h>
6275928Sjedgar#include <sys/tty.h>
6375928Sjedgar#include <sys/file.h>
6456055Srwatson#include <stdio.h>
6556055Srwatson#include <stdlib.h>
6691034Sjedgar#include <unistd.h>
6771142Srwatson#include <nlist.h>
6856055Srwatson#include <kvm.h>
6989831Sjedgar
7089831Sjedgar#include <vm/vm.h>
7189831Sjedgar#include <vm/vm_param.h>
7289831Sjedgar#include <vm/swap_pager.h>
7389831Sjedgar
7475928Sjedgar#include <sys/sysctl.h>
7575928Sjedgar
7656055Srwatson#include <limits.h>
7775928Sjedgar#include <memory.h>
7875928Sjedgar#include <paths.h>
7975928Sjedgar
8056055Srwatson#include "kvm_private.h"
8175928Sjedgar
8275928Sjedgar#define KREAD(kd, addr, obj) \
8375928Sjedgar	(kvm_read(kd, addr, (char *)(obj), sizeof(*obj)) != sizeof(*obj))
8475928Sjedgar
8556055Srwatson/*
8656055Srwatson * Read proc's from memory file into buffer bp, which has space to hold
8756055Srwatson * at most maxcnt procs.
8874191Srwatson */
8974191Srwatsonstatic int
9056055Srwatsonkvm_proclist(kd, what, arg, p, bp, maxcnt)
9156055Srwatson	kvm_t *kd;
9256055Srwatson	int what, arg;
9356055Srwatson	struct proc *p;
9470841Srwatson	struct kinfo_proc *bp;
9556055Srwatson	int maxcnt;
9656055Srwatson{
9756055Srwatson	int cnt = 0;
9856055Srwatson	struct kinfo_proc kinfo_proc, *kp;
9956055Srwatson	struct pgrp pgrp;
10056055Srwatson	struct session sess;
10174191Srwatson	struct tty tty;
10274191Srwatson	struct vmspace vmspace;
10356055Srwatson	struct procsig procsig;
10456055Srwatson	struct pstats pstats;
10556055Srwatson	struct ucred ucred;
10674191Srwatson	struct thread mtd;
10774191Srwatson	struct kse mke;
10856055Srwatson	struct ksegrp mkg;
10956055Srwatson	struct proc proc;
11056055Srwatson	struct proc pproc;
11156055Srwatson	struct timeval tv;
11256055Srwatson
11374191Srwatson	kp = &kinfo_proc;
11474191Srwatson	kp->ki_structsize = sizeof(kinfo_proc);
11574191Srwatson	for (; cnt < maxcnt && p != NULL; p = LIST_NEXT(&proc, p_list)) {
11656055Srwatson		memset(kp, 0, sizeof *kp);
11756055Srwatson		if (KREAD(kd, (u_long)p, &proc)) {
11856055Srwatson			_kvm_err(kd, kd->program, "can't read proc at %x", p);
11956055Srwatson			return (-1);
12056055Srwatson		}
12156055Srwatson		if (proc.p_state != PRS_ZOMBIE) {
12256055Srwatson			if (KREAD(kd, (u_long)TAILQ_FIRST(&proc.p_threads),
12356055Srwatson			    &mtd)) {
12456055Srwatson				_kvm_err(kd, kd->program,
12556055Srwatson				    "can't read thread at %x",
12656055Srwatson				    TAILQ_FIRST(&proc.p_threads));
12770841Srwatson				return (-1);
12856055Srwatson			}
12956055Srwatson			if (proc.p_flag & P_THREADED == 0) {
13056055Srwatson				if (KREAD(kd,
13156055Srwatson				    (u_long)TAILQ_FIRST(&proc.p_ksegrps),
13256055Srwatson				    &mkg)) {
13356055Srwatson					_kvm_err(kd, kd->program,
13474191Srwatson					    "can't read ksegrp at %x",
13574191Srwatson					    TAILQ_FIRST(&proc.p_ksegrps));
13656055Srwatson					return (-1);
13756055Srwatson				}
13856055Srwatson				if (KREAD(kd,
13956055Srwatson				    (u_long)TAILQ_FIRST(&mkg.kg_kseq), &mke)) {
14056055Srwatson					_kvm_err(kd, kd->program,
14174191Srwatson					    "can't read kse at %x",
14274191Srwatson					    TAILQ_FIRST(&mkg.kg_kseq));
14374191Srwatson					return (-1);
14456055Srwatson				}
14556055Srwatson			}
14656055Srwatson		}
14756055Srwatson		if (KREAD(kd, (u_long)proc.p_ucred, &ucred) == 0) {
14856055Srwatson			kp->ki_ruid = ucred.cr_ruid;
14956055Srwatson			kp->ki_svuid = ucred.cr_svuid;
15056055Srwatson			kp->ki_rgid = ucred.cr_rgid;
15156055Srwatson			kp->ki_svgid = ucred.cr_svgid;
15256055Srwatson			kp->ki_ngroups = ucred.cr_ngroups;
15356055Srwatson			bcopy(ucred.cr_groups, kp->ki_groups,
15470841Srwatson			    NGROUPS * sizeof(gid_t));
15556055Srwatson			kp->ki_uid = ucred.cr_uid;
15656055Srwatson		}
15756055Srwatson
15856055Srwatson		switch(what) {
15956055Srwatson
16056055Srwatson		case KERN_PROC_PID:
16174191Srwatson			if (proc.p_pid != (pid_t)arg)
16274191Srwatson				continue;
16356055Srwatson			break;
16456055Srwatson
16556055Srwatson		case KERN_PROC_UID:
16674191Srwatson			if (kp->ki_uid != (uid_t)arg)
16774191Srwatson				continue;
16856055Srwatson			break;
16956055Srwatson
17056055Srwatson		case KERN_PROC_RUID:
17156055Srwatson			if (kp->ki_ruid != (uid_t)arg)
17256055Srwatson				continue;
17374191Srwatson			break;
17474191Srwatson		}
17574191Srwatson		/*
17656055Srwatson		 * We're going to add another proc to the set.  If this
17756055Srwatson		 * will overflow the buffer, assume the reason is because
17856055Srwatson		 * nprocs (or the proc list) is corrupt and declare an error.
17956055Srwatson		 */
18056055Srwatson		if (cnt >= maxcnt) {
18156055Srwatson			_kvm_err(kd, kd->program, "nprocs corrupt");
18256055Srwatson			return (-1);
18356055Srwatson		}
18456055Srwatson		/*
18556055Srwatson		 * gather kinfo_proc
18670841Srwatson		 */
18756055Srwatson		kp->ki_paddr = p;
18856055Srwatson		kp->ki_addr = proc.p_uarea;
18956055Srwatson		/* kp->ki_kstack = proc.p_thread.td_kstack; XXXKSE */
19056055Srwatson		kp->ki_args = proc.p_args;
19156055Srwatson		kp->ki_tracep = proc.p_tracevp;
19256055Srwatson		kp->ki_textvp = proc.p_textvp;
19374191Srwatson		kp->ki_fd = proc.p_fd;
19474191Srwatson		kp->ki_vmspace = proc.p_vmspace;
19556055Srwatson		if (proc.p_procsig != NULL) {
19656055Srwatson			if (KREAD(kd, (u_long)proc.p_procsig, &procsig)) {
19756055Srwatson				_kvm_err(kd, kd->program,
19856055Srwatson				    "can't read procsig at %x", proc.p_procsig);
19956055Srwatson				return (-1);
20070841Srwatson			}
20156055Srwatson			kp->ki_sigignore = procsig.ps_sigignore;
20256055Srwatson			kp->ki_sigcatch = procsig.ps_sigcatch;
20356055Srwatson		}
20456055Srwatson		if ((proc.p_sflag & PS_INMEM) && proc.p_stats != NULL) {
20556055Srwatson			if (KREAD(kd, (u_long)proc.p_stats, &pstats)) {
20656055Srwatson				_kvm_err(kd, kd->program,
20774191Srwatson				    "can't read stats at %x", proc.p_stats);
20874191Srwatson				return (-1);
20956055Srwatson			}
21056055Srwatson			kp->ki_start = pstats.p_start;
21156055Srwatson			kp->ki_rusage = pstats.p_ru;
21256055Srwatson			kp->ki_childtime.tv_sec = pstats.p_cru.ru_utime.tv_sec +
21356055Srwatson			    pstats.p_cru.ru_stime.tv_sec;
21470841Srwatson			kp->ki_childtime.tv_usec =
21556055Srwatson			    pstats.p_cru.ru_utime.tv_usec +
21656055Srwatson			    pstats.p_cru.ru_stime.tv_usec;
21756055Srwatson		}
21856055Srwatson		if (proc.p_oppid)
21956055Srwatson			kp->ki_ppid = proc.p_oppid;
22056055Srwatson		else if (proc.p_pptr) {
22156055Srwatson			if (KREAD(kd, (u_long)proc.p_pptr, &pproc)) {
22270841Srwatson				_kvm_err(kd, kd->program,
22356055Srwatson				    "can't read pproc at %x", proc.p_pptr);
22456055Srwatson				return (-1);
22556055Srwatson			}
22656055Srwatson			kp->ki_ppid = pproc.p_pid;
22756055Srwatson		} else
22856055Srwatson			kp->ki_ppid = 0;
22956055Srwatson		if (proc.p_pgrp == NULL)
23056055Srwatson			goto nopgrp;
23156055Srwatson		if (KREAD(kd, (u_long)proc.p_pgrp, &pgrp)) {
23256055Srwatson			_kvm_err(kd, kd->program, "can't read pgrp at %x",
23356055Srwatson				 proc.p_pgrp);
23471142Srwatson			return (-1);
23556055Srwatson		}
236		kp->ki_pgid = pgrp.pg_id;
237		kp->ki_jobc = pgrp.pg_jobc;
238		if (KREAD(kd, (u_long)pgrp.pg_session, &sess)) {
239			_kvm_err(kd, kd->program, "can't read session at %x",
240				pgrp.pg_session);
241			return (-1);
242		}
243		kp->ki_sid = sess.s_sid;
244		(void)memcpy(kp->ki_login, sess.s_login,
245						sizeof(kp->ki_login));
246		kp->ki_kiflag = sess.s_ttyvp ? KI_CTTY : 0;
247		if (sess.s_leader == p)
248			kp->ki_kiflag |= KI_SLEADER;
249		if ((proc.p_flag & P_CONTROLT) && sess.s_ttyp != NULL) {
250			if (KREAD(kd, (u_long)sess.s_ttyp, &tty)) {
251				_kvm_err(kd, kd->program,
252					 "can't read tty at %x", sess.s_ttyp);
253				return (-1);
254			}
255			kp->ki_tdev = tty.t_dev;
256			if (tty.t_pgrp != NULL) {
257				if (KREAD(kd, (u_long)tty.t_pgrp, &pgrp)) {
258					_kvm_err(kd, kd->program,
259						 "can't read tpgrp at %x",
260						tty.t_pgrp);
261					return (-1);
262				}
263				kp->ki_tpgid = pgrp.pg_id;
264			} else
265				kp->ki_tpgid = -1;
266			if (tty.t_session != NULL) {
267				if (KREAD(kd, (u_long)tty.t_session, &sess)) {
268					_kvm_err(kd, kd->program,
269					    "can't read session at %x",
270					    tty.t_session);
271					return (-1);
272				}
273				kp->ki_tsid = sess.s_sid;
274			}
275		} else {
276nopgrp:
277			kp->ki_tdev = NODEV;
278		}
279		if ((proc.p_state != PRS_ZOMBIE) && mtd.td_wmesg)
280			(void)kvm_read(kd, (u_long)mtd.td_wmesg,
281			    kp->ki_wmesg, WMESGLEN);
282
283#ifdef sparc
284		(void)kvm_read(kd, (u_long)&proc.p_vmspace->vm_rssize,
285		    (char *)&kp->ki_rssize,
286		    sizeof(kp->ki_rssize));
287		(void)kvm_read(kd, (u_long)&proc.p_vmspace->vm_tsize,
288		    (char *)&kp->ki_tsize,
289		    3 * sizeof(kp->ki_rssize));	/* XXX */
290#else
291		(void)kvm_read(kd, (u_long)proc.p_vmspace,
292		    (char *)&vmspace, sizeof(vmspace));
293		kp->ki_size = vmspace.vm_map.size;
294		kp->ki_rssize = vmspace.vm_swrss; /* XXX */
295		kp->ki_swrss = vmspace.vm_swrss;
296		kp->ki_tsize = vmspace.vm_tsize;
297		kp->ki_dsize = vmspace.vm_dsize;
298		kp->ki_ssize = vmspace.vm_ssize;
299#endif
300
301		switch (what) {
302
303		case KERN_PROC_PGRP:
304			if (kp->ki_pgid != (pid_t)arg)
305				continue;
306			break;
307
308		case KERN_PROC_TTY:
309			if ((proc.p_flag & P_CONTROLT) == 0 ||
310			     kp->ki_tdev != (dev_t)arg)
311				continue;
312			break;
313		}
314		if (proc.p_comm[0] != 0) {
315			strncpy(kp->ki_comm, proc.p_comm, MAXCOMLEN);
316			kp->ki_comm[MAXCOMLEN] = 0;
317		}
318		if ((proc.p_state != PRS_ZOMBIE) &&
319		    (mtd.td_blocked != 0)) {
320			kp->ki_kiflag |= KI_LOCKBLOCK;
321			if (mtd.td_lockname)
322				(void)kvm_read(kd,
323				    (u_long)mtd.td_lockname,
324				    kp->ki_lockname, LOCKNAMELEN);
325			kp->ki_lockname[LOCKNAMELEN] = 0;
326		}
327		bintime2timeval(&proc.p_runtime, &tv);
328		kp->ki_runtime = (u_int64_t)tv.tv_sec * 1000000 + tv.tv_usec;
329		kp->ki_pid = proc.p_pid;
330		kp->ki_siglist = proc.p_siglist;
331		SIGANDSET(kp->ki_siglist, mtd.td_siglist);
332		kp->ki_sigmask = mtd.td_sigmask;
333		kp->ki_xstat = proc.p_xstat;
334		kp->ki_acflag = proc.p_acflag;
335		kp->ki_lock = proc.p_lock;
336		if (proc.p_state != PRS_ZOMBIE) {
337			kp->ki_swtime = proc.p_swtime;
338			kp->ki_flag = proc.p_flag;
339			kp->ki_sflag = proc.p_sflag;
340			kp->ki_traceflag = proc.p_traceflag;
341			if (proc.p_state == PRS_NORMAL) {
342				if (TD_ON_RUNQ(&mtd) ||
343				    TD_CAN_RUN(&mtd) ||
344				    TD_IS_RUNNING(&mtd)) {
345					kp->ki_stat = SRUN;
346				} else if (mtd.td_state ==
347				    TDS_INHIBITED) {
348					if (P_SHOULDSTOP(&proc)) {
349						kp->ki_stat = SSTOP;
350					} else if (
351					    TD_IS_SLEEPING(&mtd)) {
352						kp->ki_stat = SSLEEP;
353					} else if (TD_ON_LOCK(&mtd)) {
354						kp->ki_stat = SLOCK;
355					} else {
356						kp->ki_stat = SWAIT;
357					}
358				}
359			} else {
360				kp->ki_stat = SIDL;
361			}
362			/* Stuff from the thread */
363			kp->ki_pri.pri_level = mtd.td_priority;
364			kp->ki_pri.pri_native = mtd.td_base_pri;
365			kp->ki_lastcpu = mtd.td_lastcpu;
366			kp->ki_wchan = mtd.td_wchan;
367
368			if (!(proc.p_flag & P_THREADED)) {
369				/* stuff from the ksegrp */
370				kp->ki_slptime = mkg.kg_slptime;
371				kp->ki_pri.pri_class = mkg.kg_pri_class;
372				kp->ki_pri.pri_user = mkg.kg_user_pri;
373				kp->ki_nice = mkg.kg_nice;
374				kp->ki_estcpu = mkg.kg_estcpu;
375
376				/* Stuff from the kse */
377				kp->ki_pctcpu = mke.ke_pctcpu;
378				kp->ki_rqindex = mke.ke_rqindex;
379				kp->ki_oncpu = mke.ke_oncpu;
380			} else {
381				kp->ki_oncpu = -1;
382				kp->ki_lastcpu = -1;
383				kp->ki_tdflags = -1;
384				/* All the rest are 0 for now */
385			}
386		} else {
387			kp->ki_stat = SZOMB;
388		}
389		bcopy(&kinfo_proc, bp, sizeof(kinfo_proc));
390		++bp;
391		++cnt;
392	}
393	return (cnt);
394}
395
396/*
397 * Build proc info array by reading in proc list from a crash dump.
398 * Return number of procs read.  maxcnt is the max we will read.
399 */
400static int
401kvm_deadprocs(kd, what, arg, a_allproc, a_zombproc, maxcnt)
402	kvm_t *kd;
403	int what, arg;
404	u_long a_allproc;
405	u_long a_zombproc;
406	int maxcnt;
407{
408	struct kinfo_proc *bp = kd->procbase;
409	int acnt, zcnt;
410	struct proc *p;
411
412	if (KREAD(kd, a_allproc, &p)) {
413		_kvm_err(kd, kd->program, "cannot read allproc");
414		return (-1);
415	}
416	acnt = kvm_proclist(kd, what, arg, p, bp, maxcnt);
417	if (acnt < 0)
418		return (acnt);
419
420	if (KREAD(kd, a_zombproc, &p)) {
421		_kvm_err(kd, kd->program, "cannot read zombproc");
422		return (-1);
423	}
424	zcnt = kvm_proclist(kd, what, arg, p, bp + acnt, maxcnt - acnt);
425	if (zcnt < 0)
426		zcnt = 0;
427
428	return (acnt + zcnt);
429}
430
431struct kinfo_proc *
432kvm_getprocs(kd, op, arg, cnt)
433	kvm_t *kd;
434	int op, arg;
435	int *cnt;
436{
437	int mib[4], st, nprocs;
438	size_t size;
439
440	if (kd->procbase != 0) {
441		free((void *)kd->procbase);
442		/*
443		 * Clear this pointer in case this call fails.  Otherwise,
444		 * kvm_close() will free it again.
445		 */
446		kd->procbase = 0;
447	}
448	if (ISALIVE(kd)) {
449		size = 0;
450		mib[0] = CTL_KERN;
451		mib[1] = KERN_PROC;
452		mib[2] = op;
453		mib[3] = arg;
454		st = sysctl(mib, op == KERN_PROC_ALL ? 3 : 4, NULL, &size, NULL, 0);
455		if (st == -1) {
456			_kvm_syserr(kd, kd->program, "kvm_getprocs");
457			return (0);
458		}
459		/*
460		 * We can't continue with a size of 0 because we pass
461		 * it to realloc() (via _kvm_realloc()), and passing 0
462		 * to realloc() results in undefined behavior.
463		 */
464		if (size == 0) {
465			/*
466			 * XXX: We should probably return an invalid,
467			 * but non-NULL, pointer here so any client
468			 * program trying to dereference it will
469			 * crash.  However, _kvm_freeprocs() calls
470			 * free() on kd->procbase if it isn't NULL,
471			 * and free()'ing a junk pointer isn't good.
472			 * Then again, _kvm_freeprocs() isn't used
473			 * anywhere . . .
474			 */
475			kd->procbase = _kvm_malloc(kd, 1);
476			goto liveout;
477		}
478		do {
479			size += size / 10;
480			kd->procbase = (struct kinfo_proc *)
481			    _kvm_realloc(kd, kd->procbase, size);
482			if (kd->procbase == 0)
483				return (0);
484			st = sysctl(mib, op == KERN_PROC_ALL ? 3 : 4,
485			    kd->procbase, &size, NULL, 0);
486		} while (st == -1 && errno == ENOMEM);
487		if (st == -1) {
488			_kvm_syserr(kd, kd->program, "kvm_getprocs");
489			return (0);
490		}
491		/*
492		 * We have to check the size again because sysctl()
493		 * may "round up" oldlenp if oldp is NULL; hence it
494		 * might've told us that there was data to get when
495		 * there really isn't any.
496		 */
497		if (size > 0 &&
498		    kd->procbase->ki_structsize != sizeof(struct kinfo_proc)) {
499			_kvm_err(kd, kd->program,
500			    "kinfo_proc size mismatch (expected %d, got %d)",
501			    sizeof(struct kinfo_proc),
502			    kd->procbase->ki_structsize);
503			return (0);
504		}
505liveout:
506		nprocs = size == 0 ? 0 : size / kd->procbase->ki_structsize;
507	} else {
508		struct nlist nl[4], *p;
509
510		nl[0].n_name = "_nprocs";
511		nl[1].n_name = "_allproc";
512		nl[2].n_name = "_zombproc";
513		nl[3].n_name = 0;
514
515		if (kvm_nlist(kd, nl) != 0) {
516			for (p = nl; p->n_type != 0; ++p)
517				;
518			_kvm_err(kd, kd->program,
519				 "%s: no such symbol", p->n_name);
520			return (0);
521		}
522		if (KREAD(kd, nl[0].n_value, &nprocs)) {
523			_kvm_err(kd, kd->program, "can't read nprocs");
524			return (0);
525		}
526		size = nprocs * sizeof(struct kinfo_proc);
527		kd->procbase = (struct kinfo_proc *)_kvm_malloc(kd, size);
528		if (kd->procbase == 0)
529			return (0);
530
531		nprocs = kvm_deadprocs(kd, op, arg, nl[1].n_value,
532				      nl[2].n_value, nprocs);
533#ifdef notdef
534		size = nprocs * sizeof(struct kinfo_proc);
535		(void)realloc(kd->procbase, size);
536#endif
537	}
538	*cnt = nprocs;
539	return (kd->procbase);
540}
541
542void
543_kvm_freeprocs(kd)
544	kvm_t *kd;
545{
546	if (kd->procbase) {
547		free(kd->procbase);
548		kd->procbase = 0;
549	}
550}
551
552void *
553_kvm_realloc(kd, p, n)
554	kvm_t *kd;
555	void *p;
556	size_t n;
557{
558	void *np = (void *)realloc(p, n);
559
560	if (np == 0) {
561		free(p);
562		_kvm_err(kd, kd->program, "out of memory");
563	}
564	return (np);
565}
566
567#ifndef MAX
568#define MAX(a, b) ((a) > (b) ? (a) : (b))
569#endif
570
571/*
572 * Read in an argument vector from the user address space of process kp.
573 * addr if the user-space base address of narg null-terminated contiguous
574 * strings.  This is used to read in both the command arguments and
575 * environment strings.  Read at most maxcnt characters of strings.
576 */
577static char **
578kvm_argv(kd, kp, addr, narg, maxcnt)
579	kvm_t *kd;
580	struct kinfo_proc *kp;
581	u_long addr;
582	int narg;
583	int maxcnt;
584{
585	char *np, *cp, *ep, *ap;
586	u_long oaddr = -1;
587	int len, cc;
588	char **argv;
589
590	/*
591	 * Check that there aren't an unreasonable number of agruments,
592	 * and that the address is in user space.
593	 */
594	if (narg > 512 || addr < VM_MIN_ADDRESS || addr >= VM_MAXUSER_ADDRESS)
595		return (0);
596
597	/*
598	 * kd->argv : work space for fetching the strings from the target
599	 *            process's space, and is converted for returning to caller
600	 */
601	if (kd->argv == 0) {
602		/*
603		 * Try to avoid reallocs.
604		 */
605		kd->argc = MAX(narg + 1, 32);
606		kd->argv = (char **)_kvm_malloc(kd, kd->argc *
607						sizeof(*kd->argv));
608		if (kd->argv == 0)
609			return (0);
610	} else if (narg + 1 > kd->argc) {
611		kd->argc = MAX(2 * kd->argc, narg + 1);
612		kd->argv = (char **)_kvm_realloc(kd, kd->argv, kd->argc *
613						sizeof(*kd->argv));
614		if (kd->argv == 0)
615			return (0);
616	}
617	/*
618	 * kd->argspc : returned to user, this is where the kd->argv
619	 *              arrays are left pointing to the collected strings.
620	 */
621	if (kd->argspc == 0) {
622		kd->argspc = (char *)_kvm_malloc(kd, PAGE_SIZE);
623		if (kd->argspc == 0)
624			return (0);
625		kd->arglen = PAGE_SIZE;
626	}
627	/*
628	 * kd->argbuf : used to pull in pages from the target process.
629	 *              the strings are copied out of here.
630	 */
631	if (kd->argbuf == 0) {
632		kd->argbuf = (char *)_kvm_malloc(kd, PAGE_SIZE);
633		if (kd->argbuf == 0)
634			return (0);
635	}
636
637	/* Pull in the target process'es argv vector */
638	cc = sizeof(char *) * narg;
639	if (kvm_uread(kd, kp, addr, (char *)kd->argv, cc) != cc)
640		return (0);
641	/*
642	 * ap : saved start address of string we're working on in kd->argspc
643	 * np : pointer to next place to write in kd->argspc
644	 * len: length of data in kd->argspc
645	 * argv: pointer to the argv vector that we are hunting around the
646	 *       target process space for, and converting to addresses in
647	 *       our address space (kd->argspc).
648	 */
649	ap = np = kd->argspc;
650	argv = kd->argv;
651	len = 0;
652	/*
653	 * Loop over pages, filling in the argument vector.
654	 * Note that the argv strings could be pointing *anywhere* in
655	 * the user address space and are no longer contiguous.
656	 * Note that *argv is modified when we are going to fetch a string
657	 * that crosses a page boundary.  We copy the next part of the string
658	 * into to "np" and eventually convert the pointer.
659	 */
660	while (argv < kd->argv + narg && *argv != 0) {
661
662		/* get the address that the current argv string is on */
663		addr = (u_long)*argv & ~(PAGE_SIZE - 1);
664
665		/* is it the same page as the last one? */
666		if (addr != oaddr) {
667			if (kvm_uread(kd, kp, addr, kd->argbuf, PAGE_SIZE) !=
668			    PAGE_SIZE)
669				return (0);
670			oaddr = addr;
671		}
672
673		/* offset within the page... kd->argbuf */
674		addr = (u_long)*argv & (PAGE_SIZE - 1);
675
676		/* cp = start of string, cc = count of chars in this chunk */
677		cp = kd->argbuf + addr;
678		cc = PAGE_SIZE - addr;
679
680		/* dont get more than asked for by user process */
681		if (maxcnt > 0 && cc > maxcnt - len)
682			cc = maxcnt - len;
683
684		/* pointer to end of string if we found it in this page */
685		ep = memchr(cp, '\0', cc);
686		if (ep != 0)
687			cc = ep - cp + 1;
688		/*
689		 * at this point, cc is the count of the chars that we are
690		 * going to retrieve this time. we may or may not have found
691		 * the end of it.  (ep points to the null if the end is known)
692		 */
693
694		/* will we exceed the malloc/realloced buffer? */
695		if (len + cc > kd->arglen) {
696			int off;
697			char **pp;
698			char *op = kd->argspc;
699
700			kd->arglen *= 2;
701			kd->argspc = (char *)_kvm_realloc(kd, kd->argspc,
702							  kd->arglen);
703			if (kd->argspc == 0)
704				return (0);
705			/*
706			 * Adjust argv pointers in case realloc moved
707			 * the string space.
708			 */
709			off = kd->argspc - op;
710			for (pp = kd->argv; pp < argv; pp++)
711				*pp += off;
712			ap += off;
713			np += off;
714		}
715		/* np = where to put the next part of the string in kd->argspc*/
716		/* np is kinda redundant.. could use "kd->argspc + len" */
717		memcpy(np, cp, cc);
718		np += cc;	/* inc counters */
719		len += cc;
720
721		/*
722		 * if end of string found, set the *argv pointer to the
723		 * saved beginning of string, and advance. argv points to
724		 * somewhere in kd->argv..  This is initially relative
725		 * to the target process, but when we close it off, we set
726		 * it to point in our address space.
727		 */
728		if (ep != 0) {
729			*argv++ = ap;
730			ap = np;
731		} else {
732			/* update the address relative to the target process */
733			*argv += cc;
734		}
735
736		if (maxcnt > 0 && len >= maxcnt) {
737			/*
738			 * We're stopping prematurely.  Terminate the
739			 * current string.
740			 */
741			if (ep == 0) {
742				*np = '\0';
743				*argv++ = ap;
744			}
745			break;
746		}
747	}
748	/* Make sure argv is terminated. */
749	*argv = 0;
750	return (kd->argv);
751}
752
753static void
754ps_str_a(p, addr, n)
755	struct ps_strings *p;
756	u_long *addr;
757	int *n;
758{
759	*addr = (u_long)p->ps_argvstr;
760	*n = p->ps_nargvstr;
761}
762
763static void
764ps_str_e(p, addr, n)
765	struct ps_strings *p;
766	u_long *addr;
767	int *n;
768{
769	*addr = (u_long)p->ps_envstr;
770	*n = p->ps_nenvstr;
771}
772
773/*
774 * Determine if the proc indicated by p is still active.
775 * This test is not 100% foolproof in theory, but chances of
776 * being wrong are very low.
777 */
778static int
779proc_verify(curkp)
780	struct kinfo_proc *curkp;
781{
782	struct kinfo_proc newkp;
783	int mib[4];
784	size_t len;
785
786	mib[0] = CTL_KERN;
787	mib[1] = KERN_PROC;
788	mib[2] = KERN_PROC_PID;
789	mib[3] = curkp->ki_pid;
790	len = sizeof(newkp);
791	if (sysctl(mib, 4, &newkp, &len, NULL, 0) == -1)
792		return (0);
793	return (curkp->ki_pid == newkp.ki_pid &&
794	    (newkp.ki_stat != SZOMB || curkp->ki_stat == SZOMB));
795}
796
797static char **
798kvm_doargv(kd, kp, nchr, info)
799	kvm_t *kd;
800	struct kinfo_proc *kp;
801	int nchr;
802	void (*info)(struct ps_strings *, u_long *, int *);
803{
804	char **ap;
805	u_long addr;
806	int cnt;
807	static struct ps_strings arginfo;
808	static u_long ps_strings;
809	size_t len;
810
811	if (ps_strings == NULL) {
812		len = sizeof(ps_strings);
813		if (sysctlbyname("kern.ps_strings", &ps_strings, &len, NULL,
814		    0) == -1)
815			ps_strings = PS_STRINGS;
816	}
817
818	/*
819	 * Pointers are stored at the top of the user stack.
820	 */
821	if (kp->ki_stat == SZOMB ||
822	    kvm_uread(kd, kp, ps_strings, (char *)&arginfo,
823		      sizeof(arginfo)) != sizeof(arginfo))
824		return (0);
825
826	(*info)(&arginfo, &addr, &cnt);
827	if (cnt == 0)
828		return (0);
829	ap = kvm_argv(kd, kp, addr, cnt, nchr);
830	/*
831	 * For live kernels, make sure this process didn't go away.
832	 */
833	if (ap != 0 && ISALIVE(kd) && !proc_verify(kp))
834		ap = 0;
835	return (ap);
836}
837
838/*
839 * Get the command args.  This code is now machine independent.
840 */
841char **
842kvm_getargv(kd, kp, nchr)
843	kvm_t *kd;
844	const struct kinfo_proc *kp;
845	int nchr;
846{
847	int oid[4];
848	int i;
849	size_t bufsz;
850	static unsigned long buflen;
851	static char *buf, *p;
852	static char **bufp;
853	static int argc;
854
855	if (!ISALIVE(kd)) {
856		_kvm_err(kd, kd->program,
857		    "cannot read user space from dead kernel");
858		return (0);
859	}
860
861	if (!buflen) {
862		bufsz = sizeof(buflen);
863		i = sysctlbyname("kern.ps_arg_cache_limit",
864		    &buflen, &bufsz, NULL, 0);
865		if (i == -1) {
866			buflen = 0;
867		} else {
868			buf = malloc(buflen);
869			if (buf == NULL)
870				buflen = 0;
871			argc = 32;
872			bufp = malloc(sizeof(char *) * argc);
873		}
874	}
875	if (buf != NULL) {
876		oid[0] = CTL_KERN;
877		oid[1] = KERN_PROC;
878		oid[2] = KERN_PROC_ARGS;
879		oid[3] = kp->ki_pid;
880		bufsz = buflen;
881		i = sysctl(oid, 4, buf, &bufsz, 0, 0);
882		if (i == 0 && bufsz > 0) {
883			i = 0;
884			p = buf;
885			do {
886				bufp[i++] = p;
887				p += strlen(p) + 1;
888				if (i >= argc) {
889					argc += argc;
890					bufp = realloc(bufp,
891					    sizeof(char *) * argc);
892				}
893			} while (p < buf + bufsz);
894			bufp[i++] = 0;
895			return (bufp);
896		}
897	}
898	if (kp->ki_flag & P_SYSTEM)
899		return (NULL);
900	return (kvm_doargv(kd, kp, nchr, ps_str_a));
901}
902
903char **
904kvm_getenvv(kd, kp, nchr)
905	kvm_t *kd;
906	const struct kinfo_proc *kp;
907	int nchr;
908{
909	return (kvm_doargv(kd, kp, nchr, ps_str_e));
910}
911
912/*
913 * Read from user space.  The user context is given by p.
914 */
915ssize_t
916kvm_uread(kd, kp, uva, buf, len)
917	kvm_t *kd;
918	struct kinfo_proc *kp;
919	u_long uva;
920	char *buf;
921	size_t len;
922{
923	char *cp;
924	char procfile[MAXPATHLEN];
925	ssize_t amount;
926	int fd;
927
928	if (!ISALIVE(kd)) {
929		_kvm_err(kd, kd->program,
930		    "cannot read user space from dead kernel");
931		return (0);
932	}
933
934	sprintf(procfile, "/proc/%d/mem", kp->ki_pid);
935	fd = open(procfile, O_RDONLY, 0);
936	if (fd < 0) {
937		_kvm_err(kd, kd->program, "cannot open %s", procfile);
938		close(fd);
939		return (0);
940	}
941
942	cp = buf;
943	while (len > 0) {
944		errno = 0;
945		if (lseek(fd, (off_t)uva, 0) == -1 && errno != 0) {
946			_kvm_err(kd, kd->program, "invalid address (%x) in %s",
947			    uva, procfile);
948			break;
949		}
950		amount = read(fd, cp, len);
951		if (amount < 0) {
952			_kvm_syserr(kd, kd->program, "error reading %s",
953			    procfile);
954			break;
955		}
956		if (amount == 0) {
957			_kvm_err(kd, kd->program, "EOF reading %s", procfile);
958			break;
959		}
960		cp += amount;
961		uva += amount;
962		len -= amount;
963	}
964
965	close(fd);
966	return ((ssize_t)(cp - buf));
967}
968