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