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