kvm_proc.c revision 104248
1238384Sjkim/*-
2238384Sjkim * Copyright (c) 1989, 1992, 1993
3238384Sjkim *	The Regents of the University of California.  All rights reserved.
4238384Sjkim *
5238384Sjkim * This code is derived from software developed by the Computer Systems
6238384Sjkim * Engineering group at Lawrence Berkeley Laboratory under DARPA contract
7238384Sjkim * BG 91-66 and contributed to Berkeley.
8238384Sjkim *
9238384Sjkim * Redistribution and use in source and binary forms, with or without
10238384Sjkim * modification, are permitted provided that the following conditions
11238384Sjkim * are met:
12238384Sjkim * 1. Redistributions of source code must retain the above copyright
13238384Sjkim *    notice, this list of conditions and the following disclaimer.
14238384Sjkim * 2. Redistributions in binary form must reproduce the above copyright
15238384Sjkim *    notice, this list of conditions and the following disclaimer in the
16238384Sjkim *    documentation and/or other materials provided with the distribution.
17238384Sjkim * 3. All advertising materials mentioning features or use of this software
18238384Sjkim *    must display the following acknowledgement:
19238384Sjkim *	This product includes software developed by the University of
20280304Sjkim *	California, Berkeley and its contributors.
21238384Sjkim * 4. Neither the name of the University nor the names of its contributors
22238384Sjkim *    may be used to endorse or promote products derived from this software
23280304Sjkim *    without specific prior written permission.
24238384Sjkim *
25238384Sjkim * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26238384Sjkim * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27238384Sjkim * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28280304Sjkim * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29238384Sjkim * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30238384Sjkim * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31238384Sjkim * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32238384Sjkim * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33238384Sjkim * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34238384Sjkim * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35238384Sjkim * SUCH DAMAGE.
36238384Sjkim */
37238384Sjkim
38238384Sjkim#if 0
39238384Sjkim#if defined(LIBC_SCCS) && !defined(lint)
40238384Sjkimstatic char sccsid[] = "@(#)kvm_proc.c	8.3 (Berkeley) 9/23/93";
41238384Sjkim#endif /* LIBC_SCCS and not lint */
42238384Sjkim#endif
43238384Sjkim
44238384Sjkim#include <sys/cdefs.h>
45238384Sjkim__FBSDID("$FreeBSD: head/lib/libkvm/kvm_proc.c 104248 2002-10-01 00:28:14Z jmallett $");
46280304Sjkim
47238384Sjkim/*
48280304Sjkim * Proc traversal interface for kvm.  ps and w are (probably) the exclusive
49238384Sjkim * users of this code, so we've factored it out into a separate module.
50280304Sjkim * Thus, we keep this grunge out of the other kvm applications (i.e.,
51 * most other applications are interested only in open/close/read/nlist).
52 */
53
54#include <sys/param.h>
55#define _WANT_UCRED	/* make ucred.h give us 'struct ucred' */
56#include <sys/ucred.h>
57#include <sys/user.h>
58#include <sys/proc.h>
59#include <sys/exec.h>
60#include <sys/stat.h>
61#include <sys/ioctl.h>
62#include <sys/tty.h>
63#include <sys/file.h>
64#include <stdio.h>
65#include <stdlib.h>
66#include <unistd.h>
67#include <nlist.h>
68#include <kvm.h>
69
70#include <vm/vm.h>
71#include <vm/vm_param.h>
72#include <vm/swap_pager.h>
73
74#include <sys/sysctl.h>
75
76#include <limits.h>
77#include <memory.h>
78#include <paths.h>
79
80#include "kvm_private.h"
81
82#define KREAD(kd, addr, obj) \
83	(kvm_read(kd, addr, (char *)(obj), sizeof(*obj)) != sizeof(*obj))
84
85/*
86 * Read proc's from memory file into buffer bp, which has space to hold
87 * at most maxcnt procs.
88 */
89static int
90kvm_proclist(kd, what, arg, p, bp, maxcnt)
91	kvm_t *kd;
92	int what, arg;
93	struct proc *p;
94	struct kinfo_proc *bp;
95	int maxcnt;
96{
97	int cnt = 0;
98	struct kinfo_proc kinfo_proc, *kp;
99	struct pgrp pgrp;
100	struct session sess;
101	struct tty tty;
102	struct vmspace vmspace;
103	struct procsig procsig;
104	struct pstats pstats;
105	struct ucred ucred;
106	struct thread mtd;
107	struct kse mke;
108	struct ksegrp mkg;
109	struct proc proc;
110	struct proc pproc;
111	struct timeval tv;
112
113	kp = &kinfo_proc;
114	kp->ki_structsize = sizeof(kinfo_proc);
115	for (; cnt < maxcnt && p != NULL; p = LIST_NEXT(&proc, p_list)) {
116		memset(kp, 0, sizeof *kp);
117		if (KREAD(kd, (u_long)p, &proc)) {
118			_kvm_err(kd, kd->program, "can't read proc at %x", p);
119			return (-1);
120		}
121		if (proc.p_state != PRS_ZOMBIE) {
122			if (KREAD(kd, (u_long)TAILQ_FIRST(&proc.p_threads),
123			    &mtd)) {
124				_kvm_err(kd, kd->program,
125				    "can't read thread at %x",
126				    TAILQ_FIRST(&proc.p_threads));
127				return (-1);
128			}
129			if (proc.p_flag & P_KSES == 0) {
130				if (KREAD(kd,
131				    (u_long)TAILQ_FIRST(&proc.p_ksegrps),
132				    &mkg)) {
133					_kvm_err(kd, kd->program,
134					    "can't read ksegrp at %x",
135					    TAILQ_FIRST(&proc.p_ksegrps));
136					return (-1);
137				}
138				if (KREAD(kd,
139				    (u_long)TAILQ_FIRST(&mkg.kg_kseq), &mke)) {
140					_kvm_err(kd, kd->program,
141					    "can't read kse at %x",
142					    TAILQ_FIRST(&mkg.kg_kseq));
143					return (-1);
144				}
145			}
146		}
147		if (KREAD(kd, (u_long)proc.p_ucred, &ucred) == 0) {
148			kp->ki_ruid = ucred.cr_ruid;
149			kp->ki_svuid = ucred.cr_svuid;
150			kp->ki_rgid = ucred.cr_rgid;
151			kp->ki_svgid = ucred.cr_svgid;
152			kp->ki_ngroups = ucred.cr_ngroups;
153			bcopy(ucred.cr_groups, kp->ki_groups,
154			    NGROUPS * sizeof(gid_t));
155			kp->ki_uid = ucred.cr_uid;
156		}
157
158		switch(what) {
159
160		case KERN_PROC_PID:
161			if (proc.p_pid != (pid_t)arg)
162				continue;
163			break;
164
165		case KERN_PROC_UID:
166			if (kp->ki_uid != (uid_t)arg)
167				continue;
168			break;
169
170		case KERN_PROC_RUID:
171			if (kp->ki_ruid != (uid_t)arg)
172				continue;
173			break;
174		}
175		/*
176		 * We're going to add another proc to the set.  If this
177		 * will overflow the buffer, assume the reason is because
178		 * nprocs (or the proc list) is corrupt and declare an error.
179		 */
180		if (cnt >= maxcnt) {
181			_kvm_err(kd, kd->program, "nprocs corrupt");
182			return (-1);
183		}
184		/*
185		 * gather kinfo_proc
186		 */
187		kp->ki_paddr = p;
188		kp->ki_addr = proc.p_uarea;
189		/* kp->ki_kstack = proc.p_thread.td_kstack; XXXKSE */
190		kp->ki_args = proc.p_args;
191		kp->ki_tracep = proc.p_tracep;
192		kp->ki_textvp = proc.p_textvp;
193		kp->ki_fd = proc.p_fd;
194		kp->ki_vmspace = proc.p_vmspace;
195		/*
196		 * The pending signal list is private to the kernel, as the
197		 * queue cannot be exported, and the interfaces used are
198		 * not exposed to userland.  For compatability, just install
199		 * an empty signal set.
200		 */
201		SIGEMPTYSET(kp->ki_siglist);
202		if (proc.p_procsig != NULL) {
203			if (KREAD(kd, (u_long)proc.p_procsig, &procsig)) {
204				_kvm_err(kd, kd->program,
205				    "can't read procsig at %x", proc.p_procsig);
206				return (-1);
207			}
208			kp->ki_sigignore = procsig.ps_sigignore;
209			kp->ki_sigcatch = procsig.ps_sigcatch;
210		}
211		if ((proc.p_sflag & PS_INMEM) && proc.p_stats != NULL) {
212			if (KREAD(kd, (u_long)proc.p_stats, &pstats)) {
213				_kvm_err(kd, kd->program,
214				    "can't read stats at %x", proc.p_stats);
215				return (-1);
216			}
217			kp->ki_start = pstats.p_start;
218			kp->ki_rusage = pstats.p_ru;
219			kp->ki_childtime.tv_sec = pstats.p_cru.ru_utime.tv_sec +
220			    pstats.p_cru.ru_stime.tv_sec;
221			kp->ki_childtime.tv_usec =
222			    pstats.p_cru.ru_utime.tv_usec +
223			    pstats.p_cru.ru_stime.tv_usec;
224		}
225		if (proc.p_oppid)
226			kp->ki_ppid = proc.p_oppid;
227		else if (proc.p_pptr) {
228			if (KREAD(kd, (u_long)proc.p_pptr, &pproc)) {
229				_kvm_err(kd, kd->program,
230				    "can't read pproc at %x", proc.p_pptr);
231				return (-1);
232			}
233			kp->ki_ppid = pproc.p_pid;
234		} else
235			kp->ki_ppid = 0;
236		if (proc.p_pgrp == NULL)
237			goto nopgrp;
238		if (KREAD(kd, (u_long)proc.p_pgrp, &pgrp)) {
239			_kvm_err(kd, kd->program, "can't read pgrp at %x",
240				 proc.p_pgrp);
241			return (-1);
242		}
243		kp->ki_pgid = pgrp.pg_id;
244		kp->ki_jobc = pgrp.pg_jobc;
245		if (KREAD(kd, (u_long)pgrp.pg_session, &sess)) {
246			_kvm_err(kd, kd->program, "can't read session at %x",
247				pgrp.pg_session);
248			return (-1);
249		}
250		kp->ki_sid = sess.s_sid;
251		(void)memcpy(kp->ki_login, sess.s_login,
252						sizeof(kp->ki_login));
253		kp->ki_kiflag = sess.s_ttyvp ? KI_CTTY : 0;
254		if (sess.s_leader == p)
255			kp->ki_kiflag |= KI_SLEADER;
256		if ((proc.p_flag & P_CONTROLT) && sess.s_ttyp != NULL) {
257			if (KREAD(kd, (u_long)sess.s_ttyp, &tty)) {
258				_kvm_err(kd, kd->program,
259					 "can't read tty at %x", sess.s_ttyp);
260				return (-1);
261			}
262			kp->ki_tdev = tty.t_dev;
263			if (tty.t_pgrp != NULL) {
264				if (KREAD(kd, (u_long)tty.t_pgrp, &pgrp)) {
265					_kvm_err(kd, kd->program,
266						 "can't read tpgrp at %x",
267						tty.t_pgrp);
268					return (-1);
269				}
270				kp->ki_tpgid = pgrp.pg_id;
271			} else
272				kp->ki_tpgid = -1;
273			if (tty.t_session != NULL) {
274				if (KREAD(kd, (u_long)tty.t_session, &sess)) {
275					_kvm_err(kd, kd->program,
276					    "can't read session at %x",
277					    tty.t_session);
278					return (-1);
279				}
280				kp->ki_tsid = sess.s_sid;
281			}
282		} else {
283nopgrp:
284			kp->ki_tdev = NODEV;
285		}
286		if ((proc.p_state != PRS_ZOMBIE) && mtd.td_wmesg)
287			(void)kvm_read(kd, (u_long)mtd.td_wmesg,
288			    kp->ki_wmesg, WMESGLEN);
289
290#ifdef sparc
291		(void)kvm_read(kd, (u_long)&proc.p_vmspace->vm_rssize,
292		    (char *)&kp->ki_rssize,
293		    sizeof(kp->ki_rssize));
294		(void)kvm_read(kd, (u_long)&proc.p_vmspace->vm_tsize,
295		    (char *)&kp->ki_tsize,
296		    3 * sizeof(kp->ki_rssize));	/* XXX */
297#else
298		(void)kvm_read(kd, (u_long)proc.p_vmspace,
299		    (char *)&vmspace, sizeof(vmspace));
300		kp->ki_size = vmspace.vm_map.size;
301		kp->ki_rssize = vmspace.vm_swrss; /* XXX */
302		kp->ki_swrss = vmspace.vm_swrss;
303		kp->ki_tsize = vmspace.vm_tsize;
304		kp->ki_dsize = vmspace.vm_dsize;
305		kp->ki_ssize = vmspace.vm_ssize;
306#endif
307
308		switch (what) {
309
310		case KERN_PROC_PGRP:
311			if (kp->ki_pgid != (pid_t)arg)
312				continue;
313			break;
314
315		case KERN_PROC_TTY:
316			if ((proc.p_flag & P_CONTROLT) == 0 ||
317			     kp->ki_tdev != (dev_t)arg)
318				continue;
319			break;
320		}
321		if (proc.p_comm[0] != 0) {
322			strncpy(kp->ki_comm, proc.p_comm, MAXCOMLEN);
323			kp->ki_comm[MAXCOMLEN] = 0;
324		}
325		if ((proc.p_state != PRS_ZOMBIE) &&
326		    (mtd.td_blocked != 0)) {
327			kp->ki_kiflag |= KI_MTXBLOCK;
328			if (mtd.td_mtxname)
329				(void)kvm_read(kd,
330				    (u_long)mtd.td_mtxname,
331				    kp->ki_mtxname, MTXNAMELEN);
332			kp->ki_mtxname[MTXNAMELEN] = 0;
333		}
334		bintime2timeval(&proc.p_runtime, &tv);
335		kp->ki_runtime = (u_int64_t)tv.tv_sec * 1000000 + tv.tv_usec;
336		kp->ki_pid = proc.p_pid;
337		kp->ki_sigmask = proc.p_sigmask;
338		kp->ki_xstat = proc.p_xstat;
339		kp->ki_acflag = proc.p_acflag;
340		kp->ki_lock = proc.p_lock;
341		if (proc.p_state != PRS_ZOMBIE) {
342			kp->ki_swtime = proc.p_swtime;
343			kp->ki_flag = proc.p_flag;
344			kp->ki_sflag = proc.p_sflag;
345			kp->ki_traceflag = proc.p_traceflag;
346			if (proc.p_state == PRS_NORMAL) {
347				if (TD_ON_RUNQ(&mtd) ||
348				    TD_CAN_RUN(&mtd) ||
349				    TD_IS_RUNNING(&mtd)) {
350					kp->ki_stat = SRUN;
351				} else if (mtd.td_state ==
352				    TDS_INHIBITED) {
353					if (P_SHOULDSTOP(&proc)) {
354						kp->ki_stat = SSTOP;
355					} else if (
356					    TD_IS_SLEEPING(&mtd)) {
357						kp->ki_stat = SSLEEP;
358					} else if (TD_ON_MUTEX(&mtd)) {
359						kp->ki_stat = SMTX;
360					} else {
361						kp->ki_stat = SWAIT;
362					}
363				}
364			} else {
365				kp->ki_stat = SIDL;
366			}
367			/* Stuff from the thread */
368			kp->ki_pri.pri_level = mtd.td_priority;
369			kp->ki_pri.pri_native = mtd.td_base_pri;
370			kp->ki_lastcpu = mtd.td_lastcpu;
371			kp->ki_wchan = mtd.td_wchan;
372
373			if (!(proc.p_flag & P_KSES)) {
374				/* stuff from the ksegrp */
375				kp->ki_slptime = mkg.kg_slptime;
376				kp->ki_pri.pri_class = mkg.kg_pri_class;
377				kp->ki_pri.pri_user = mkg.kg_user_pri;
378				kp->ki_nice = mkg.kg_nice;
379				kp->ki_estcpu = mkg.kg_estcpu;
380
381				/* Stuff from the kse */
382				kp->ki_pctcpu = mke.ke_pctcpu;
383				kp->ki_rqindex = mke.ke_rqindex;
384				kp->ki_oncpu = mke.ke_oncpu;
385			} else {
386				kp->ki_oncpu = -1;
387				kp->ki_lastcpu = -1;
388				kp->ki_tdflags = -1;
389				/* All the rest are 0 for now */
390			}
391		} else {
392			kp->ki_stat = SZOMB;
393		}
394		bcopy(&kinfo_proc, bp, sizeof(kinfo_proc));
395		++bp;
396		++cnt;
397	}
398	return (cnt);
399}
400
401/*
402 * Build proc info array by reading in proc list from a crash dump.
403 * Return number of procs read.  maxcnt is the max we will read.
404 */
405static int
406kvm_deadprocs(kd, what, arg, a_allproc, a_zombproc, maxcnt)
407	kvm_t *kd;
408	int what, arg;
409	u_long a_allproc;
410	u_long a_zombproc;
411	int maxcnt;
412{
413	struct kinfo_proc *bp = kd->procbase;
414	int acnt, zcnt;
415	struct proc *p;
416
417	if (KREAD(kd, a_allproc, &p)) {
418		_kvm_err(kd, kd->program, "cannot read allproc");
419		return (-1);
420	}
421	acnt = kvm_proclist(kd, what, arg, p, bp, maxcnt);
422	if (acnt < 0)
423		return (acnt);
424
425	if (KREAD(kd, a_zombproc, &p)) {
426		_kvm_err(kd, kd->program, "cannot read zombproc");
427		return (-1);
428	}
429	zcnt = kvm_proclist(kd, what, arg, p, bp + acnt, maxcnt - acnt);
430	if (zcnt < 0)
431		zcnt = 0;
432
433	return (acnt + zcnt);
434}
435
436struct kinfo_proc *
437kvm_getprocs(kd, op, arg, cnt)
438	kvm_t *kd;
439	int op, arg;
440	int *cnt;
441{
442	int mib[4], st, nprocs;
443	size_t size;
444
445	if (kd->procbase != 0) {
446		free((void *)kd->procbase);
447		/*
448		 * Clear this pointer in case this call fails.  Otherwise,
449		 * kvm_close() will free it again.
450		 */
451		kd->procbase = 0;
452	}
453	if (ISALIVE(kd)) {
454		size = 0;
455		mib[0] = CTL_KERN;
456		mib[1] = KERN_PROC;
457		mib[2] = op;
458		mib[3] = arg;
459		st = sysctl(mib, op == KERN_PROC_ALL ? 3 : 4, NULL, &size, NULL, 0);
460		if (st == -1) {
461			_kvm_syserr(kd, kd->program, "kvm_getprocs");
462			return (0);
463		}
464		/*
465		 * We can't continue with a size of 0 because we pass
466		 * it to realloc() (via _kvm_realloc()), and passing 0
467		 * to realloc() results in undefined behavior.
468		 */
469		if (size == 0) {
470			/*
471			 * XXX: We should probably return an invalid,
472			 * but non-NULL, pointer here so any client
473			 * program trying to dereference it will
474			 * crash.  However, _kvm_freeprocs() calls
475			 * free() on kd->procbase if it isn't NULL,
476			 * and free()'ing a junk pointer isn't good.
477			 * Then again, _kvm_freeprocs() isn't used
478			 * anywhere . . .
479			 */
480			kd->procbase = _kvm_malloc(kd, 1);
481			goto liveout;
482		}
483		do {
484			size += size / 10;
485			kd->procbase = (struct kinfo_proc *)
486			    _kvm_realloc(kd, kd->procbase, size);
487			if (kd->procbase == 0)
488				return (0);
489			st = sysctl(mib, op == KERN_PROC_ALL ? 3 : 4,
490			    kd->procbase, &size, NULL, 0);
491		} while (st == -1 && errno == ENOMEM);
492		if (st == -1) {
493			_kvm_syserr(kd, kd->program, "kvm_getprocs");
494			return (0);
495		}
496		/*
497		 * We have to check the size again because sysctl()
498		 * may "round up" oldlenp if oldp is NULL; hence it
499		 * might've told us that there was data to get when
500		 * there really isn't any.
501		 */
502		if (size > 0 &&
503		    kd->procbase->ki_structsize != sizeof(struct kinfo_proc)) {
504			_kvm_err(kd, kd->program,
505			    "kinfo_proc size mismatch (expected %d, got %d)",
506			    sizeof(struct kinfo_proc),
507			    kd->procbase->ki_structsize);
508			return (0);
509		}
510liveout:
511		nprocs = size == 0 ? 0 : size / kd->procbase->ki_structsize;
512	} else {
513		struct nlist nl[4], *p;
514
515		nl[0].n_name = "_nprocs";
516		nl[1].n_name = "_allproc";
517		nl[2].n_name = "_zombproc";
518		nl[3].n_name = 0;
519
520		if (kvm_nlist(kd, nl) != 0) {
521			for (p = nl; p->n_type != 0; ++p)
522				;
523			_kvm_err(kd, kd->program,
524				 "%s: no such symbol", p->n_name);
525			return (0);
526		}
527		if (KREAD(kd, nl[0].n_value, &nprocs)) {
528			_kvm_err(kd, kd->program, "can't read nprocs");
529			return (0);
530		}
531		size = nprocs * sizeof(struct kinfo_proc);
532		kd->procbase = (struct kinfo_proc *)_kvm_malloc(kd, size);
533		if (kd->procbase == 0)
534			return (0);
535
536		nprocs = kvm_deadprocs(kd, op, arg, nl[1].n_value,
537				      nl[2].n_value, nprocs);
538#ifdef notdef
539		size = nprocs * sizeof(struct kinfo_proc);
540		(void)realloc(kd->procbase, size);
541#endif
542	}
543	*cnt = nprocs;
544	return (kd->procbase);
545}
546
547void
548_kvm_freeprocs(kd)
549	kvm_t *kd;
550{
551	if (kd->procbase) {
552		free(kd->procbase);
553		kd->procbase = 0;
554	}
555}
556
557void *
558_kvm_realloc(kd, p, n)
559	kvm_t *kd;
560	void *p;
561	size_t n;
562{
563	void *np = (void *)realloc(p, n);
564
565	if (np == 0) {
566		free(p);
567		_kvm_err(kd, kd->program, "out of memory");
568	}
569	return (np);
570}
571
572#ifndef MAX
573#define MAX(a, b) ((a) > (b) ? (a) : (b))
574#endif
575
576/*
577 * Read in an argument vector from the user address space of process kp.
578 * addr if the user-space base address of narg null-terminated contiguous
579 * strings.  This is used to read in both the command arguments and
580 * environment strings.  Read at most maxcnt characters of strings.
581 */
582static char **
583kvm_argv(kd, kp, addr, narg, maxcnt)
584	kvm_t *kd;
585	struct kinfo_proc *kp;
586	u_long addr;
587	int narg;
588	int maxcnt;
589{
590	char *np, *cp, *ep, *ap;
591	u_long oaddr = -1;
592	int len, cc;
593	char **argv;
594
595	/*
596	 * Check that there aren't an unreasonable number of agruments,
597	 * and that the address is in user space.
598	 */
599	if (narg > 512 || addr < VM_MIN_ADDRESS || addr >= VM_MAXUSER_ADDRESS)
600		return (0);
601
602	/*
603	 * kd->argv : work space for fetching the strings from the target
604	 *            process's space, and is converted for returning to caller
605	 */
606	if (kd->argv == 0) {
607		/*
608		 * Try to avoid reallocs.
609		 */
610		kd->argc = MAX(narg + 1, 32);
611		kd->argv = (char **)_kvm_malloc(kd, kd->argc *
612						sizeof(*kd->argv));
613		if (kd->argv == 0)
614			return (0);
615	} else if (narg + 1 > kd->argc) {
616		kd->argc = MAX(2 * kd->argc, narg + 1);
617		kd->argv = (char **)_kvm_realloc(kd, kd->argv, kd->argc *
618						sizeof(*kd->argv));
619		if (kd->argv == 0)
620			return (0);
621	}
622	/*
623	 * kd->argspc : returned to user, this is where the kd->argv
624	 *              arrays are left pointing to the collected strings.
625	 */
626	if (kd->argspc == 0) {
627		kd->argspc = (char *)_kvm_malloc(kd, PAGE_SIZE);
628		if (kd->argspc == 0)
629			return (0);
630		kd->arglen = PAGE_SIZE;
631	}
632	/*
633	 * kd->argbuf : used to pull in pages from the target process.
634	 *              the strings are copied out of here.
635	 */
636	if (kd->argbuf == 0) {
637		kd->argbuf = (char *)_kvm_malloc(kd, PAGE_SIZE);
638		if (kd->argbuf == 0)
639			return (0);
640	}
641
642	/* Pull in the target process'es argv vector */
643	cc = sizeof(char *) * narg;
644	if (kvm_uread(kd, kp, addr, (char *)kd->argv, cc) != cc)
645		return (0);
646	/*
647	 * ap : saved start address of string we're working on in kd->argspc
648	 * np : pointer to next place to write in kd->argspc
649	 * len: length of data in kd->argspc
650	 * argv: pointer to the argv vector that we are hunting around the
651	 *       target process space for, and converting to addresses in
652	 *       our address space (kd->argspc).
653	 */
654	ap = np = kd->argspc;
655	argv = kd->argv;
656	len = 0;
657	/*
658	 * Loop over pages, filling in the argument vector.
659	 * Note that the argv strings could be pointing *anywhere* in
660	 * the user address space and are no longer contiguous.
661	 * Note that *argv is modified when we are going to fetch a string
662	 * that crosses a page boundary.  We copy the next part of the string
663	 * into to "np" and eventually convert the pointer.
664	 */
665	while (argv < kd->argv + narg && *argv != 0) {
666
667		/* get the address that the current argv string is on */
668		addr = (u_long)*argv & ~(PAGE_SIZE - 1);
669
670		/* is it the same page as the last one? */
671		if (addr != oaddr) {
672			if (kvm_uread(kd, kp, addr, kd->argbuf, PAGE_SIZE) !=
673			    PAGE_SIZE)
674				return (0);
675			oaddr = addr;
676		}
677
678		/* offset within the page... kd->argbuf */
679		addr = (u_long)*argv & (PAGE_SIZE - 1);
680
681		/* cp = start of string, cc = count of chars in this chunk */
682		cp = kd->argbuf + addr;
683		cc = PAGE_SIZE - addr;
684
685		/* dont get more than asked for by user process */
686		if (maxcnt > 0 && cc > maxcnt - len)
687			cc = maxcnt - len;
688
689		/* pointer to end of string if we found it in this page */
690		ep = memchr(cp, '\0', cc);
691		if (ep != 0)
692			cc = ep - cp + 1;
693		/*
694		 * at this point, cc is the count of the chars that we are
695		 * going to retrieve this time. we may or may not have found
696		 * the end of it.  (ep points to the null if the end is known)
697		 */
698
699		/* will we exceed the malloc/realloced buffer? */
700		if (len + cc > kd->arglen) {
701			int off;
702			char **pp;
703			char *op = kd->argspc;
704
705			kd->arglen *= 2;
706			kd->argspc = (char *)_kvm_realloc(kd, kd->argspc,
707							  kd->arglen);
708			if (kd->argspc == 0)
709				return (0);
710			/*
711			 * Adjust argv pointers in case realloc moved
712			 * the string space.
713			 */
714			off = kd->argspc - op;
715			for (pp = kd->argv; pp < argv; pp++)
716				*pp += off;
717			ap += off;
718			np += off;
719		}
720		/* np = where to put the next part of the string in kd->argspc*/
721		/* np is kinda redundant.. could use "kd->argspc + len" */
722		memcpy(np, cp, cc);
723		np += cc;	/* inc counters */
724		len += cc;
725
726		/*
727		 * if end of string found, set the *argv pointer to the
728		 * saved beginning of string, and advance. argv points to
729		 * somewhere in kd->argv..  This is initially relative
730		 * to the target process, but when we close it off, we set
731		 * it to point in our address space.
732		 */
733		if (ep != 0) {
734			*argv++ = ap;
735			ap = np;
736		} else {
737			/* update the address relative to the target process */
738			*argv += cc;
739		}
740
741		if (maxcnt > 0 && len >= maxcnt) {
742			/*
743			 * We're stopping prematurely.  Terminate the
744			 * current string.
745			 */
746			if (ep == 0) {
747				*np = '\0';
748				*argv++ = ap;
749			}
750			break;
751		}
752	}
753	/* Make sure argv is terminated. */
754	*argv = 0;
755	return (kd->argv);
756}
757
758static void
759ps_str_a(p, addr, n)
760	struct ps_strings *p;
761	u_long *addr;
762	int *n;
763{
764	*addr = (u_long)p->ps_argvstr;
765	*n = p->ps_nargvstr;
766}
767
768static void
769ps_str_e(p, addr, n)
770	struct ps_strings *p;
771	u_long *addr;
772	int *n;
773{
774	*addr = (u_long)p->ps_envstr;
775	*n = p->ps_nenvstr;
776}
777
778/*
779 * Determine if the proc indicated by p is still active.
780 * This test is not 100% foolproof in theory, but chances of
781 * being wrong are very low.
782 */
783static int
784proc_verify(curkp)
785	struct kinfo_proc *curkp;
786{
787	struct kinfo_proc newkp;
788	int mib[4];
789	size_t len;
790
791	mib[0] = CTL_KERN;
792	mib[1] = KERN_PROC;
793	mib[2] = KERN_PROC_PID;
794	mib[3] = curkp->ki_pid;
795	len = sizeof(newkp);
796	if (sysctl(mib, 4, &newkp, &len, NULL, 0) == -1)
797		return (0);
798	return (curkp->ki_pid == newkp.ki_pid &&
799	    (newkp.ki_stat != SZOMB || curkp->ki_stat == SZOMB));
800}
801
802static char **
803kvm_doargv(kd, kp, nchr, info)
804	kvm_t *kd;
805	struct kinfo_proc *kp;
806	int nchr;
807	void (*info)(struct ps_strings *, u_long *, int *);
808{
809	char **ap;
810	u_long addr;
811	int cnt;
812	static struct ps_strings arginfo;
813	static u_long ps_strings;
814	size_t len;
815
816	if (ps_strings == NULL) {
817		len = sizeof(ps_strings);
818		if (sysctlbyname("kern.ps_strings", &ps_strings, &len, NULL,
819		    0) == -1)
820			ps_strings = PS_STRINGS;
821	}
822
823	/*
824	 * Pointers are stored at the top of the user stack.
825	 */
826	if (kp->ki_stat == SZOMB ||
827	    kvm_uread(kd, kp, ps_strings, (char *)&arginfo,
828		      sizeof(arginfo)) != sizeof(arginfo))
829		return (0);
830
831	(*info)(&arginfo, &addr, &cnt);
832	if (cnt == 0)
833		return (0);
834	ap = kvm_argv(kd, kp, addr, cnt, nchr);
835	/*
836	 * For live kernels, make sure this process didn't go away.
837	 */
838	if (ap != 0 && ISALIVE(kd) && !proc_verify(kp))
839		ap = 0;
840	return (ap);
841}
842
843/*
844 * Get the command args.  This code is now machine independent.
845 */
846char **
847kvm_getargv(kd, kp, nchr)
848	kvm_t *kd;
849	const struct kinfo_proc *kp;
850	int nchr;
851{
852	int oid[4];
853	int i;
854	size_t bufsz;
855	static unsigned long buflen;
856	static char *buf, *p;
857	static char **bufp;
858	static int argc;
859
860	if (!ISALIVE(kd)) {
861		_kvm_err(kd, kd->program,
862		    "cannot read user space from dead kernel");
863		return (0);
864	}
865
866	if (!buflen) {
867		bufsz = sizeof(buflen);
868		i = sysctlbyname("kern.ps_arg_cache_limit",
869		    &buflen, &bufsz, NULL, 0);
870		if (i == -1) {
871			buflen = 0;
872		} else {
873			buf = malloc(buflen);
874			if (buf == NULL)
875				buflen = 0;
876			argc = 32;
877			bufp = malloc(sizeof(char *) * argc);
878		}
879	}
880	if (buf != NULL) {
881		oid[0] = CTL_KERN;
882		oid[1] = KERN_PROC;
883		oid[2] = KERN_PROC_ARGS;
884		oid[3] = kp->ki_pid;
885		bufsz = buflen;
886		i = sysctl(oid, 4, buf, &bufsz, 0, 0);
887		if (i == 0 && bufsz > 0) {
888			i = 0;
889			p = buf;
890			do {
891				bufp[i++] = p;
892				p += strlen(p) + 1;
893				if (i >= argc) {
894					argc += argc;
895					bufp = realloc(bufp,
896					    sizeof(char *) * argc);
897				}
898			} while (p < buf + bufsz);
899			bufp[i++] = 0;
900			return (bufp);
901		}
902	}
903	if (kp->ki_flag & P_SYSTEM)
904		return (NULL);
905	return (kvm_doargv(kd, kp, nchr, ps_str_a));
906}
907
908char **
909kvm_getenvv(kd, kp, nchr)
910	kvm_t *kd;
911	const struct kinfo_proc *kp;
912	int nchr;
913{
914	return (kvm_doargv(kd, kp, nchr, ps_str_e));
915}
916
917/*
918 * Read from user space.  The user context is given by p.
919 */
920ssize_t
921kvm_uread(kd, kp, uva, buf, len)
922	kvm_t *kd;
923	struct kinfo_proc *kp;
924	u_long uva;
925	char *buf;
926	size_t len;
927{
928	char *cp;
929	char procfile[MAXPATHLEN];
930	ssize_t amount;
931	int fd;
932
933	if (!ISALIVE(kd)) {
934		_kvm_err(kd, kd->program,
935		    "cannot read user space from dead kernel");
936		return (0);
937	}
938
939	sprintf(procfile, "/proc/%d/mem", kp->ki_pid);
940	fd = open(procfile, O_RDONLY, 0);
941	if (fd < 0) {
942		_kvm_err(kd, kd->program, "cannot open %s", procfile);
943		close(fd);
944		return (0);
945	}
946
947	cp = buf;
948	while (len > 0) {
949		errno = 0;
950		if (lseek(fd, (off_t)uva, 0) == -1 && errno != 0) {
951			_kvm_err(kd, kd->program, "invalid address (%x) in %s",
952			    uva, procfile);
953			break;
954		}
955		amount = read(fd, cp, len);
956		if (amount < 0) {
957			_kvm_syserr(kd, kd->program, "error reading %s",
958			    procfile);
959			break;
960		}
961		if (amount == 0) {
962			_kvm_err(kd, kd->program, "EOF reading %s", procfile);
963			break;
964		}
965		cp += amount;
966		uva += amount;
967		len -= amount;
968	}
969
970	close(fd);
971	return ((ssize_t)(cp - buf));
972}
973