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