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