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