xref: /freebsd/lib/libkvm/kvm_proc.c (revision 0c43d89a0d8e976ca494d4837f4c1f3734d2c300)
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 defined(LIBC_SCCS) && !defined(lint)
39 static char sccsid[] = "@(#)kvm_proc.c	8.3 (Berkeley) 9/23/93";
40 #endif /* LIBC_SCCS and not lint */
41 
42 /*
43  * Proc traversal interface for kvm.  ps and w are (probably) the exclusive
44  * users of this code, so we've factored it out into a separate module.
45  * Thus, we keep this grunge out of the other kvm applications (i.e.,
46  * most other applications are interested only in open/close/read/nlist).
47  */
48 
49 #include <sys/param.h>
50 #include <sys/user.h>
51 #include <sys/proc.h>
52 #include <sys/exec.h>
53 #include <sys/stat.h>
54 #include <sys/ioctl.h>
55 #include <sys/tty.h>
56 #include <sys/file.h>
57 #include <unistd.h>
58 #include <nlist.h>
59 #include <kvm.h>
60 
61 #include <vm/vm.h>
62 #include <vm/vm_param.h>
63 #include <vm/swap_pager.h>
64 
65 #include <sys/sysctl.h>
66 
67 #include <limits.h>
68 #include <db.h>
69 #include <paths.h>
70 
71 #include "kvm_private.h"
72 
73 static char *
74 kvm_readswap(kd, p, va, cnt)
75 	kvm_t *kd;
76 	const struct proc *p;
77 	u_long va;
78 	u_long *cnt;
79 {
80 #ifdef __FreeBSD__
81 	/* XXX Stubbed out, our vm system is differnet */
82 	_kvm_err(kd, kd->program, "kvm_readswap not implemented");
83 	return(0);
84 #endif	/* __FreeBSD__ */
85 }
86 
87 #define KREAD(kd, addr, obj) \
88 	(kvm_read(kd, addr, (char *)(obj), sizeof(*obj)) != sizeof(*obj))
89 
90 /*
91  * Read proc's from memory file into buffer bp, which has space to hold
92  * at most maxcnt procs.
93  */
94 static int
95 kvm_proclist(kd, what, arg, p, bp, maxcnt)
96 	kvm_t *kd;
97 	int what, arg;
98 	struct proc *p;
99 	struct kinfo_proc *bp;
100 	int maxcnt;
101 {
102 	register int cnt = 0;
103 	struct eproc eproc;
104 	struct pgrp pgrp;
105 	struct session sess;
106 	struct tty tty;
107 	struct proc proc;
108 
109 	for (; cnt < maxcnt && p != NULL; p = proc.p_next) {
110 		if (KREAD(kd, (u_long)p, &proc)) {
111 			_kvm_err(kd, kd->program, "can't read proc at %x", p);
112 			return (-1);
113 		}
114 		if (KREAD(kd, (u_long)proc.p_cred, &eproc.e_pcred) == 0)
115 			KREAD(kd, (u_long)eproc.e_pcred.pc_ucred,
116 			      &eproc.e_ucred);
117 
118 		switch(what) {
119 
120 		case KERN_PROC_PID:
121 			if (proc.p_pid != (pid_t)arg)
122 				continue;
123 			break;
124 
125 		case KERN_PROC_UID:
126 			if (eproc.e_ucred.cr_uid != (uid_t)arg)
127 				continue;
128 			break;
129 
130 		case KERN_PROC_RUID:
131 			if (eproc.e_pcred.p_ruid != (uid_t)arg)
132 				continue;
133 			break;
134 		}
135 		/*
136 		 * We're going to add another proc to the set.  If this
137 		 * will overflow the buffer, assume the reason is because
138 		 * nprocs (or the proc list) is corrupt and declare an error.
139 		 */
140 		if (cnt >= maxcnt) {
141 			_kvm_err(kd, kd->program, "nprocs corrupt");
142 			return (-1);
143 		}
144 		/*
145 		 * gather eproc
146 		 */
147 		eproc.e_paddr = p;
148 		if (KREAD(kd, (u_long)proc.p_pgrp, &pgrp)) {
149 			_kvm_err(kd, kd->program, "can't read pgrp at %x",
150 				 proc.p_pgrp);
151 			return (-1);
152 		}
153 		eproc.e_sess = pgrp.pg_session;
154 		eproc.e_pgid = pgrp.pg_id;
155 		eproc.e_jobc = pgrp.pg_jobc;
156 		if (KREAD(kd, (u_long)pgrp.pg_session, &sess)) {
157 			_kvm_err(kd, kd->program, "can't read session at %x",
158 				pgrp.pg_session);
159 			return (-1);
160 		}
161 		if ((proc.p_flag & P_CONTROLT) && sess.s_ttyp != NULL) {
162 			if (KREAD(kd, (u_long)sess.s_ttyp, &tty)) {
163 				_kvm_err(kd, kd->program,
164 					 "can't read tty at %x", sess.s_ttyp);
165 				return (-1);
166 			}
167 			eproc.e_tdev = tty.t_dev;
168 			eproc.e_tsess = tty.t_session;
169 			if (tty.t_pgrp != NULL) {
170 				if (KREAD(kd, (u_long)tty.t_pgrp, &pgrp)) {
171 					_kvm_err(kd, kd->program,
172 						 "can't read tpgrp at &x",
173 						tty.t_pgrp);
174 					return (-1);
175 				}
176 				eproc.e_tpgid = pgrp.pg_id;
177 			} else
178 				eproc.e_tpgid = -1;
179 		} else
180 			eproc.e_tdev = NODEV;
181 		eproc.e_flag = sess.s_ttyvp ? EPROC_CTTY : 0;
182 		if (sess.s_leader == p)
183 			eproc.e_flag |= EPROC_SLEADER;
184 		if (proc.p_wmesg)
185 			(void)kvm_read(kd, (u_long)proc.p_wmesg,
186 			    eproc.e_wmesg, WMESGLEN);
187 
188 #ifdef sparc
189 		(void)kvm_read(kd, (u_long)&proc.p_vmspace->vm_rssize,
190 		    (char *)&eproc.e_vm.vm_rssize,
191 		    sizeof(eproc.e_vm.vm_rssize));
192 		(void)kvm_read(kd, (u_long)&proc.p_vmspace->vm_tsize,
193 		    (char *)&eproc.e_vm.vm_tsize,
194 		    3 * sizeof(eproc.e_vm.vm_rssize));	/* XXX */
195 #else
196 		(void)kvm_read(kd, (u_long)proc.p_vmspace,
197 		    (char *)&eproc.e_vm, sizeof(eproc.e_vm));
198 #endif
199 		eproc.e_xsize = eproc.e_xrssize = 0;
200 		eproc.e_xccount = eproc.e_xswrss = 0;
201 
202 		switch (what) {
203 
204 		case KERN_PROC_PGRP:
205 			if (eproc.e_pgid != (pid_t)arg)
206 				continue;
207 			break;
208 
209 		case KERN_PROC_TTY:
210 			if ((proc.p_flag & P_CONTROLT) == 0 ||
211 			     eproc.e_tdev != (dev_t)arg)
212 				continue;
213 			break;
214 		}
215 		bcopy(&proc, &bp->kp_proc, sizeof(proc));
216 		bcopy(&eproc, &bp->kp_eproc, sizeof(eproc));
217 		++bp;
218 		++cnt;
219 	}
220 	return (cnt);
221 }
222 
223 /*
224  * Build proc info array by reading in proc list from a crash dump.
225  * Return number of procs read.  maxcnt is the max we will read.
226  */
227 static int
228 kvm_deadprocs(kd, what, arg, a_allproc, a_zombproc, maxcnt)
229 	kvm_t *kd;
230 	int what, arg;
231 	u_long a_allproc;
232 	u_long a_zombproc;
233 	int maxcnt;
234 {
235 	register struct kinfo_proc *bp = kd->procbase;
236 	register int acnt, zcnt;
237 	struct proc *p;
238 
239 	if (KREAD(kd, a_allproc, &p)) {
240 		_kvm_err(kd, kd->program, "cannot read allproc");
241 		return (-1);
242 	}
243 	acnt = kvm_proclist(kd, what, arg, p, bp, maxcnt);
244 	if (acnt < 0)
245 		return (acnt);
246 
247 	if (KREAD(kd, a_zombproc, &p)) {
248 		_kvm_err(kd, kd->program, "cannot read zombproc");
249 		return (-1);
250 	}
251 	zcnt = kvm_proclist(kd, what, arg, p, bp + acnt, maxcnt - acnt);
252 	if (zcnt < 0)
253 		zcnt = 0;
254 
255 	return (acnt + zcnt);
256 }
257 
258 struct kinfo_proc *
259 kvm_getprocs(kd, op, arg, cnt)
260 	kvm_t *kd;
261 	int op, arg;
262 	int *cnt;
263 {
264 	int mib[4], size, st, nprocs;
265 
266 	if (kd->procbase != 0) {
267 		free((void *)kd->procbase);
268 		/*
269 		 * Clear this pointer in case this call fails.  Otherwise,
270 		 * kvm_close() will free it again.
271 		 */
272 		kd->procbase = 0;
273 	}
274 	if (ISALIVE(kd)) {
275 		size = 0;
276 		mib[0] = CTL_KERN;
277 		mib[1] = KERN_PROC;
278 		mib[2] = op;
279 		mib[3] = arg;
280 		st = sysctl(mib, 4, NULL, &size, NULL, 0);
281 		if (st == -1) {
282 			_kvm_syserr(kd, kd->program, "kvm_getprocs");
283 			return (0);
284 		}
285 		kd->procbase = (struct kinfo_proc *)_kvm_malloc(kd, size);
286 		if (kd->procbase == 0)
287 			return (0);
288 		st = sysctl(mib, 4, kd->procbase, &size, NULL, 0);
289 		if (st == -1) {
290 			_kvm_syserr(kd, kd->program, "kvm_getprocs");
291 			return (0);
292 		}
293 		if (size % sizeof(struct kinfo_proc) != 0) {
294 			_kvm_err(kd, kd->program,
295 				"proc size mismatch (%d total, %d chunks)",
296 				size, sizeof(struct kinfo_proc));
297 			return (0);
298 		}
299 		nprocs = size / sizeof(struct kinfo_proc);
300 	} else {
301 		struct nlist nl[4], *p;
302 
303 		nl[0].n_name = "_nprocs";
304 		nl[1].n_name = "_allproc";
305 		nl[2].n_name = "_zombproc";
306 		nl[3].n_name = 0;
307 
308 		if (kvm_nlist(kd, nl) != 0) {
309 			for (p = nl; p->n_type != 0; ++p)
310 				;
311 			_kvm_err(kd, kd->program,
312 				 "%s: no such symbol", p->n_name);
313 			return (0);
314 		}
315 		if (KREAD(kd, nl[0].n_value, &nprocs)) {
316 			_kvm_err(kd, kd->program, "can't read nprocs");
317 			return (0);
318 		}
319 		size = nprocs * sizeof(struct kinfo_proc);
320 		kd->procbase = (struct kinfo_proc *)_kvm_malloc(kd, size);
321 		if (kd->procbase == 0)
322 			return (0);
323 
324 		nprocs = kvm_deadprocs(kd, op, arg, nl[1].n_value,
325 				      nl[2].n_value, nprocs);
326 #ifdef notdef
327 		size = nprocs * sizeof(struct kinfo_proc);
328 		(void)realloc(kd->procbase, size);
329 #endif
330 	}
331 	*cnt = nprocs;
332 	return (kd->procbase);
333 }
334 
335 void
336 _kvm_freeprocs(kd)
337 	kvm_t *kd;
338 {
339 	if (kd->procbase) {
340 		free(kd->procbase);
341 		kd->procbase = 0;
342 	}
343 }
344 
345 void *
346 _kvm_realloc(kd, p, n)
347 	kvm_t *kd;
348 	void *p;
349 	size_t n;
350 {
351 	void *np = (void *)realloc(p, n);
352 
353 	if (np == 0)
354 		_kvm_err(kd, kd->program, "out of memory");
355 	return (np);
356 }
357 
358 #ifndef MAX
359 #define MAX(a, b) ((a) > (b) ? (a) : (b))
360 #endif
361 
362 /*
363  * Read in an argument vector from the user address space of process p.
364  * addr is the user-space base address of narg null-terminated contiguous
365  * strings.  This is used to read in both the command arguments and
366  * environment strings.  Read at most maxcnt characters of strings.
367  */
368 static char **
369 kvm_argv(kd, p, addr, narg, maxcnt)
370 	kvm_t *kd;
371 	struct proc *p;
372 	register u_long addr;
373 	register int narg;
374 	register int maxcnt;
375 {
376 	register char *cp;
377 	register int len, cc;
378 	register char **argv;
379 
380 	/*
381 	 * Check that there aren't an unreasonable number of agruments,
382 	 * and that the address is in user space.
383 	 */
384 	if (narg > 512 || addr < VM_MIN_ADDRESS || addr >= VM_MAXUSER_ADDRESS)
385 		return (0);
386 
387 	if (kd->argv == 0) {
388 		/*
389 		 * Try to avoid reallocs.
390 		 */
391 		kd->argc = MAX(narg + 1, 32);
392 		kd->argv = (char **)_kvm_malloc(kd, kd->argc *
393 						sizeof(*kd->argv));
394 		if (kd->argv == 0)
395 			return (0);
396 	} else if (narg + 1 > kd->argc) {
397 		kd->argc = MAX(2 * kd->argc, narg + 1);
398 		kd->argv = (char **)_kvm_realloc(kd, kd->argv, kd->argc *
399 						sizeof(*kd->argv));
400 		if (kd->argv == 0)
401 			return (0);
402 	}
403 	if (kd->argspc == 0) {
404 		kd->argspc = (char *)_kvm_malloc(kd, NBPG);
405 		if (kd->argspc == 0)
406 			return (0);
407 		kd->arglen = NBPG;
408 	}
409 	cp = kd->argspc;
410 	argv = kd->argv;
411 	*argv = cp;
412 	len = 0;
413 	/*
414 	 * Loop over pages, filling in the argument vector.
415 	 */
416 	while (addr < VM_MAXUSER_ADDRESS) {
417 		cc = NBPG - (addr & PGOFSET);
418 		if (maxcnt > 0 && cc > maxcnt - len)
419 			cc = maxcnt - len;;
420 		if (len + cc > kd->arglen) {
421 			register int off;
422 			register char **pp;
423 			register char *op = kd->argspc;
424 
425 			kd->arglen *= 2;
426 			kd->argspc = (char *)_kvm_realloc(kd, kd->argspc,
427 							  kd->arglen);
428 			if (kd->argspc == 0)
429 				return (0);
430 			cp = &kd->argspc[len];
431 			/*
432 			 * Adjust argv pointers in case realloc moved
433 			 * the string space.
434 			 */
435 			off = kd->argspc - op;
436 			for (pp = kd->argv; pp < argv; ++pp)
437 				*pp += off;
438 		}
439 		if (kvm_uread(kd, p, addr, cp, cc) != cc)
440 			/* XXX */
441 			return (0);
442 		len += cc;
443 		addr += cc;
444 
445 		if (maxcnt == 0 && len > 16 * NBPG)
446 			/* sanity */
447 			return (0);
448 
449 		while (--cc >= 0) {
450 			if (*cp++ == 0) {
451 				if (--narg <= 0 || (struct ps_strings *)(addr - cc) >= PS_STRINGS) {
452 					*++argv = 0;
453 					return (kd->argv);
454 				} else
455 					*++argv = cp;
456 			}
457 		}
458 		if (maxcnt > 0 && len >= maxcnt) {
459 			/*
460 			 * We're stopping prematurely.  Terminate the
461 			 * argv and current string.
462 			 */
463 			*++argv = 0;
464 			*cp = 0;
465 			return (kd->argv);
466 		}
467 	}
468 }
469 
470 static void
471 ps_str_a(p, addr, n)
472 	struct ps_strings *p;
473 	u_long *addr;
474 	int *n;
475 {
476 	*addr = (u_long)p->ps_argvstr;
477 	*n = p->ps_nargvstr;
478 }
479 
480 static void
481 ps_str_e(p, addr, n)
482 	struct ps_strings *p;
483 	u_long *addr;
484 	int *n;
485 {
486 	*addr = (u_long)p->ps_envstr;
487 	*n = p->ps_nenvstr;
488 }
489 
490 /*
491  * Determine if the proc indicated by p is still active.
492  * This test is not 100% foolproof in theory, but chances of
493  * being wrong are very low.
494  */
495 static int
496 proc_verify(kd, kernp, p)
497 	kvm_t *kd;
498 	u_long kernp;
499 	const struct proc *p;
500 {
501 	struct proc kernproc;
502 
503 	/*
504 	 * Just read in the whole proc.  It's not that big relative
505 	 * to the cost of the read system call.
506 	 */
507 	if (kvm_read(kd, kernp, (char *)&kernproc, sizeof(kernproc)) !=
508 	    sizeof(kernproc))
509 		return (0);
510 	return (p->p_pid == kernproc.p_pid &&
511 		(kernproc.p_stat != SZOMB || p->p_stat == SZOMB));
512 }
513 
514 static char **
515 kvm_doargv(kd, kp, nchr, info)
516 	kvm_t *kd;
517 	const struct kinfo_proc *kp;
518 	int nchr;
519 	int (*info)(struct ps_strings*, u_long *, int *);
520 {
521 	register const struct proc *p = &kp->kp_proc;
522 	register char **ap;
523 	u_long addr;
524 	int cnt;
525 	struct ps_strings arginfo;
526 
527 	/*
528 	 * Pointers are stored at the top of the user stack.
529 	 */
530 	if (p->p_stat == SZOMB ||
531 	    kvm_uread(kd, p, USRSTACK - sizeof(arginfo), (char *)&arginfo,
532 		      sizeof(arginfo)) != sizeof(arginfo))
533 		return (0);
534 
535 	(*info)(&arginfo, &addr, &cnt);
536 	ap = kvm_argv(kd, p, addr, cnt, nchr);
537 	/*
538 	 * For live kernels, make sure this process didn't go away.
539 	 */
540 	if (ap != 0 && ISALIVE(kd) &&
541 	    !proc_verify(kd, (u_long)kp->kp_eproc.e_paddr, p))
542 		ap = 0;
543 	return (ap);
544 }
545 
546 /*
547  * Get the command args.  This code is now machine independent.
548  */
549 char **
550 kvm_getargv(kd, kp, nchr)
551 	kvm_t *kd;
552 	const struct kinfo_proc *kp;
553 	int nchr;
554 {
555 	return (kvm_doargv(kd, kp, nchr, ps_str_a));
556 }
557 
558 char **
559 kvm_getenvv(kd, kp, nchr)
560 	kvm_t *kd;
561 	const struct kinfo_proc *kp;
562 	int nchr;
563 {
564 	return (kvm_doargv(kd, kp, nchr, ps_str_e));
565 }
566 
567 /*
568  * Read from user space.  The user context is given by p.
569  */
570 ssize_t
571 kvm_uread(kd, p, uva, buf, len)
572 	kvm_t *kd;
573 	register struct proc *p;
574 	register u_long uva;
575 	register char *buf;
576 	register size_t len;
577 {
578 	register char *cp;
579 	char procfile[MAXPATHLEN];
580 	ssize_t amount;
581 	int fd;
582 	u_long tmpuva = uva;
583 	int i;
584 	char *chr;
585 
586 	cp = buf;
587 
588 	sprintf(procfile, "/proc/%d/mem", p->p_pid);
589 	fd = open(procfile, O_RDONLY, 0);
590 
591 	if (fd < 0) {
592 		_kvm_err(kd, kd->program, "cannot open %s", procfile);
593 		close(fd);
594 		return (0);
595 	}
596 
597 
598 	while (len > 0) {
599 		if (lseek(fd, uva, 0) == -1 && errno != 0) {
600 			_kvm_err(kd, kd->program, "invalid address (%x) in %s", uva, procfile);
601 			break;
602 		}
603 		amount = read(fd, buf, len);
604 		if (amount < 0) {
605 			_kvm_err(kd, kd->program, "error reading %s", procfile);
606 			break;
607 		}
608 		cp += amount;
609 		uva += amount;
610 		len -= amount;
611 	}
612 
613 	close(fd);
614 	return (ssize_t)(cp - buf);
615 }
616