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