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