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