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