kvm_proc.c revision 69896
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 69896 2000-12-12 07:25:57Z mckusick $
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/user.h>
53#include <sys/proc.h>
54#include <sys/exec.h>
55#include <sys/stat.h>
56#include <sys/ioctl.h>
57#define _KERNEL
58#include <sys/select.h>
59#undef _KERNEL
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 pcred pcred;
119	struct pstats pstats;
120	struct ucred ucred;
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 = proc.p_list.le_next) {
127		if (KREAD(kd, (u_long)p, &proc)) {
128			_kvm_err(kd, kd->program, "can't read proc at %x", p);
129			return (-1);
130		}
131		if (KREAD(kd, (u_long)proc.p_cred, &pcred) == 0) {
132			kp->ki_ruid = pcred.p_ruid;
133			kp->ki_svuid = pcred.p_svuid;
134			kp->ki_rgid = pcred.p_rgid;
135			kp->ki_svgid = pcred.p_svgid;
136			(void)(KREAD(kd, (u_long)pcred.pc_ucred, &ucred));
137			kp->ki_ngroups = ucred.cr_ngroups;
138			bcopy(ucred.cr_groups, kp->ki_groups,
139			    NGROUPS * sizeof(gid_t));
140			kp->ki_uid = ucred.cr_uid;
141		}
142
143		switch(what) {
144
145		case KERN_PROC_PID:
146			if (proc.p_pid != (pid_t)arg)
147				continue;
148			break;
149
150		case KERN_PROC_UID:
151			if (kp->ki_uid != (uid_t)arg)
152				continue;
153			break;
154
155		case KERN_PROC_RUID:
156			if (kp->ki_ruid != (uid_t)arg)
157				continue;
158			break;
159		}
160		/*
161		 * We're going to add another proc to the set.  If this
162		 * will overflow the buffer, assume the reason is because
163		 * nprocs (or the proc list) is corrupt and declare an error.
164		 */
165		if (cnt >= maxcnt) {
166			_kvm_err(kd, kd->program, "nprocs corrupt");
167			return (-1);
168		}
169		/*
170		 * gather kinfo_proc
171		 */
172		kp->ki_paddr = p;
173		kp->ki_addr = proc.p_addr;
174		kp->ki_args = proc.p_args;
175		kp->ki_tracep = proc.p_tracep;
176		kp->ki_textvp = proc.p_textvp;
177		kp->ki_fd = proc.p_fd;
178		kp->ki_vmspace = proc.p_vmspace;
179		if (proc.p_procsig != NULL) {
180			if (KREAD(kd, (u_long)proc.p_procsig, &procsig)) {
181				_kvm_err(kd, kd->program,
182				    "can't read procsig at %x", proc.p_procsig);
183				return (-1);
184			}
185			kp->ki_sigignore = procsig.ps_sigignore;
186			kp->ki_sigcatch = procsig.ps_sigcatch;
187		}
188		if ((proc.p_flag & P_INMEM) && proc.p_stats != NULL) {
189			if (KREAD(kd, (u_long)proc.p_stats, &pstats)) {
190				_kvm_err(kd, kd->program,
191				    "can't read stats at %x", proc.p_stats);
192				return (-1);
193			}
194			kp->ki_start = pstats.p_start;
195			kp->ki_rusage = pstats.p_ru;
196			kp->ki_childtime.tv_sec = pstats.p_cru.ru_utime.tv_sec +
197			    pstats.p_cru.ru_stime.tv_sec;
198			kp->ki_childtime.tv_usec =
199			    pstats.p_cru.ru_utime.tv_usec +
200			    pstats.p_cru.ru_stime.tv_usec;
201		}
202		if (KREAD(kd, (u_long)proc.p_pgrp, &pgrp)) {
203			_kvm_err(kd, kd->program, "can't read pgrp at %x",
204				 proc.p_pgrp);
205			return (-1);
206		}
207		if (proc.p_oppid)
208			kp->ki_ppid = proc.p_oppid;
209		else if (proc.p_pptr) {
210			if (KREAD(kd, (u_long)proc.p_pptr, &pproc)) {
211				_kvm_err(kd, kd->program,
212				    "can't read pproc at %x", proc.p_pptr);
213				return (-1);
214			}
215			kp->ki_ppid = pproc.p_pid;
216		} else
217			kp->ki_ppid = 0;
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
258			kp->ki_tdev = NODEV;
259		if (proc.p_wmesg)
260			(void)kvm_read(kd, (u_long)proc.p_wmesg,
261			    kp->ki_wmesg, WMESGLEN);
262
263#ifdef sparc
264		(void)kvm_read(kd, (u_long)&proc.p_vmspace->vm_rssize,
265		    (char *)&kp->ki_rssize,
266		    sizeof(kp->ki_rssize));
267		(void)kvm_read(kd, (u_long)&proc.p_vmspace->vm_tsize,
268		    (char *)&kp->ki_tsize,
269		    3 * sizeof(kp->ki_rssize));	/* XXX */
270#else
271		(void)kvm_read(kd, (u_long)proc.p_vmspace,
272		    (char *)&vmspace, sizeof(vmspace));
273		kp->ki_size = vmspace.vm_map.size;
274		kp->ki_rssize = vmspace.vm_swrss; /* XXX */
275		kp->ki_swrss = vmspace.vm_swrss;
276		kp->ki_tsize = vmspace.vm_tsize;
277		kp->ki_dsize = vmspace.vm_dsize;
278		kp->ki_ssize = vmspace.vm_ssize;
279#endif
280
281		switch (what) {
282
283		case KERN_PROC_PGRP:
284			if (kp->ki_pgid != (pid_t)arg)
285				continue;
286			break;
287
288		case KERN_PROC_TTY:
289			if ((proc.p_flag & P_CONTROLT) == 0 ||
290			     kp->ki_tdev != (dev_t)arg)
291				continue;
292			break;
293		}
294		if (proc.p_comm[0] != 0) {
295			strncpy(kp->ki_comm, proc.p_comm, MAXCOMLEN);
296			kp->ki_comm[MAXCOMLEN] = 0;
297		}
298		if (proc.p_blocked != 0) {
299			kp->ki_kiflag |= KI_MTXBLOCK;
300			if (proc.p_mtxname)
301				(void)kvm_read(kd, (u_long)proc.p_mtxname,
302				    kp->ki_mtxname, MTXNAMELEN);
303			kp->ki_mtxname[MTXNAMELEN] = 0;
304		}
305		kp->ki_rtprio = proc.p_rtprio;
306		kp->ki_runtime = proc.p_runtime;
307		kp->ki_pid = proc.p_pid;
308		kp->ki_siglist = proc.p_siglist;
309		kp->ki_sigmask = proc.p_sigmask;
310		kp->ki_xstat = proc.p_xstat;
311		kp->ki_acflag = proc.p_acflag;
312		kp->ki_pctcpu = proc.p_pctcpu;
313		kp->ki_estcpu = proc.p_estcpu;
314		kp->ki_slptime = proc.p_slptime;
315		kp->ki_swtime = proc.p_swtime;
316		kp->ki_flag = proc.p_flag;
317		kp->ki_wchan = proc.p_wchan;
318		kp->ki_traceflag = proc.p_traceflag;
319		kp->ki_priority = proc.p_priority;
320		kp->ki_usrpri = proc.p_usrpri;
321		kp->ki_nativepri = proc.p_nativepri;
322		kp->ki_stat = proc.p_stat;
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 (kd->procbase->ki_structsize != sizeof(struct kinfo_proc)) {
412			_kvm_err(kd, kd->program,
413			    "kinfo_proc size mismatch (expected %d, got %d)",
414			    sizeof(struct kinfo_proc),
415			    kd->procbase->ki_structsize);
416			return (0);
417		}
418		nprocs = size / kd->procbase->ki_structsize;
419	} else {
420		struct nlist nl[4], *p;
421
422		nl[0].n_name = "_nprocs";
423		nl[1].n_name = "_allproc";
424		nl[2].n_name = "_zombproc";
425		nl[3].n_name = 0;
426
427		if (kvm_nlist(kd, nl) != 0) {
428			for (p = nl; p->n_type != 0; ++p)
429				;
430			_kvm_err(kd, kd->program,
431				 "%s: no such symbol", p->n_name);
432			return (0);
433		}
434		if (KREAD(kd, nl[0].n_value, &nprocs)) {
435			_kvm_err(kd, kd->program, "can't read nprocs");
436			return (0);
437		}
438		size = nprocs * sizeof(struct kinfo_proc);
439		kd->procbase = (struct kinfo_proc *)_kvm_malloc(kd, size);
440		if (kd->procbase == 0)
441			return (0);
442
443		nprocs = kvm_deadprocs(kd, op, arg, nl[1].n_value,
444				      nl[2].n_value, nprocs);
445#ifdef notdef
446		size = nprocs * sizeof(struct kinfo_proc);
447		(void)realloc(kd->procbase, size);
448#endif
449	}
450	*cnt = nprocs;
451	return (kd->procbase);
452}
453
454void
455_kvm_freeprocs(kd)
456	kvm_t *kd;
457{
458	if (kd->procbase) {
459		free(kd->procbase);
460		kd->procbase = 0;
461	}
462}
463
464void *
465_kvm_realloc(kd, p, n)
466	kvm_t *kd;
467	void *p;
468	size_t n;
469{
470	void *np = (void *)realloc(p, n);
471
472	if (np == 0) {
473		free(p);
474		_kvm_err(kd, kd->program, "out of memory");
475	}
476	return (np);
477}
478
479#ifndef MAX
480#define MAX(a, b) ((a) > (b) ? (a) : (b))
481#endif
482
483/*
484 * Read in an argument vector from the user address space of process kp.
485 * addr if the user-space base address of narg null-terminated contiguous
486 * strings.  This is used to read in both the command arguments and
487 * environment strings.  Read at most maxcnt characters of strings.
488 */
489static char **
490kvm_argv(kd, kp, addr, narg, maxcnt)
491	kvm_t *kd;
492	struct kinfo_proc *kp;
493	register u_long addr;
494	register int narg;
495	register int maxcnt;
496{
497	register char *np, *cp, *ep, *ap;
498	register u_long oaddr = -1;
499	register int len, cc;
500	register char **argv;
501
502	/*
503	 * Check that there aren't an unreasonable number of agruments,
504	 * and that the address is in user space.
505	 */
506	if (narg > 512 || addr < VM_MIN_ADDRESS || addr >= VM_MAXUSER_ADDRESS)
507		return (0);
508
509	/*
510	 * kd->argv : work space for fetching the strings from the target
511	 *            process's space, and is converted for returning to caller
512	 */
513	if (kd->argv == 0) {
514		/*
515		 * Try to avoid reallocs.
516		 */
517		kd->argc = MAX(narg + 1, 32);
518		kd->argv = (char **)_kvm_malloc(kd, kd->argc *
519						sizeof(*kd->argv));
520		if (kd->argv == 0)
521			return (0);
522	} else if (narg + 1 > kd->argc) {
523		kd->argc = MAX(2 * kd->argc, narg + 1);
524		kd->argv = (char **)_kvm_realloc(kd, kd->argv, kd->argc *
525						sizeof(*kd->argv));
526		if (kd->argv == 0)
527			return (0);
528	}
529	/*
530	 * kd->argspc : returned to user, this is where the kd->argv
531	 *              arrays are left pointing to the collected strings.
532	 */
533	if (kd->argspc == 0) {
534		kd->argspc = (char *)_kvm_malloc(kd, PAGE_SIZE);
535		if (kd->argspc == 0)
536			return (0);
537		kd->arglen = PAGE_SIZE;
538	}
539	/*
540	 * kd->argbuf : used to pull in pages from the target process.
541	 *              the strings are copied out of here.
542	 */
543	if (kd->argbuf == 0) {
544		kd->argbuf = (char *)_kvm_malloc(kd, PAGE_SIZE);
545		if (kd->argbuf == 0)
546			return (0);
547	}
548
549	/* Pull in the target process'es argv vector */
550	cc = sizeof(char *) * narg;
551	if (kvm_uread(kd, kp, addr, (char *)kd->argv, cc) != cc)
552		return (0);
553	/*
554	 * ap : saved start address of string we're working on in kd->argspc
555	 * np : pointer to next place to write in kd->argspc
556	 * len: length of data in kd->argspc
557	 * argv: pointer to the argv vector that we are hunting around the
558	 *       target process space for, and converting to addresses in
559	 *       our address space (kd->argspc).
560	 */
561	ap = np = kd->argspc;
562	argv = kd->argv;
563	len = 0;
564	/*
565	 * Loop over pages, filling in the argument vector.
566	 * Note that the argv strings could be pointing *anywhere* in
567	 * the user address space and are no longer contiguous.
568	 * Note that *argv is modified when we are going to fetch a string
569	 * that crosses a page boundary.  We copy the next part of the string
570	 * into to "np" and eventually convert the pointer.
571	 */
572	while (argv < kd->argv + narg && *argv != 0) {
573
574		/* get the address that the current argv string is on */
575		addr = (u_long)*argv & ~(PAGE_SIZE - 1);
576
577		/* is it the same page as the last one? */
578		if (addr != oaddr) {
579			if (kvm_uread(kd, kp, addr, kd->argbuf, PAGE_SIZE) !=
580			    PAGE_SIZE)
581				return (0);
582			oaddr = addr;
583		}
584
585		/* offset within the page... kd->argbuf */
586		addr = (u_long)*argv & (PAGE_SIZE - 1);
587
588		/* cp = start of string, cc = count of chars in this chunk */
589		cp = kd->argbuf + addr;
590		cc = PAGE_SIZE - addr;
591
592		/* dont get more than asked for by user process */
593		if (maxcnt > 0 && cc > maxcnt - len)
594			cc = maxcnt - len;
595
596		/* pointer to end of string if we found it in this page */
597		ep = memchr(cp, '\0', cc);
598		if (ep != 0)
599			cc = ep - cp + 1;
600		/*
601		 * at this point, cc is the count of the chars that we are
602		 * going to retrieve this time. we may or may not have found
603		 * the end of it.  (ep points to the null if the end is known)
604		 */
605
606		/* will we exceed the malloc/realloced buffer? */
607		if (len + cc > kd->arglen) {
608			register int off;
609			register char **pp;
610			register char *op = kd->argspc;
611
612			kd->arglen *= 2;
613			kd->argspc = (char *)_kvm_realloc(kd, kd->argspc,
614							  kd->arglen);
615			if (kd->argspc == 0)
616				return (0);
617			/*
618			 * Adjust argv pointers in case realloc moved
619			 * the string space.
620			 */
621			off = kd->argspc - op;
622			for (pp = kd->argv; pp < argv; pp++)
623				*pp += off;
624			ap += off;
625			np += off;
626		}
627		/* np = where to put the next part of the string in kd->argspc*/
628		/* np is kinda redundant.. could use "kd->argspc + len" */
629		memcpy(np, cp, cc);
630		np += cc;	/* inc counters */
631		len += cc;
632
633		/*
634		 * if end of string found, set the *argv pointer to the
635		 * saved beginning of string, and advance. argv points to
636		 * somewhere in kd->argv..  This is initially relative
637		 * to the target process, but when we close it off, we set
638		 * it to point in our address space.
639		 */
640		if (ep != 0) {
641			*argv++ = ap;
642			ap = np;
643		} else {
644			/* update the address relative to the target process */
645			*argv += cc;
646		}
647
648		if (maxcnt > 0 && len >= maxcnt) {
649			/*
650			 * We're stopping prematurely.  Terminate the
651			 * current string.
652			 */
653			if (ep == 0) {
654				*np = '\0';
655				*argv++ = ap;
656			}
657			break;
658		}
659	}
660	/* Make sure argv is terminated. */
661	*argv = 0;
662	return (kd->argv);
663}
664
665static void
666ps_str_a(p, addr, n)
667	struct ps_strings *p;
668	u_long *addr;
669	int *n;
670{
671	*addr = (u_long)p->ps_argvstr;
672	*n = p->ps_nargvstr;
673}
674
675static void
676ps_str_e(p, addr, n)
677	struct ps_strings *p;
678	u_long *addr;
679	int *n;
680{
681	*addr = (u_long)p->ps_envstr;
682	*n = p->ps_nenvstr;
683}
684
685/*
686 * Determine if the proc indicated by p is still active.
687 * This test is not 100% foolproof in theory, but chances of
688 * being wrong are very low.
689 */
690static int
691proc_verify(curkp)
692	struct kinfo_proc *curkp;
693{
694	struct kinfo_proc newkp;
695	int mib[4];
696	size_t len;
697
698	mib[0] = CTL_KERN;
699	mib[1] = KERN_PROC;
700	mib[2] = KERN_PROC_PID;
701	mib[3] = curkp->ki_pid;
702	len = sizeof(newkp);
703	if (sysctl(mib, 4, &newkp, &len, NULL, 0) == -1)
704		return (0);
705	return (curkp->ki_pid == newkp.ki_pid &&
706	    (newkp.ki_stat != SZOMB || curkp->ki_stat == SZOMB));
707}
708
709static char **
710kvm_doargv(kd, kp, nchr, info)
711	kvm_t *kd;
712	struct kinfo_proc *kp;
713	int nchr;
714	void (*info)(struct ps_strings *, u_long *, int *);
715{
716	char **ap;
717	u_long addr;
718	int cnt;
719	static struct ps_strings arginfo;
720	static u_long ps_strings;
721	size_t len;
722
723	if (ps_strings == NULL) {
724		len = sizeof(ps_strings);
725		if (sysctlbyname("kern.ps_strings", &ps_strings, &len, NULL,
726		    0) == -1)
727			ps_strings = PS_STRINGS;
728	}
729
730	/*
731	 * Pointers are stored at the top of the user stack.
732	 */
733	if (kp->ki_stat == SZOMB ||
734	    kvm_uread(kd, kp, ps_strings, (char *)&arginfo,
735		      sizeof(arginfo)) != sizeof(arginfo))
736		return (0);
737
738	(*info)(&arginfo, &addr, &cnt);
739	if (cnt == 0)
740		return (0);
741	ap = kvm_argv(kd, kp, addr, cnt, nchr);
742	/*
743	 * For live kernels, make sure this process didn't go away.
744	 */
745	if (ap != 0 && ISALIVE(kd) && !proc_verify(kp))
746		ap = 0;
747	return (ap);
748}
749
750/*
751 * Get the command args.  This code is now machine independent.
752 */
753char **
754kvm_getargv(kd, kp, nchr)
755	kvm_t *kd;
756	const struct kinfo_proc *kp;
757	int nchr;
758{
759	int oid[4];
760	int i;
761	size_t bufsz;
762	static int buflen;
763	static char *buf, *p;
764	static char **bufp;
765	static int argc;
766
767	if (!ISALIVE(kd)) {
768		_kvm_err(kd, kd->program,
769		    "cannot read user space from dead kernel");
770		return (0);
771	}
772
773	if (!buflen) {
774		bufsz = sizeof(buflen);
775		i = sysctlbyname("kern.ps_arg_cache_limit",
776		    &buflen, &bufsz, NULL, 0);
777		if (i == -1) {
778			buflen = 0;
779		} else {
780			buf = malloc(buflen);
781			if (buf == NULL)
782				buflen = 0;
783			argc = 32;
784			bufp = malloc(sizeof(char *) * argc);
785		}
786	}
787	if (buf != NULL) {
788		oid[0] = CTL_KERN;
789		oid[1] = KERN_PROC;
790		oid[2] = KERN_PROC_ARGS;
791		oid[3] = kp->ki_pid;
792		bufsz = buflen;
793		i = sysctl(oid, 4, buf, &bufsz, 0, 0);
794		if (i == 0 && bufsz > 0) {
795			i = 0;
796			p = buf;
797			do {
798				bufp[i++] = p;
799				p += strlen(p) + 1;
800				if (i >= argc) {
801					argc += argc;
802					bufp = realloc(bufp,
803					    sizeof(char *) * argc);
804				}
805			} while (p < buf + bufsz);
806			bufp[i++] = 0;
807			return (bufp);
808		}
809	}
810	if (kp->ki_flag & P_SYSTEM)
811		return (NULL);
812	return (kvm_doargv(kd, kp, nchr, ps_str_a));
813}
814
815char **
816kvm_getenvv(kd, kp, nchr)
817	kvm_t *kd;
818	const struct kinfo_proc *kp;
819	int nchr;
820{
821	return (kvm_doargv(kd, kp, nchr, ps_str_e));
822}
823
824/*
825 * Read from user space.  The user context is given by p.
826 */
827ssize_t
828kvm_uread(kd, kp, uva, buf, len)
829	kvm_t *kd;
830	struct kinfo_proc *kp;
831	register u_long uva;
832	register char *buf;
833	register size_t len;
834{
835	register char *cp;
836	char procfile[MAXPATHLEN];
837	ssize_t amount;
838	int fd;
839
840	if (!ISALIVE(kd)) {
841		_kvm_err(kd, kd->program,
842		    "cannot read user space from dead kernel");
843		return (0);
844	}
845
846	sprintf(procfile, "/proc/%d/mem", kp->ki_pid);
847	fd = open(procfile, O_RDONLY, 0);
848	if (fd < 0) {
849		_kvm_err(kd, kd->program, "cannot open %s", procfile);
850		close(fd);
851		return (0);
852	}
853
854	cp = buf;
855	while (len > 0) {
856		errno = 0;
857		if (lseek(fd, (off_t)uva, 0) == -1 && errno != 0) {
858			_kvm_err(kd, kd->program, "invalid address (%x) in %s",
859			    uva, procfile);
860			break;
861		}
862		amount = read(fd, cp, len);
863		if (amount < 0) {
864			_kvm_syserr(kd, kd->program, "error reading %s",
865			    procfile);
866			break;
867		}
868		if (amount == 0) {
869			_kvm_err(kd, kd->program, "EOF reading %s", procfile);
870			break;
871		}
872		cp += amount;
873		uva += amount;
874		len -= amount;
875	}
876
877	close(fd);
878	return ((ssize_t)(cp - buf));
879}
880