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