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