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