xref: /freebsd/sys/kern/kern_proc.c (revision ff0ba87247820afbdfdc1b307c803f7923d0e4d3)
1 /*-
2  * Copyright (c) 1982, 1986, 1989, 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  *	@(#)kern_proc.c	8.7 (Berkeley) 2/14/95
30  */
31 
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
34 
35 #include "opt_compat.h"
36 #include "opt_ddb.h"
37 #include "opt_ktrace.h"
38 #include "opt_kstack_pages.h"
39 #include "opt_stack.h"
40 
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/elf.h>
44 #include <sys/exec.h>
45 #include <sys/kernel.h>
46 #include <sys/limits.h>
47 #include <sys/lock.h>
48 #include <sys/loginclass.h>
49 #include <sys/malloc.h>
50 #include <sys/mman.h>
51 #include <sys/mount.h>
52 #include <sys/mutex.h>
53 #include <sys/proc.h>
54 #include <sys/ptrace.h>
55 #include <sys/refcount.h>
56 #include <sys/resourcevar.h>
57 #include <sys/rwlock.h>
58 #include <sys/sbuf.h>
59 #include <sys/sysent.h>
60 #include <sys/sched.h>
61 #include <sys/smp.h>
62 #include <sys/stack.h>
63 #include <sys/stat.h>
64 #include <sys/sysctl.h>
65 #include <sys/filedesc.h>
66 #include <sys/tty.h>
67 #include <sys/signalvar.h>
68 #include <sys/sdt.h>
69 #include <sys/sx.h>
70 #include <sys/user.h>
71 #include <sys/jail.h>
72 #include <sys/vnode.h>
73 #include <sys/eventhandler.h>
74 
75 #ifdef DDB
76 #include <ddb/ddb.h>
77 #endif
78 
79 #include <vm/vm.h>
80 #include <vm/vm_param.h>
81 #include <vm/vm_extern.h>
82 #include <vm/pmap.h>
83 #include <vm/vm_map.h>
84 #include <vm/vm_object.h>
85 #include <vm/vm_page.h>
86 #include <vm/uma.h>
87 
88 #ifdef COMPAT_FREEBSD32
89 #include <compat/freebsd32/freebsd32.h>
90 #include <compat/freebsd32/freebsd32_util.h>
91 #endif
92 
93 SDT_PROVIDER_DEFINE(proc);
94 SDT_PROBE_DEFINE4(proc, kernel, ctor, entry, "struct proc *", "int",
95     "void *", "int");
96 SDT_PROBE_DEFINE4(proc, kernel, ctor, return, "struct proc *", "int",
97     "void *", "int");
98 SDT_PROBE_DEFINE4(proc, kernel, dtor, entry, "struct proc *", "int",
99     "void *", "struct thread *");
100 SDT_PROBE_DEFINE3(proc, kernel, dtor, return, "struct proc *", "int",
101     "void *");
102 SDT_PROBE_DEFINE3(proc, kernel, init, entry, "struct proc *", "int",
103     "int");
104 SDT_PROBE_DEFINE3(proc, kernel, init, return, "struct proc *", "int",
105     "int");
106 
107 MALLOC_DEFINE(M_PGRP, "pgrp", "process group header");
108 MALLOC_DEFINE(M_SESSION, "session", "session header");
109 static MALLOC_DEFINE(M_PROC, "proc", "Proc structures");
110 MALLOC_DEFINE(M_SUBPROC, "subproc", "Proc sub-structures");
111 
112 static void doenterpgrp(struct proc *, struct pgrp *);
113 static void orphanpg(struct pgrp *pg);
114 static void fill_kinfo_aggregate(struct proc *p, struct kinfo_proc *kp);
115 static void fill_kinfo_proc_only(struct proc *p, struct kinfo_proc *kp);
116 static void fill_kinfo_thread(struct thread *td, struct kinfo_proc *kp,
117     int preferthread);
118 static void pgadjustjobc(struct pgrp *pgrp, int entering);
119 static void pgdelete(struct pgrp *);
120 static int proc_ctor(void *mem, int size, void *arg, int flags);
121 static void proc_dtor(void *mem, int size, void *arg);
122 static int proc_init(void *mem, int size, int flags);
123 static void proc_fini(void *mem, int size);
124 static void pargs_free(struct pargs *pa);
125 static struct proc *zpfind_locked(pid_t pid);
126 
127 /*
128  * Other process lists
129  */
130 struct pidhashhead *pidhashtbl;
131 u_long pidhash;
132 struct pgrphashhead *pgrphashtbl;
133 u_long pgrphash;
134 struct proclist allproc;
135 struct proclist zombproc;
136 struct sx allproc_lock;
137 struct sx proctree_lock;
138 struct mtx ppeers_lock;
139 uma_zone_t proc_zone;
140 
141 int kstack_pages = KSTACK_PAGES;
142 SYSCTL_INT(_kern, OID_AUTO, kstack_pages, CTLFLAG_RD, &kstack_pages, 0,
143     "Kernel stack size in pages");
144 static int vmmap_skip_res_cnt = 0;
145 SYSCTL_INT(_kern, OID_AUTO, proc_vmmap_skip_resident_count, CTLFLAG_RW,
146     &vmmap_skip_res_cnt, 0,
147     "Skip calculation of the pages resident count in kern.proc.vmmap");
148 
149 CTASSERT(sizeof(struct kinfo_proc) == KINFO_PROC_SIZE);
150 #ifdef COMPAT_FREEBSD32
151 CTASSERT(sizeof(struct kinfo_proc32) == KINFO_PROC32_SIZE);
152 #endif
153 
154 /*
155  * Initialize global process hashing structures.
156  */
157 void
158 procinit()
159 {
160 
161 	sx_init(&allproc_lock, "allproc");
162 	sx_init(&proctree_lock, "proctree");
163 	mtx_init(&ppeers_lock, "p_peers", NULL, MTX_DEF);
164 	LIST_INIT(&allproc);
165 	LIST_INIT(&zombproc);
166 	pidhashtbl = hashinit(maxproc / 4, M_PROC, &pidhash);
167 	pgrphashtbl = hashinit(maxproc / 4, M_PROC, &pgrphash);
168 	proc_zone = uma_zcreate("PROC", sched_sizeof_proc(),
169 	    proc_ctor, proc_dtor, proc_init, proc_fini,
170 	    UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
171 	uihashinit();
172 }
173 
174 /*
175  * Prepare a proc for use.
176  */
177 static int
178 proc_ctor(void *mem, int size, void *arg, int flags)
179 {
180 	struct proc *p;
181 
182 	p = (struct proc *)mem;
183 	SDT_PROBE(proc, kernel, ctor , entry, p, size, arg, flags, 0);
184 	EVENTHANDLER_INVOKE(process_ctor, p);
185 	SDT_PROBE(proc, kernel, ctor , return, p, size, arg, flags, 0);
186 	return (0);
187 }
188 
189 /*
190  * Reclaim a proc after use.
191  */
192 static void
193 proc_dtor(void *mem, int size, void *arg)
194 {
195 	struct proc *p;
196 	struct thread *td;
197 
198 	/* INVARIANTS checks go here */
199 	p = (struct proc *)mem;
200 	td = FIRST_THREAD_IN_PROC(p);
201 	SDT_PROBE(proc, kernel, dtor, entry, p, size, arg, td, 0);
202 	if (td != NULL) {
203 #ifdef INVARIANTS
204 		KASSERT((p->p_numthreads == 1),
205 		    ("bad number of threads in exiting process"));
206 		KASSERT(STAILQ_EMPTY(&p->p_ktr), ("proc_dtor: non-empty p_ktr"));
207 #endif
208 		/* Free all OSD associated to this thread. */
209 		osd_thread_exit(td);
210 	}
211 	EVENTHANDLER_INVOKE(process_dtor, p);
212 	if (p->p_ksi != NULL)
213 		KASSERT(! KSI_ONQ(p->p_ksi), ("SIGCHLD queue"));
214 	SDT_PROBE(proc, kernel, dtor, return, p, size, arg, 0, 0);
215 }
216 
217 /*
218  * Initialize type-stable parts of a proc (when newly created).
219  */
220 static int
221 proc_init(void *mem, int size, int flags)
222 {
223 	struct proc *p;
224 
225 	p = (struct proc *)mem;
226 	SDT_PROBE(proc, kernel, init, entry, p, size, flags, 0, 0);
227 	p->p_sched = (struct p_sched *)&p[1];
228 	bzero(&p->p_mtx, sizeof(struct mtx));
229 	mtx_init(&p->p_mtx, "process lock", NULL, MTX_DEF | MTX_DUPOK);
230 	mtx_init(&p->p_slock, "process slock", NULL, MTX_SPIN | MTX_RECURSE);
231 	cv_init(&p->p_pwait, "ppwait");
232 	cv_init(&p->p_dbgwait, "dbgwait");
233 	TAILQ_INIT(&p->p_threads);	     /* all threads in proc */
234 	EVENTHANDLER_INVOKE(process_init, p);
235 	p->p_stats = pstats_alloc();
236 	SDT_PROBE(proc, kernel, init, return, p, size, flags, 0, 0);
237 	return (0);
238 }
239 
240 /*
241  * UMA should ensure that this function is never called.
242  * Freeing a proc structure would violate type stability.
243  */
244 static void
245 proc_fini(void *mem, int size)
246 {
247 #ifdef notnow
248 	struct proc *p;
249 
250 	p = (struct proc *)mem;
251 	EVENTHANDLER_INVOKE(process_fini, p);
252 	pstats_free(p->p_stats);
253 	thread_free(FIRST_THREAD_IN_PROC(p));
254 	mtx_destroy(&p->p_mtx);
255 	if (p->p_ksi != NULL)
256 		ksiginfo_free(p->p_ksi);
257 #else
258 	panic("proc reclaimed");
259 #endif
260 }
261 
262 /*
263  * Is p an inferior of the current process?
264  */
265 int
266 inferior(struct proc *p)
267 {
268 
269 	sx_assert(&proctree_lock, SX_LOCKED);
270 	PROC_LOCK_ASSERT(p, MA_OWNED);
271 	for (; p != curproc; p = proc_realparent(p)) {
272 		if (p->p_pid == 0)
273 			return (0);
274 	}
275 	return (1);
276 }
277 
278 struct proc *
279 pfind_locked(pid_t pid)
280 {
281 	struct proc *p;
282 
283 	sx_assert(&allproc_lock, SX_LOCKED);
284 	LIST_FOREACH(p, PIDHASH(pid), p_hash) {
285 		if (p->p_pid == pid) {
286 			PROC_LOCK(p);
287 			if (p->p_state == PRS_NEW) {
288 				PROC_UNLOCK(p);
289 				p = NULL;
290 			}
291 			break;
292 		}
293 	}
294 	return (p);
295 }
296 
297 /*
298  * Locate a process by number; return only "live" processes -- i.e., neither
299  * zombies nor newly born but incompletely initialized processes.  By not
300  * returning processes in the PRS_NEW state, we allow callers to avoid
301  * testing for that condition to avoid dereferencing p_ucred, et al.
302  */
303 struct proc *
304 pfind(pid_t pid)
305 {
306 	struct proc *p;
307 
308 	sx_slock(&allproc_lock);
309 	p = pfind_locked(pid);
310 	sx_sunlock(&allproc_lock);
311 	return (p);
312 }
313 
314 static struct proc *
315 pfind_tid_locked(pid_t tid)
316 {
317 	struct proc *p;
318 	struct thread *td;
319 
320 	sx_assert(&allproc_lock, SX_LOCKED);
321 	FOREACH_PROC_IN_SYSTEM(p) {
322 		PROC_LOCK(p);
323 		if (p->p_state == PRS_NEW) {
324 			PROC_UNLOCK(p);
325 			continue;
326 		}
327 		FOREACH_THREAD_IN_PROC(p, td) {
328 			if (td->td_tid == tid)
329 				goto found;
330 		}
331 		PROC_UNLOCK(p);
332 	}
333 found:
334 	return (p);
335 }
336 
337 /*
338  * Locate a process group by number.
339  * The caller must hold proctree_lock.
340  */
341 struct pgrp *
342 pgfind(pgid)
343 	register pid_t pgid;
344 {
345 	register struct pgrp *pgrp;
346 
347 	sx_assert(&proctree_lock, SX_LOCKED);
348 
349 	LIST_FOREACH(pgrp, PGRPHASH(pgid), pg_hash) {
350 		if (pgrp->pg_id == pgid) {
351 			PGRP_LOCK(pgrp);
352 			return (pgrp);
353 		}
354 	}
355 	return (NULL);
356 }
357 
358 /*
359  * Locate process and do additional manipulations, depending on flags.
360  */
361 int
362 pget(pid_t pid, int flags, struct proc **pp)
363 {
364 	struct proc *p;
365 	int error;
366 
367 	sx_slock(&allproc_lock);
368 	if (pid <= PID_MAX) {
369 		p = pfind_locked(pid);
370 		if (p == NULL && (flags & PGET_NOTWEXIT) == 0)
371 			p = zpfind_locked(pid);
372 	} else if ((flags & PGET_NOTID) == 0) {
373 		p = pfind_tid_locked(pid);
374 	} else {
375 		p = NULL;
376 	}
377 	sx_sunlock(&allproc_lock);
378 	if (p == NULL)
379 		return (ESRCH);
380 	if ((flags & PGET_CANSEE) != 0) {
381 		error = p_cansee(curthread, p);
382 		if (error != 0)
383 			goto errout;
384 	}
385 	if ((flags & PGET_CANDEBUG) != 0) {
386 		error = p_candebug(curthread, p);
387 		if (error != 0)
388 			goto errout;
389 	}
390 	if ((flags & PGET_ISCURRENT) != 0 && curproc != p) {
391 		error = EPERM;
392 		goto errout;
393 	}
394 	if ((flags & PGET_NOTWEXIT) != 0 && (p->p_flag & P_WEXIT) != 0) {
395 		error = ESRCH;
396 		goto errout;
397 	}
398 	if ((flags & PGET_NOTINEXEC) != 0 && (p->p_flag & P_INEXEC) != 0) {
399 		/*
400 		 * XXXRW: Not clear ESRCH is the right error during proc
401 		 * execve().
402 		 */
403 		error = ESRCH;
404 		goto errout;
405 	}
406 	if ((flags & PGET_HOLD) != 0) {
407 		_PHOLD(p);
408 		PROC_UNLOCK(p);
409 	}
410 	*pp = p;
411 	return (0);
412 errout:
413 	PROC_UNLOCK(p);
414 	return (error);
415 }
416 
417 /*
418  * Create a new process group.
419  * pgid must be equal to the pid of p.
420  * Begin a new session if required.
421  */
422 int
423 enterpgrp(p, pgid, pgrp, sess)
424 	register struct proc *p;
425 	pid_t pgid;
426 	struct pgrp *pgrp;
427 	struct session *sess;
428 {
429 
430 	sx_assert(&proctree_lock, SX_XLOCKED);
431 
432 	KASSERT(pgrp != NULL, ("enterpgrp: pgrp == NULL"));
433 	KASSERT(p->p_pid == pgid,
434 	    ("enterpgrp: new pgrp and pid != pgid"));
435 	KASSERT(pgfind(pgid) == NULL,
436 	    ("enterpgrp: pgrp with pgid exists"));
437 	KASSERT(!SESS_LEADER(p),
438 	    ("enterpgrp: session leader attempted setpgrp"));
439 
440 	mtx_init(&pgrp->pg_mtx, "process group", NULL, MTX_DEF | MTX_DUPOK);
441 
442 	if (sess != NULL) {
443 		/*
444 		 * new session
445 		 */
446 		mtx_init(&sess->s_mtx, "session", NULL, MTX_DEF);
447 		PROC_LOCK(p);
448 		p->p_flag &= ~P_CONTROLT;
449 		PROC_UNLOCK(p);
450 		PGRP_LOCK(pgrp);
451 		sess->s_leader = p;
452 		sess->s_sid = p->p_pid;
453 		refcount_init(&sess->s_count, 1);
454 		sess->s_ttyvp = NULL;
455 		sess->s_ttydp = NULL;
456 		sess->s_ttyp = NULL;
457 		bcopy(p->p_session->s_login, sess->s_login,
458 			    sizeof(sess->s_login));
459 		pgrp->pg_session = sess;
460 		KASSERT(p == curproc,
461 		    ("enterpgrp: mksession and p != curproc"));
462 	} else {
463 		pgrp->pg_session = p->p_session;
464 		sess_hold(pgrp->pg_session);
465 		PGRP_LOCK(pgrp);
466 	}
467 	pgrp->pg_id = pgid;
468 	LIST_INIT(&pgrp->pg_members);
469 
470 	/*
471 	 * As we have an exclusive lock of proctree_lock,
472 	 * this should not deadlock.
473 	 */
474 	LIST_INSERT_HEAD(PGRPHASH(pgid), pgrp, pg_hash);
475 	pgrp->pg_jobc = 0;
476 	SLIST_INIT(&pgrp->pg_sigiolst);
477 	PGRP_UNLOCK(pgrp);
478 
479 	doenterpgrp(p, pgrp);
480 
481 	return (0);
482 }
483 
484 /*
485  * Move p to an existing process group
486  */
487 int
488 enterthispgrp(p, pgrp)
489 	register struct proc *p;
490 	struct pgrp *pgrp;
491 {
492 
493 	sx_assert(&proctree_lock, SX_XLOCKED);
494 	PROC_LOCK_ASSERT(p, MA_NOTOWNED);
495 	PGRP_LOCK_ASSERT(pgrp, MA_NOTOWNED);
496 	PGRP_LOCK_ASSERT(p->p_pgrp, MA_NOTOWNED);
497 	SESS_LOCK_ASSERT(p->p_session, MA_NOTOWNED);
498 	KASSERT(pgrp->pg_session == p->p_session,
499 		("%s: pgrp's session %p, p->p_session %p.\n",
500 		__func__,
501 		pgrp->pg_session,
502 		p->p_session));
503 	KASSERT(pgrp != p->p_pgrp,
504 		("%s: p belongs to pgrp.", __func__));
505 
506 	doenterpgrp(p, pgrp);
507 
508 	return (0);
509 }
510 
511 /*
512  * Move p to a process group
513  */
514 static void
515 doenterpgrp(p, pgrp)
516 	struct proc *p;
517 	struct pgrp *pgrp;
518 {
519 	struct pgrp *savepgrp;
520 
521 	sx_assert(&proctree_lock, SX_XLOCKED);
522 	PROC_LOCK_ASSERT(p, MA_NOTOWNED);
523 	PGRP_LOCK_ASSERT(pgrp, MA_NOTOWNED);
524 	PGRP_LOCK_ASSERT(p->p_pgrp, MA_NOTOWNED);
525 	SESS_LOCK_ASSERT(p->p_session, MA_NOTOWNED);
526 
527 	savepgrp = p->p_pgrp;
528 
529 	/*
530 	 * Adjust eligibility of affected pgrps to participate in job control.
531 	 * Increment eligibility counts before decrementing, otherwise we
532 	 * could reach 0 spuriously during the first call.
533 	 */
534 	fixjobc(p, pgrp, 1);
535 	fixjobc(p, p->p_pgrp, 0);
536 
537 	PGRP_LOCK(pgrp);
538 	PGRP_LOCK(savepgrp);
539 	PROC_LOCK(p);
540 	LIST_REMOVE(p, p_pglist);
541 	p->p_pgrp = pgrp;
542 	PROC_UNLOCK(p);
543 	LIST_INSERT_HEAD(&pgrp->pg_members, p, p_pglist);
544 	PGRP_UNLOCK(savepgrp);
545 	PGRP_UNLOCK(pgrp);
546 	if (LIST_EMPTY(&savepgrp->pg_members))
547 		pgdelete(savepgrp);
548 }
549 
550 /*
551  * remove process from process group
552  */
553 int
554 leavepgrp(p)
555 	register struct proc *p;
556 {
557 	struct pgrp *savepgrp;
558 
559 	sx_assert(&proctree_lock, SX_XLOCKED);
560 	savepgrp = p->p_pgrp;
561 	PGRP_LOCK(savepgrp);
562 	PROC_LOCK(p);
563 	LIST_REMOVE(p, p_pglist);
564 	p->p_pgrp = NULL;
565 	PROC_UNLOCK(p);
566 	PGRP_UNLOCK(savepgrp);
567 	if (LIST_EMPTY(&savepgrp->pg_members))
568 		pgdelete(savepgrp);
569 	return (0);
570 }
571 
572 /*
573  * delete a process group
574  */
575 static void
576 pgdelete(pgrp)
577 	register struct pgrp *pgrp;
578 {
579 	struct session *savesess;
580 	struct tty *tp;
581 
582 	sx_assert(&proctree_lock, SX_XLOCKED);
583 	PGRP_LOCK_ASSERT(pgrp, MA_NOTOWNED);
584 	SESS_LOCK_ASSERT(pgrp->pg_session, MA_NOTOWNED);
585 
586 	/*
587 	 * Reset any sigio structures pointing to us as a result of
588 	 * F_SETOWN with our pgid.
589 	 */
590 	funsetownlst(&pgrp->pg_sigiolst);
591 
592 	PGRP_LOCK(pgrp);
593 	tp = pgrp->pg_session->s_ttyp;
594 	LIST_REMOVE(pgrp, pg_hash);
595 	savesess = pgrp->pg_session;
596 	PGRP_UNLOCK(pgrp);
597 
598 	/* Remove the reference to the pgrp before deallocating it. */
599 	if (tp != NULL) {
600 		tty_lock(tp);
601 		tty_rel_pgrp(tp, pgrp);
602 	}
603 
604 	mtx_destroy(&pgrp->pg_mtx);
605 	free(pgrp, M_PGRP);
606 	sess_release(savesess);
607 }
608 
609 static void
610 pgadjustjobc(pgrp, entering)
611 	struct pgrp *pgrp;
612 	int entering;
613 {
614 
615 	PGRP_LOCK(pgrp);
616 	if (entering)
617 		pgrp->pg_jobc++;
618 	else {
619 		--pgrp->pg_jobc;
620 		if (pgrp->pg_jobc == 0)
621 			orphanpg(pgrp);
622 	}
623 	PGRP_UNLOCK(pgrp);
624 }
625 
626 /*
627  * Adjust pgrp jobc counters when specified process changes process group.
628  * We count the number of processes in each process group that "qualify"
629  * the group for terminal job control (those with a parent in a different
630  * process group of the same session).  If that count reaches zero, the
631  * process group becomes orphaned.  Check both the specified process'
632  * process group and that of its children.
633  * entering == 0 => p is leaving specified group.
634  * entering == 1 => p is entering specified group.
635  */
636 void
637 fixjobc(p, pgrp, entering)
638 	register struct proc *p;
639 	register struct pgrp *pgrp;
640 	int entering;
641 {
642 	register struct pgrp *hispgrp;
643 	register struct session *mysession;
644 
645 	sx_assert(&proctree_lock, SX_LOCKED);
646 	PROC_LOCK_ASSERT(p, MA_NOTOWNED);
647 	PGRP_LOCK_ASSERT(pgrp, MA_NOTOWNED);
648 	SESS_LOCK_ASSERT(pgrp->pg_session, MA_NOTOWNED);
649 
650 	/*
651 	 * Check p's parent to see whether p qualifies its own process
652 	 * group; if so, adjust count for p's process group.
653 	 */
654 	mysession = pgrp->pg_session;
655 	if ((hispgrp = p->p_pptr->p_pgrp) != pgrp &&
656 	    hispgrp->pg_session == mysession)
657 		pgadjustjobc(pgrp, entering);
658 
659 	/*
660 	 * Check this process' children to see whether they qualify
661 	 * their process groups; if so, adjust counts for children's
662 	 * process groups.
663 	 */
664 	LIST_FOREACH(p, &p->p_children, p_sibling) {
665 		hispgrp = p->p_pgrp;
666 		if (hispgrp == pgrp ||
667 		    hispgrp->pg_session != mysession)
668 			continue;
669 		PROC_LOCK(p);
670 		if (p->p_state == PRS_ZOMBIE) {
671 			PROC_UNLOCK(p);
672 			continue;
673 		}
674 		PROC_UNLOCK(p);
675 		pgadjustjobc(hispgrp, entering);
676 	}
677 }
678 
679 /*
680  * A process group has become orphaned;
681  * if there are any stopped processes in the group,
682  * hang-up all process in that group.
683  */
684 static void
685 orphanpg(pg)
686 	struct pgrp *pg;
687 {
688 	register struct proc *p;
689 
690 	PGRP_LOCK_ASSERT(pg, MA_OWNED);
691 
692 	LIST_FOREACH(p, &pg->pg_members, p_pglist) {
693 		PROC_LOCK(p);
694 		if (P_SHOULDSTOP(p)) {
695 			PROC_UNLOCK(p);
696 			LIST_FOREACH(p, &pg->pg_members, p_pglist) {
697 				PROC_LOCK(p);
698 				kern_psignal(p, SIGHUP);
699 				kern_psignal(p, SIGCONT);
700 				PROC_UNLOCK(p);
701 			}
702 			return;
703 		}
704 		PROC_UNLOCK(p);
705 	}
706 }
707 
708 void
709 sess_hold(struct session *s)
710 {
711 
712 	refcount_acquire(&s->s_count);
713 }
714 
715 void
716 sess_release(struct session *s)
717 {
718 
719 	if (refcount_release(&s->s_count)) {
720 		if (s->s_ttyp != NULL) {
721 			tty_lock(s->s_ttyp);
722 			tty_rel_sess(s->s_ttyp, s);
723 		}
724 		mtx_destroy(&s->s_mtx);
725 		free(s, M_SESSION);
726 	}
727 }
728 
729 #ifdef DDB
730 
731 DB_SHOW_COMMAND(pgrpdump, pgrpdump)
732 {
733 	register struct pgrp *pgrp;
734 	register struct proc *p;
735 	register int i;
736 
737 	for (i = 0; i <= pgrphash; i++) {
738 		if (!LIST_EMPTY(&pgrphashtbl[i])) {
739 			printf("\tindx %d\n", i);
740 			LIST_FOREACH(pgrp, &pgrphashtbl[i], pg_hash) {
741 				printf(
742 			"\tpgrp %p, pgid %ld, sess %p, sesscnt %d, mem %p\n",
743 				    (void *)pgrp, (long)pgrp->pg_id,
744 				    (void *)pgrp->pg_session,
745 				    pgrp->pg_session->s_count,
746 				    (void *)LIST_FIRST(&pgrp->pg_members));
747 				LIST_FOREACH(p, &pgrp->pg_members, p_pglist) {
748 					printf("\t\tpid %ld addr %p pgrp %p\n",
749 					    (long)p->p_pid, (void *)p,
750 					    (void *)p->p_pgrp);
751 				}
752 			}
753 		}
754 	}
755 }
756 #endif /* DDB */
757 
758 /*
759  * Calculate the kinfo_proc members which contain process-wide
760  * informations.
761  * Must be called with the target process locked.
762  */
763 static void
764 fill_kinfo_aggregate(struct proc *p, struct kinfo_proc *kp)
765 {
766 	struct thread *td;
767 
768 	PROC_LOCK_ASSERT(p, MA_OWNED);
769 
770 	kp->ki_estcpu = 0;
771 	kp->ki_pctcpu = 0;
772 	FOREACH_THREAD_IN_PROC(p, td) {
773 		thread_lock(td);
774 		kp->ki_pctcpu += sched_pctcpu(td);
775 		kp->ki_estcpu += td->td_estcpu;
776 		thread_unlock(td);
777 	}
778 }
779 
780 /*
781  * Clear kinfo_proc and fill in any information that is common
782  * to all threads in the process.
783  * Must be called with the target process locked.
784  */
785 static void
786 fill_kinfo_proc_only(struct proc *p, struct kinfo_proc *kp)
787 {
788 	struct thread *td0;
789 	struct tty *tp;
790 	struct session *sp;
791 	struct ucred *cred;
792 	struct sigacts *ps;
793 
794 	/* For proc_realparent. */
795 	sx_assert(&proctree_lock, SX_LOCKED);
796 	PROC_LOCK_ASSERT(p, MA_OWNED);
797 	bzero(kp, sizeof(*kp));
798 
799 	kp->ki_structsize = sizeof(*kp);
800 	kp->ki_paddr = p;
801 	kp->ki_addr =/* p->p_addr; */0; /* XXX */
802 	kp->ki_args = p->p_args;
803 	kp->ki_textvp = p->p_textvp;
804 #ifdef KTRACE
805 	kp->ki_tracep = p->p_tracevp;
806 	kp->ki_traceflag = p->p_traceflag;
807 #endif
808 	kp->ki_fd = p->p_fd;
809 	kp->ki_vmspace = p->p_vmspace;
810 	kp->ki_flag = p->p_flag;
811 	kp->ki_flag2 = p->p_flag2;
812 	cred = p->p_ucred;
813 	if (cred) {
814 		kp->ki_uid = cred->cr_uid;
815 		kp->ki_ruid = cred->cr_ruid;
816 		kp->ki_svuid = cred->cr_svuid;
817 		kp->ki_cr_flags = 0;
818 		if (cred->cr_flags & CRED_FLAG_CAPMODE)
819 			kp->ki_cr_flags |= KI_CRF_CAPABILITY_MODE;
820 		/* XXX bde doesn't like KI_NGROUPS */
821 		if (cred->cr_ngroups > KI_NGROUPS) {
822 			kp->ki_ngroups = KI_NGROUPS;
823 			kp->ki_cr_flags |= KI_CRF_GRP_OVERFLOW;
824 		} else
825 			kp->ki_ngroups = cred->cr_ngroups;
826 		bcopy(cred->cr_groups, kp->ki_groups,
827 		    kp->ki_ngroups * sizeof(gid_t));
828 		kp->ki_rgid = cred->cr_rgid;
829 		kp->ki_svgid = cred->cr_svgid;
830 		/* If jailed(cred), emulate the old P_JAILED flag. */
831 		if (jailed(cred)) {
832 			kp->ki_flag |= P_JAILED;
833 			/* If inside the jail, use 0 as a jail ID. */
834 			if (cred->cr_prison != curthread->td_ucred->cr_prison)
835 				kp->ki_jid = cred->cr_prison->pr_id;
836 		}
837 		strlcpy(kp->ki_loginclass, cred->cr_loginclass->lc_name,
838 		    sizeof(kp->ki_loginclass));
839 	}
840 	ps = p->p_sigacts;
841 	if (ps) {
842 		mtx_lock(&ps->ps_mtx);
843 		kp->ki_sigignore = ps->ps_sigignore;
844 		kp->ki_sigcatch = ps->ps_sigcatch;
845 		mtx_unlock(&ps->ps_mtx);
846 	}
847 	if (p->p_state != PRS_NEW &&
848 	    p->p_state != PRS_ZOMBIE &&
849 	    p->p_vmspace != NULL) {
850 		struct vmspace *vm = p->p_vmspace;
851 
852 		kp->ki_size = vm->vm_map.size;
853 		kp->ki_rssize = vmspace_resident_count(vm); /*XXX*/
854 		FOREACH_THREAD_IN_PROC(p, td0) {
855 			if (!TD_IS_SWAPPED(td0))
856 				kp->ki_rssize += td0->td_kstack_pages;
857 		}
858 		kp->ki_swrss = vm->vm_swrss;
859 		kp->ki_tsize = vm->vm_tsize;
860 		kp->ki_dsize = vm->vm_dsize;
861 		kp->ki_ssize = vm->vm_ssize;
862 	} else if (p->p_state == PRS_ZOMBIE)
863 		kp->ki_stat = SZOMB;
864 	if (kp->ki_flag & P_INMEM)
865 		kp->ki_sflag = PS_INMEM;
866 	else
867 		kp->ki_sflag = 0;
868 	/* Calculate legacy swtime as seconds since 'swtick'. */
869 	kp->ki_swtime = (ticks - p->p_swtick) / hz;
870 	kp->ki_pid = p->p_pid;
871 	kp->ki_nice = p->p_nice;
872 	kp->ki_fibnum = p->p_fibnum;
873 	kp->ki_start = p->p_stats->p_start;
874 	timevaladd(&kp->ki_start, &boottime);
875 	PROC_SLOCK(p);
876 	rufetch(p, &kp->ki_rusage);
877 	kp->ki_runtime = cputick2usec(p->p_rux.rux_runtime);
878 	calcru(p, &kp->ki_rusage.ru_utime, &kp->ki_rusage.ru_stime);
879 	PROC_SUNLOCK(p);
880 	calccru(p, &kp->ki_childutime, &kp->ki_childstime);
881 	/* Some callers want child times in a single value. */
882 	kp->ki_childtime = kp->ki_childstime;
883 	timevaladd(&kp->ki_childtime, &kp->ki_childutime);
884 
885 	FOREACH_THREAD_IN_PROC(p, td0)
886 		kp->ki_cow += td0->td_cow;
887 
888 	tp = NULL;
889 	if (p->p_pgrp) {
890 		kp->ki_pgid = p->p_pgrp->pg_id;
891 		kp->ki_jobc = p->p_pgrp->pg_jobc;
892 		sp = p->p_pgrp->pg_session;
893 
894 		if (sp != NULL) {
895 			kp->ki_sid = sp->s_sid;
896 			SESS_LOCK(sp);
897 			strlcpy(kp->ki_login, sp->s_login,
898 			    sizeof(kp->ki_login));
899 			if (sp->s_ttyvp)
900 				kp->ki_kiflag |= KI_CTTY;
901 			if (SESS_LEADER(p))
902 				kp->ki_kiflag |= KI_SLEADER;
903 			/* XXX proctree_lock */
904 			tp = sp->s_ttyp;
905 			SESS_UNLOCK(sp);
906 		}
907 	}
908 	if ((p->p_flag & P_CONTROLT) && tp != NULL) {
909 		kp->ki_tdev = tty_udev(tp);
910 		kp->ki_tpgid = tp->t_pgrp ? tp->t_pgrp->pg_id : NO_PID;
911 		if (tp->t_session)
912 			kp->ki_tsid = tp->t_session->s_sid;
913 	} else
914 		kp->ki_tdev = NODEV;
915 	if (p->p_comm[0] != '\0')
916 		strlcpy(kp->ki_comm, p->p_comm, sizeof(kp->ki_comm));
917 	if (p->p_sysent && p->p_sysent->sv_name != NULL &&
918 	    p->p_sysent->sv_name[0] != '\0')
919 		strlcpy(kp->ki_emul, p->p_sysent->sv_name, sizeof(kp->ki_emul));
920 	kp->ki_siglist = p->p_siglist;
921 	kp->ki_xstat = p->p_xstat;
922 	kp->ki_acflag = p->p_acflag;
923 	kp->ki_lock = p->p_lock;
924 	if (p->p_pptr) {
925 		kp->ki_ppid = proc_realparent(p)->p_pid;
926 		if (p->p_flag & P_TRACED)
927 			kp->ki_tracer = p->p_pptr->p_pid;
928 	}
929 }
930 
931 /*
932  * Fill in information that is thread specific.  Must be called with
933  * target process locked.  If 'preferthread' is set, overwrite certain
934  * process-related fields that are maintained for both threads and
935  * processes.
936  */
937 static void
938 fill_kinfo_thread(struct thread *td, struct kinfo_proc *kp, int preferthread)
939 {
940 	struct proc *p;
941 
942 	p = td->td_proc;
943 	kp->ki_tdaddr = td;
944 	PROC_LOCK_ASSERT(p, MA_OWNED);
945 
946 	if (preferthread)
947 		PROC_SLOCK(p);
948 	thread_lock(td);
949 	if (td->td_wmesg != NULL)
950 		strlcpy(kp->ki_wmesg, td->td_wmesg, sizeof(kp->ki_wmesg));
951 	else
952 		bzero(kp->ki_wmesg, sizeof(kp->ki_wmesg));
953 	strlcpy(kp->ki_tdname, td->td_name, sizeof(kp->ki_tdname));
954 	if (TD_ON_LOCK(td)) {
955 		kp->ki_kiflag |= KI_LOCKBLOCK;
956 		strlcpy(kp->ki_lockname, td->td_lockname,
957 		    sizeof(kp->ki_lockname));
958 	} else {
959 		kp->ki_kiflag &= ~KI_LOCKBLOCK;
960 		bzero(kp->ki_lockname, sizeof(kp->ki_lockname));
961 	}
962 
963 	if (p->p_state == PRS_NORMAL) { /* approximate. */
964 		if (TD_ON_RUNQ(td) ||
965 		    TD_CAN_RUN(td) ||
966 		    TD_IS_RUNNING(td)) {
967 			kp->ki_stat = SRUN;
968 		} else if (P_SHOULDSTOP(p)) {
969 			kp->ki_stat = SSTOP;
970 		} else if (TD_IS_SLEEPING(td)) {
971 			kp->ki_stat = SSLEEP;
972 		} else if (TD_ON_LOCK(td)) {
973 			kp->ki_stat = SLOCK;
974 		} else {
975 			kp->ki_stat = SWAIT;
976 		}
977 	} else if (p->p_state == PRS_ZOMBIE) {
978 		kp->ki_stat = SZOMB;
979 	} else {
980 		kp->ki_stat = SIDL;
981 	}
982 
983 	/* Things in the thread */
984 	kp->ki_wchan = td->td_wchan;
985 	kp->ki_pri.pri_level = td->td_priority;
986 	kp->ki_pri.pri_native = td->td_base_pri;
987 
988 	/*
989 	 * Note: legacy fields; clamp at the old NOCPU value and/or
990 	 * the maximum u_char CPU value.
991 	 */
992 	if (td->td_lastcpu == NOCPU)
993 		kp->ki_lastcpu_old = NOCPU_OLD;
994 	else if (td->td_lastcpu > MAXCPU_OLD)
995 		kp->ki_lastcpu_old = MAXCPU_OLD;
996 	else
997 		kp->ki_lastcpu_old = td->td_lastcpu;
998 
999 	if (td->td_oncpu == NOCPU)
1000 		kp->ki_oncpu_old = NOCPU_OLD;
1001 	else if (td->td_oncpu > MAXCPU_OLD)
1002 		kp->ki_oncpu_old = MAXCPU_OLD;
1003 	else
1004 		kp->ki_oncpu_old = td->td_oncpu;
1005 
1006 	kp->ki_lastcpu = td->td_lastcpu;
1007 	kp->ki_oncpu = td->td_oncpu;
1008 	kp->ki_tdflags = td->td_flags;
1009 	kp->ki_tid = td->td_tid;
1010 	kp->ki_numthreads = p->p_numthreads;
1011 	kp->ki_pcb = td->td_pcb;
1012 	kp->ki_kstack = (void *)td->td_kstack;
1013 	kp->ki_slptime = (ticks - td->td_slptick) / hz;
1014 	kp->ki_pri.pri_class = td->td_pri_class;
1015 	kp->ki_pri.pri_user = td->td_user_pri;
1016 
1017 	if (preferthread) {
1018 		rufetchtd(td, &kp->ki_rusage);
1019 		kp->ki_runtime = cputick2usec(td->td_rux.rux_runtime);
1020 		kp->ki_pctcpu = sched_pctcpu(td);
1021 		kp->ki_estcpu = td->td_estcpu;
1022 		kp->ki_cow = td->td_cow;
1023 	}
1024 
1025 	/* We can't get this anymore but ps etc never used it anyway. */
1026 	kp->ki_rqindex = 0;
1027 
1028 	if (preferthread)
1029 		kp->ki_siglist = td->td_siglist;
1030 	kp->ki_sigmask = td->td_sigmask;
1031 	thread_unlock(td);
1032 	if (preferthread)
1033 		PROC_SUNLOCK(p);
1034 }
1035 
1036 /*
1037  * Fill in a kinfo_proc structure for the specified process.
1038  * Must be called with the target process locked.
1039  */
1040 void
1041 fill_kinfo_proc(struct proc *p, struct kinfo_proc *kp)
1042 {
1043 
1044 	MPASS(FIRST_THREAD_IN_PROC(p) != NULL);
1045 
1046 	fill_kinfo_proc_only(p, kp);
1047 	fill_kinfo_thread(FIRST_THREAD_IN_PROC(p), kp, 0);
1048 	fill_kinfo_aggregate(p, kp);
1049 }
1050 
1051 struct pstats *
1052 pstats_alloc(void)
1053 {
1054 
1055 	return (malloc(sizeof(struct pstats), M_SUBPROC, M_ZERO|M_WAITOK));
1056 }
1057 
1058 /*
1059  * Copy parts of p_stats; zero the rest of p_stats (statistics).
1060  */
1061 void
1062 pstats_fork(struct pstats *src, struct pstats *dst)
1063 {
1064 
1065 	bzero(&dst->pstat_startzero,
1066 	    __rangeof(struct pstats, pstat_startzero, pstat_endzero));
1067 	bcopy(&src->pstat_startcopy, &dst->pstat_startcopy,
1068 	    __rangeof(struct pstats, pstat_startcopy, pstat_endcopy));
1069 }
1070 
1071 void
1072 pstats_free(struct pstats *ps)
1073 {
1074 
1075 	free(ps, M_SUBPROC);
1076 }
1077 
1078 static struct proc *
1079 zpfind_locked(pid_t pid)
1080 {
1081 	struct proc *p;
1082 
1083 	sx_assert(&allproc_lock, SX_LOCKED);
1084 	LIST_FOREACH(p, &zombproc, p_list) {
1085 		if (p->p_pid == pid) {
1086 			PROC_LOCK(p);
1087 			break;
1088 		}
1089 	}
1090 	return (p);
1091 }
1092 
1093 /*
1094  * Locate a zombie process by number
1095  */
1096 struct proc *
1097 zpfind(pid_t pid)
1098 {
1099 	struct proc *p;
1100 
1101 	sx_slock(&allproc_lock);
1102 	p = zpfind_locked(pid);
1103 	sx_sunlock(&allproc_lock);
1104 	return (p);
1105 }
1106 
1107 #ifdef COMPAT_FREEBSD32
1108 
1109 /*
1110  * This function is typically used to copy out the kernel address, so
1111  * it can be replaced by assignment of zero.
1112  */
1113 static inline uint32_t
1114 ptr32_trim(void *ptr)
1115 {
1116 	uintptr_t uptr;
1117 
1118 	uptr = (uintptr_t)ptr;
1119 	return ((uptr > UINT_MAX) ? 0 : uptr);
1120 }
1121 
1122 #define PTRTRIM_CP(src,dst,fld) \
1123 	do { (dst).fld = ptr32_trim((src).fld); } while (0)
1124 
1125 static void
1126 freebsd32_kinfo_proc_out(const struct kinfo_proc *ki, struct kinfo_proc32 *ki32)
1127 {
1128 	int i;
1129 
1130 	bzero(ki32, sizeof(struct kinfo_proc32));
1131 	ki32->ki_structsize = sizeof(struct kinfo_proc32);
1132 	CP(*ki, *ki32, ki_layout);
1133 	PTRTRIM_CP(*ki, *ki32, ki_args);
1134 	PTRTRIM_CP(*ki, *ki32, ki_paddr);
1135 	PTRTRIM_CP(*ki, *ki32, ki_addr);
1136 	PTRTRIM_CP(*ki, *ki32, ki_tracep);
1137 	PTRTRIM_CP(*ki, *ki32, ki_textvp);
1138 	PTRTRIM_CP(*ki, *ki32, ki_fd);
1139 	PTRTRIM_CP(*ki, *ki32, ki_vmspace);
1140 	PTRTRIM_CP(*ki, *ki32, ki_wchan);
1141 	CP(*ki, *ki32, ki_pid);
1142 	CP(*ki, *ki32, ki_ppid);
1143 	CP(*ki, *ki32, ki_pgid);
1144 	CP(*ki, *ki32, ki_tpgid);
1145 	CP(*ki, *ki32, ki_sid);
1146 	CP(*ki, *ki32, ki_tsid);
1147 	CP(*ki, *ki32, ki_jobc);
1148 	CP(*ki, *ki32, ki_tdev);
1149 	CP(*ki, *ki32, ki_siglist);
1150 	CP(*ki, *ki32, ki_sigmask);
1151 	CP(*ki, *ki32, ki_sigignore);
1152 	CP(*ki, *ki32, ki_sigcatch);
1153 	CP(*ki, *ki32, ki_uid);
1154 	CP(*ki, *ki32, ki_ruid);
1155 	CP(*ki, *ki32, ki_svuid);
1156 	CP(*ki, *ki32, ki_rgid);
1157 	CP(*ki, *ki32, ki_svgid);
1158 	CP(*ki, *ki32, ki_ngroups);
1159 	for (i = 0; i < KI_NGROUPS; i++)
1160 		CP(*ki, *ki32, ki_groups[i]);
1161 	CP(*ki, *ki32, ki_size);
1162 	CP(*ki, *ki32, ki_rssize);
1163 	CP(*ki, *ki32, ki_swrss);
1164 	CP(*ki, *ki32, ki_tsize);
1165 	CP(*ki, *ki32, ki_dsize);
1166 	CP(*ki, *ki32, ki_ssize);
1167 	CP(*ki, *ki32, ki_xstat);
1168 	CP(*ki, *ki32, ki_acflag);
1169 	CP(*ki, *ki32, ki_pctcpu);
1170 	CP(*ki, *ki32, ki_estcpu);
1171 	CP(*ki, *ki32, ki_slptime);
1172 	CP(*ki, *ki32, ki_swtime);
1173 	CP(*ki, *ki32, ki_cow);
1174 	CP(*ki, *ki32, ki_runtime);
1175 	TV_CP(*ki, *ki32, ki_start);
1176 	TV_CP(*ki, *ki32, ki_childtime);
1177 	CP(*ki, *ki32, ki_flag);
1178 	CP(*ki, *ki32, ki_kiflag);
1179 	CP(*ki, *ki32, ki_traceflag);
1180 	CP(*ki, *ki32, ki_stat);
1181 	CP(*ki, *ki32, ki_nice);
1182 	CP(*ki, *ki32, ki_lock);
1183 	CP(*ki, *ki32, ki_rqindex);
1184 	CP(*ki, *ki32, ki_oncpu);
1185 	CP(*ki, *ki32, ki_lastcpu);
1186 
1187 	/* XXX TODO: wrap cpu value as appropriate */
1188 	CP(*ki, *ki32, ki_oncpu_old);
1189 	CP(*ki, *ki32, ki_lastcpu_old);
1190 
1191 	bcopy(ki->ki_tdname, ki32->ki_tdname, TDNAMLEN + 1);
1192 	bcopy(ki->ki_wmesg, ki32->ki_wmesg, WMESGLEN + 1);
1193 	bcopy(ki->ki_login, ki32->ki_login, LOGNAMELEN + 1);
1194 	bcopy(ki->ki_lockname, ki32->ki_lockname, LOCKNAMELEN + 1);
1195 	bcopy(ki->ki_comm, ki32->ki_comm, COMMLEN + 1);
1196 	bcopy(ki->ki_emul, ki32->ki_emul, KI_EMULNAMELEN + 1);
1197 	bcopy(ki->ki_loginclass, ki32->ki_loginclass, LOGINCLASSLEN + 1);
1198 	CP(*ki, *ki32, ki_tracer);
1199 	CP(*ki, *ki32, ki_flag2);
1200 	CP(*ki, *ki32, ki_fibnum);
1201 	CP(*ki, *ki32, ki_cr_flags);
1202 	CP(*ki, *ki32, ki_jid);
1203 	CP(*ki, *ki32, ki_numthreads);
1204 	CP(*ki, *ki32, ki_tid);
1205 	CP(*ki, *ki32, ki_pri);
1206 	freebsd32_rusage_out(&ki->ki_rusage, &ki32->ki_rusage);
1207 	freebsd32_rusage_out(&ki->ki_rusage_ch, &ki32->ki_rusage_ch);
1208 	PTRTRIM_CP(*ki, *ki32, ki_pcb);
1209 	PTRTRIM_CP(*ki, *ki32, ki_kstack);
1210 	PTRTRIM_CP(*ki, *ki32, ki_udata);
1211 	CP(*ki, *ki32, ki_sflag);
1212 	CP(*ki, *ki32, ki_tdflags);
1213 }
1214 #endif
1215 
1216 int
1217 kern_proc_out(struct proc *p, struct sbuf *sb, int flags)
1218 {
1219 	struct thread *td;
1220 	struct kinfo_proc ki;
1221 #ifdef COMPAT_FREEBSD32
1222 	struct kinfo_proc32 ki32;
1223 #endif
1224 	int error;
1225 
1226 	PROC_LOCK_ASSERT(p, MA_OWNED);
1227 	MPASS(FIRST_THREAD_IN_PROC(p) != NULL);
1228 
1229 	error = 0;
1230 	fill_kinfo_proc(p, &ki);
1231 	if ((flags & KERN_PROC_NOTHREADS) != 0) {
1232 #ifdef COMPAT_FREEBSD32
1233 		if ((flags & KERN_PROC_MASK32) != 0) {
1234 			freebsd32_kinfo_proc_out(&ki, &ki32);
1235 			if (sbuf_bcat(sb, &ki32, sizeof(ki32)) != 0)
1236 				error = ENOMEM;
1237 		} else
1238 #endif
1239 			if (sbuf_bcat(sb, &ki, sizeof(ki)) != 0)
1240 				error = ENOMEM;
1241 	} else {
1242 		FOREACH_THREAD_IN_PROC(p, td) {
1243 			fill_kinfo_thread(td, &ki, 1);
1244 #ifdef COMPAT_FREEBSD32
1245 			if ((flags & KERN_PROC_MASK32) != 0) {
1246 				freebsd32_kinfo_proc_out(&ki, &ki32);
1247 				if (sbuf_bcat(sb, &ki32, sizeof(ki32)) != 0)
1248 					error = ENOMEM;
1249 			} else
1250 #endif
1251 				if (sbuf_bcat(sb, &ki, sizeof(ki)) != 0)
1252 					error = ENOMEM;
1253 			if (error != 0)
1254 				break;
1255 		}
1256 	}
1257 	PROC_UNLOCK(p);
1258 	return (error);
1259 }
1260 
1261 static int
1262 sysctl_out_proc(struct proc *p, struct sysctl_req *req, int flags,
1263     int doingzomb)
1264 {
1265 	struct sbuf sb;
1266 	struct kinfo_proc ki;
1267 	struct proc *np;
1268 	int error, error2;
1269 	pid_t pid;
1270 
1271 	pid = p->p_pid;
1272 	sbuf_new_for_sysctl(&sb, (char *)&ki, sizeof(ki), req);
1273 	error = kern_proc_out(p, &sb, flags);
1274 	error2 = sbuf_finish(&sb);
1275 	sbuf_delete(&sb);
1276 	if (error != 0)
1277 		return (error);
1278 	else if (error2 != 0)
1279 		return (error2);
1280 	if (doingzomb)
1281 		np = zpfind(pid);
1282 	else {
1283 		if (pid == 0)
1284 			return (0);
1285 		np = pfind(pid);
1286 	}
1287 	if (np == NULL)
1288 		return (ESRCH);
1289 	if (np != p) {
1290 		PROC_UNLOCK(np);
1291 		return (ESRCH);
1292 	}
1293 	PROC_UNLOCK(np);
1294 	return (0);
1295 }
1296 
1297 static int
1298 sysctl_kern_proc(SYSCTL_HANDLER_ARGS)
1299 {
1300 	int *name = (int *)arg1;
1301 	u_int namelen = arg2;
1302 	struct proc *p;
1303 	int flags, doingzomb, oid_number;
1304 	int error = 0;
1305 
1306 	oid_number = oidp->oid_number;
1307 	if (oid_number != KERN_PROC_ALL &&
1308 	    (oid_number & KERN_PROC_INC_THREAD) == 0)
1309 		flags = KERN_PROC_NOTHREADS;
1310 	else {
1311 		flags = 0;
1312 		oid_number &= ~KERN_PROC_INC_THREAD;
1313 	}
1314 #ifdef COMPAT_FREEBSD32
1315 	if (req->flags & SCTL_MASK32)
1316 		flags |= KERN_PROC_MASK32;
1317 #endif
1318 	if (oid_number == KERN_PROC_PID) {
1319 		if (namelen != 1)
1320 			return (EINVAL);
1321 		error = sysctl_wire_old_buffer(req, 0);
1322 		if (error)
1323 			return (error);
1324 		sx_slock(&proctree_lock);
1325 		error = pget((pid_t)name[0], PGET_CANSEE, &p);
1326 		if (error == 0)
1327 			error = sysctl_out_proc(p, req, flags, 0);
1328 		sx_sunlock(&proctree_lock);
1329 		return (error);
1330 	}
1331 
1332 	switch (oid_number) {
1333 	case KERN_PROC_ALL:
1334 		if (namelen != 0)
1335 			return (EINVAL);
1336 		break;
1337 	case KERN_PROC_PROC:
1338 		if (namelen != 0 && namelen != 1)
1339 			return (EINVAL);
1340 		break;
1341 	default:
1342 		if (namelen != 1)
1343 			return (EINVAL);
1344 		break;
1345 	}
1346 
1347 	if (!req->oldptr) {
1348 		/* overestimate by 5 procs */
1349 		error = SYSCTL_OUT(req, 0, sizeof (struct kinfo_proc) * 5);
1350 		if (error)
1351 			return (error);
1352 	}
1353 	error = sysctl_wire_old_buffer(req, 0);
1354 	if (error != 0)
1355 		return (error);
1356 	sx_slock(&proctree_lock);
1357 	sx_slock(&allproc_lock);
1358 	for (doingzomb=0 ; doingzomb < 2 ; doingzomb++) {
1359 		if (!doingzomb)
1360 			p = LIST_FIRST(&allproc);
1361 		else
1362 			p = LIST_FIRST(&zombproc);
1363 		for (; p != 0; p = LIST_NEXT(p, p_list)) {
1364 			/*
1365 			 * Skip embryonic processes.
1366 			 */
1367 			PROC_LOCK(p);
1368 			if (p->p_state == PRS_NEW) {
1369 				PROC_UNLOCK(p);
1370 				continue;
1371 			}
1372 			KASSERT(p->p_ucred != NULL,
1373 			    ("process credential is NULL for non-NEW proc"));
1374 			/*
1375 			 * Show a user only appropriate processes.
1376 			 */
1377 			if (p_cansee(curthread, p)) {
1378 				PROC_UNLOCK(p);
1379 				continue;
1380 			}
1381 			/*
1382 			 * TODO - make more efficient (see notes below).
1383 			 * do by session.
1384 			 */
1385 			switch (oid_number) {
1386 
1387 			case KERN_PROC_GID:
1388 				if (p->p_ucred->cr_gid != (gid_t)name[0]) {
1389 					PROC_UNLOCK(p);
1390 					continue;
1391 				}
1392 				break;
1393 
1394 			case KERN_PROC_PGRP:
1395 				/* could do this by traversing pgrp */
1396 				if (p->p_pgrp == NULL ||
1397 				    p->p_pgrp->pg_id != (pid_t)name[0]) {
1398 					PROC_UNLOCK(p);
1399 					continue;
1400 				}
1401 				break;
1402 
1403 			case KERN_PROC_RGID:
1404 				if (p->p_ucred->cr_rgid != (gid_t)name[0]) {
1405 					PROC_UNLOCK(p);
1406 					continue;
1407 				}
1408 				break;
1409 
1410 			case KERN_PROC_SESSION:
1411 				if (p->p_session == NULL ||
1412 				    p->p_session->s_sid != (pid_t)name[0]) {
1413 					PROC_UNLOCK(p);
1414 					continue;
1415 				}
1416 				break;
1417 
1418 			case KERN_PROC_TTY:
1419 				if ((p->p_flag & P_CONTROLT) == 0 ||
1420 				    p->p_session == NULL) {
1421 					PROC_UNLOCK(p);
1422 					continue;
1423 				}
1424 				/* XXX proctree_lock */
1425 				SESS_LOCK(p->p_session);
1426 				if (p->p_session->s_ttyp == NULL ||
1427 				    tty_udev(p->p_session->s_ttyp) !=
1428 				    (dev_t)name[0]) {
1429 					SESS_UNLOCK(p->p_session);
1430 					PROC_UNLOCK(p);
1431 					continue;
1432 				}
1433 				SESS_UNLOCK(p->p_session);
1434 				break;
1435 
1436 			case KERN_PROC_UID:
1437 				if (p->p_ucred->cr_uid != (uid_t)name[0]) {
1438 					PROC_UNLOCK(p);
1439 					continue;
1440 				}
1441 				break;
1442 
1443 			case KERN_PROC_RUID:
1444 				if (p->p_ucred->cr_ruid != (uid_t)name[0]) {
1445 					PROC_UNLOCK(p);
1446 					continue;
1447 				}
1448 				break;
1449 
1450 			case KERN_PROC_PROC:
1451 				break;
1452 
1453 			default:
1454 				break;
1455 
1456 			}
1457 
1458 			error = sysctl_out_proc(p, req, flags, doingzomb);
1459 			if (error) {
1460 				sx_sunlock(&allproc_lock);
1461 				sx_sunlock(&proctree_lock);
1462 				return (error);
1463 			}
1464 		}
1465 	}
1466 	sx_sunlock(&allproc_lock);
1467 	sx_sunlock(&proctree_lock);
1468 	return (0);
1469 }
1470 
1471 struct pargs *
1472 pargs_alloc(int len)
1473 {
1474 	struct pargs *pa;
1475 
1476 	pa = malloc(sizeof(struct pargs) + len, M_PARGS,
1477 		M_WAITOK);
1478 	refcount_init(&pa->ar_ref, 1);
1479 	pa->ar_length = len;
1480 	return (pa);
1481 }
1482 
1483 static void
1484 pargs_free(struct pargs *pa)
1485 {
1486 
1487 	free(pa, M_PARGS);
1488 }
1489 
1490 void
1491 pargs_hold(struct pargs *pa)
1492 {
1493 
1494 	if (pa == NULL)
1495 		return;
1496 	refcount_acquire(&pa->ar_ref);
1497 }
1498 
1499 void
1500 pargs_drop(struct pargs *pa)
1501 {
1502 
1503 	if (pa == NULL)
1504 		return;
1505 	if (refcount_release(&pa->ar_ref))
1506 		pargs_free(pa);
1507 }
1508 
1509 static int
1510 proc_read_mem(struct thread *td, struct proc *p, vm_offset_t offset, void* buf,
1511     size_t len)
1512 {
1513 	struct iovec iov;
1514 	struct uio uio;
1515 
1516 	iov.iov_base = (caddr_t)buf;
1517 	iov.iov_len = len;
1518 	uio.uio_iov = &iov;
1519 	uio.uio_iovcnt = 1;
1520 	uio.uio_offset = offset;
1521 	uio.uio_resid = (ssize_t)len;
1522 	uio.uio_segflg = UIO_SYSSPACE;
1523 	uio.uio_rw = UIO_READ;
1524 	uio.uio_td = td;
1525 
1526 	return (proc_rwmem(p, &uio));
1527 }
1528 
1529 static int
1530 proc_read_string(struct thread *td, struct proc *p, const char *sptr, char *buf,
1531     size_t len)
1532 {
1533 	size_t i;
1534 	int error;
1535 
1536 	error = proc_read_mem(td, p, (vm_offset_t)sptr, buf, len);
1537 	/*
1538 	 * Reading the chunk may validly return EFAULT if the string is shorter
1539 	 * than the chunk and is aligned at the end of the page, assuming the
1540 	 * next page is not mapped.  So if EFAULT is returned do a fallback to
1541 	 * one byte read loop.
1542 	 */
1543 	if (error == EFAULT) {
1544 		for (i = 0; i < len; i++, buf++, sptr++) {
1545 			error = proc_read_mem(td, p, (vm_offset_t)sptr, buf, 1);
1546 			if (error != 0)
1547 				return (error);
1548 			if (*buf == '\0')
1549 				break;
1550 		}
1551 		error = 0;
1552 	}
1553 	return (error);
1554 }
1555 
1556 #define PROC_AUXV_MAX	256	/* Safety limit on auxv size. */
1557 
1558 enum proc_vector_type {
1559 	PROC_ARG,
1560 	PROC_ENV,
1561 	PROC_AUX,
1562 };
1563 
1564 #ifdef COMPAT_FREEBSD32
1565 static int
1566 get_proc_vector32(struct thread *td, struct proc *p, char ***proc_vectorp,
1567     size_t *vsizep, enum proc_vector_type type)
1568 {
1569 	struct freebsd32_ps_strings pss;
1570 	Elf32_Auxinfo aux;
1571 	vm_offset_t vptr, ptr;
1572 	uint32_t *proc_vector32;
1573 	char **proc_vector;
1574 	size_t vsize, size;
1575 	int i, error;
1576 
1577 	error = proc_read_mem(td, p, (vm_offset_t)(p->p_sysent->sv_psstrings),
1578 	    &pss, sizeof(pss));
1579 	if (error != 0)
1580 		return (error);
1581 	switch (type) {
1582 	case PROC_ARG:
1583 		vptr = (vm_offset_t)PTRIN(pss.ps_argvstr);
1584 		vsize = pss.ps_nargvstr;
1585 		if (vsize > ARG_MAX)
1586 			return (ENOEXEC);
1587 		size = vsize * sizeof(int32_t);
1588 		break;
1589 	case PROC_ENV:
1590 		vptr = (vm_offset_t)PTRIN(pss.ps_envstr);
1591 		vsize = pss.ps_nenvstr;
1592 		if (vsize > ARG_MAX)
1593 			return (ENOEXEC);
1594 		size = vsize * sizeof(int32_t);
1595 		break;
1596 	case PROC_AUX:
1597 		vptr = (vm_offset_t)PTRIN(pss.ps_envstr) +
1598 		    (pss.ps_nenvstr + 1) * sizeof(int32_t);
1599 		if (vptr % 4 != 0)
1600 			return (ENOEXEC);
1601 		for (ptr = vptr, i = 0; i < PROC_AUXV_MAX; i++) {
1602 			error = proc_read_mem(td, p, ptr, &aux, sizeof(aux));
1603 			if (error != 0)
1604 				return (error);
1605 			if (aux.a_type == AT_NULL)
1606 				break;
1607 			ptr += sizeof(aux);
1608 		}
1609 		if (aux.a_type != AT_NULL)
1610 			return (ENOEXEC);
1611 		vsize = i + 1;
1612 		size = vsize * sizeof(aux);
1613 		break;
1614 	default:
1615 		KASSERT(0, ("Wrong proc vector type: %d", type));
1616 		return (EINVAL);
1617 	}
1618 	proc_vector32 = malloc(size, M_TEMP, M_WAITOK);
1619 	error = proc_read_mem(td, p, vptr, proc_vector32, size);
1620 	if (error != 0)
1621 		goto done;
1622 	if (type == PROC_AUX) {
1623 		*proc_vectorp = (char **)proc_vector32;
1624 		*vsizep = vsize;
1625 		return (0);
1626 	}
1627 	proc_vector = malloc(vsize * sizeof(char *), M_TEMP, M_WAITOK);
1628 	for (i = 0; i < (int)vsize; i++)
1629 		proc_vector[i] = PTRIN(proc_vector32[i]);
1630 	*proc_vectorp = proc_vector;
1631 	*vsizep = vsize;
1632 done:
1633 	free(proc_vector32, M_TEMP);
1634 	return (error);
1635 }
1636 #endif
1637 
1638 static int
1639 get_proc_vector(struct thread *td, struct proc *p, char ***proc_vectorp,
1640     size_t *vsizep, enum proc_vector_type type)
1641 {
1642 	struct ps_strings pss;
1643 	Elf_Auxinfo aux;
1644 	vm_offset_t vptr, ptr;
1645 	char **proc_vector;
1646 	size_t vsize, size;
1647 	int error, i;
1648 
1649 #ifdef COMPAT_FREEBSD32
1650 	if (SV_PROC_FLAG(p, SV_ILP32) != 0)
1651 		return (get_proc_vector32(td, p, proc_vectorp, vsizep, type));
1652 #endif
1653 	error = proc_read_mem(td, p, (vm_offset_t)(p->p_sysent->sv_psstrings),
1654 	    &pss, sizeof(pss));
1655 	if (error != 0)
1656 		return (error);
1657 	switch (type) {
1658 	case PROC_ARG:
1659 		vptr = (vm_offset_t)pss.ps_argvstr;
1660 		vsize = pss.ps_nargvstr;
1661 		if (vsize > ARG_MAX)
1662 			return (ENOEXEC);
1663 		size = vsize * sizeof(char *);
1664 		break;
1665 	case PROC_ENV:
1666 		vptr = (vm_offset_t)pss.ps_envstr;
1667 		vsize = pss.ps_nenvstr;
1668 		if (vsize > ARG_MAX)
1669 			return (ENOEXEC);
1670 		size = vsize * sizeof(char *);
1671 		break;
1672 	case PROC_AUX:
1673 		/*
1674 		 * The aux array is just above env array on the stack. Check
1675 		 * that the address is naturally aligned.
1676 		 */
1677 		vptr = (vm_offset_t)pss.ps_envstr + (pss.ps_nenvstr + 1)
1678 		    * sizeof(char *);
1679 #if __ELF_WORD_SIZE == 64
1680 		if (vptr % sizeof(uint64_t) != 0)
1681 #else
1682 		if (vptr % sizeof(uint32_t) != 0)
1683 #endif
1684 			return (ENOEXEC);
1685 		/*
1686 		 * We count the array size reading the aux vectors from the
1687 		 * stack until AT_NULL vector is returned.  So (to keep the code
1688 		 * simple) we read the process stack twice: the first time here
1689 		 * to find the size and the second time when copying the vectors
1690 		 * to the allocated proc_vector.
1691 		 */
1692 		for (ptr = vptr, i = 0; i < PROC_AUXV_MAX; i++) {
1693 			error = proc_read_mem(td, p, ptr, &aux, sizeof(aux));
1694 			if (error != 0)
1695 				return (error);
1696 			if (aux.a_type == AT_NULL)
1697 				break;
1698 			ptr += sizeof(aux);
1699 		}
1700 		/*
1701 		 * If the PROC_AUXV_MAX entries are iterated over, and we have
1702 		 * not reached AT_NULL, it is most likely we are reading wrong
1703 		 * data: either the process doesn't have auxv array or data has
1704 		 * been modified. Return the error in this case.
1705 		 */
1706 		if (aux.a_type != AT_NULL)
1707 			return (ENOEXEC);
1708 		vsize = i + 1;
1709 		size = vsize * sizeof(aux);
1710 		break;
1711 	default:
1712 		KASSERT(0, ("Wrong proc vector type: %d", type));
1713 		return (EINVAL); /* In case we are built without INVARIANTS. */
1714 	}
1715 	proc_vector = malloc(size, M_TEMP, M_WAITOK);
1716 	if (proc_vector == NULL)
1717 		return (ENOMEM);
1718 	error = proc_read_mem(td, p, vptr, proc_vector, size);
1719 	if (error != 0) {
1720 		free(proc_vector, M_TEMP);
1721 		return (error);
1722 	}
1723 	*proc_vectorp = proc_vector;
1724 	*vsizep = vsize;
1725 
1726 	return (0);
1727 }
1728 
1729 #define GET_PS_STRINGS_CHUNK_SZ	256	/* Chunk size (bytes) for ps_strings operations. */
1730 
1731 static int
1732 get_ps_strings(struct thread *td, struct proc *p, struct sbuf *sb,
1733     enum proc_vector_type type)
1734 {
1735 	size_t done, len, nchr, vsize;
1736 	int error, i;
1737 	char **proc_vector, *sptr;
1738 	char pss_string[GET_PS_STRINGS_CHUNK_SZ];
1739 
1740 	PROC_ASSERT_HELD(p);
1741 
1742 	/*
1743 	 * We are not going to read more than 2 * (PATH_MAX + ARG_MAX) bytes.
1744 	 */
1745 	nchr = 2 * (PATH_MAX + ARG_MAX);
1746 
1747 	error = get_proc_vector(td, p, &proc_vector, &vsize, type);
1748 	if (error != 0)
1749 		return (error);
1750 	for (done = 0, i = 0; i < (int)vsize && done < nchr; i++) {
1751 		/*
1752 		 * The program may have scribbled into its argv array, e.g. to
1753 		 * remove some arguments.  If that has happened, break out
1754 		 * before trying to read from NULL.
1755 		 */
1756 		if (proc_vector[i] == NULL)
1757 			break;
1758 		for (sptr = proc_vector[i]; ; sptr += GET_PS_STRINGS_CHUNK_SZ) {
1759 			error = proc_read_string(td, p, sptr, pss_string,
1760 			    sizeof(pss_string));
1761 			if (error != 0)
1762 				goto done;
1763 			len = strnlen(pss_string, GET_PS_STRINGS_CHUNK_SZ);
1764 			if (done + len >= nchr)
1765 				len = nchr - done - 1;
1766 			sbuf_bcat(sb, pss_string, len);
1767 			if (len != GET_PS_STRINGS_CHUNK_SZ)
1768 				break;
1769 			done += GET_PS_STRINGS_CHUNK_SZ;
1770 		}
1771 		sbuf_bcat(sb, "", 1);
1772 		done += len + 1;
1773 	}
1774 done:
1775 	free(proc_vector, M_TEMP);
1776 	return (error);
1777 }
1778 
1779 int
1780 proc_getargv(struct thread *td, struct proc *p, struct sbuf *sb)
1781 {
1782 
1783 	return (get_ps_strings(curthread, p, sb, PROC_ARG));
1784 }
1785 
1786 int
1787 proc_getenvv(struct thread *td, struct proc *p, struct sbuf *sb)
1788 {
1789 
1790 	return (get_ps_strings(curthread, p, sb, PROC_ENV));
1791 }
1792 
1793 int
1794 proc_getauxv(struct thread *td, struct proc *p, struct sbuf *sb)
1795 {
1796 	size_t vsize, size;
1797 	char **auxv;
1798 	int error;
1799 
1800 	error = get_proc_vector(td, p, &auxv, &vsize, PROC_AUX);
1801 	if (error == 0) {
1802 #ifdef COMPAT_FREEBSD32
1803 		if (SV_PROC_FLAG(p, SV_ILP32) != 0)
1804 			size = vsize * sizeof(Elf32_Auxinfo);
1805 		else
1806 #endif
1807 			size = vsize * sizeof(Elf_Auxinfo);
1808 		if (sbuf_bcat(sb, auxv, size) != 0)
1809 			error = ENOMEM;
1810 		free(auxv, M_TEMP);
1811 	}
1812 	return (error);
1813 }
1814 
1815 /*
1816  * This sysctl allows a process to retrieve the argument list or process
1817  * title for another process without groping around in the address space
1818  * of the other process.  It also allow a process to set its own "process
1819  * title to a string of its own choice.
1820  */
1821 static int
1822 sysctl_kern_proc_args(SYSCTL_HANDLER_ARGS)
1823 {
1824 	int *name = (int *)arg1;
1825 	u_int namelen = arg2;
1826 	struct pargs *newpa, *pa;
1827 	struct proc *p;
1828 	struct sbuf sb;
1829 	int flags, error = 0, error2;
1830 
1831 	if (namelen != 1)
1832 		return (EINVAL);
1833 
1834 	flags = PGET_CANSEE;
1835 	if (req->newptr != NULL)
1836 		flags |= PGET_ISCURRENT;
1837 	error = pget((pid_t)name[0], flags, &p);
1838 	if (error)
1839 		return (error);
1840 
1841 	pa = p->p_args;
1842 	if (pa != NULL) {
1843 		pargs_hold(pa);
1844 		PROC_UNLOCK(p);
1845 		error = SYSCTL_OUT(req, pa->ar_args, pa->ar_length);
1846 		pargs_drop(pa);
1847 	} else if ((p->p_flag & (P_WEXIT | P_SYSTEM)) == 0) {
1848 		_PHOLD(p);
1849 		PROC_UNLOCK(p);
1850 		sbuf_new_for_sysctl(&sb, NULL, GET_PS_STRINGS_CHUNK_SZ, req);
1851 		error = proc_getargv(curthread, p, &sb);
1852 		error2 = sbuf_finish(&sb);
1853 		PRELE(p);
1854 		sbuf_delete(&sb);
1855 		if (error == 0 && error2 != 0)
1856 			error = error2;
1857 	} else {
1858 		PROC_UNLOCK(p);
1859 	}
1860 	if (error != 0 || req->newptr == NULL)
1861 		return (error);
1862 
1863 	if (req->newlen + sizeof(struct pargs) > ps_arg_cache_limit)
1864 		return (ENOMEM);
1865 	newpa = pargs_alloc(req->newlen);
1866 	error = SYSCTL_IN(req, newpa->ar_args, req->newlen);
1867 	if (error != 0) {
1868 		pargs_free(newpa);
1869 		return (error);
1870 	}
1871 	PROC_LOCK(p);
1872 	pa = p->p_args;
1873 	p->p_args = newpa;
1874 	PROC_UNLOCK(p);
1875 	pargs_drop(pa);
1876 	return (0);
1877 }
1878 
1879 /*
1880  * This sysctl allows a process to retrieve environment of another process.
1881  */
1882 static int
1883 sysctl_kern_proc_env(SYSCTL_HANDLER_ARGS)
1884 {
1885 	int *name = (int *)arg1;
1886 	u_int namelen = arg2;
1887 	struct proc *p;
1888 	struct sbuf sb;
1889 	int error, error2;
1890 
1891 	if (namelen != 1)
1892 		return (EINVAL);
1893 
1894 	error = pget((pid_t)name[0], PGET_WANTREAD, &p);
1895 	if (error != 0)
1896 		return (error);
1897 	if ((p->p_flag & P_SYSTEM) != 0) {
1898 		PRELE(p);
1899 		return (0);
1900 	}
1901 
1902 	sbuf_new_for_sysctl(&sb, NULL, GET_PS_STRINGS_CHUNK_SZ, req);
1903 	error = proc_getenvv(curthread, p, &sb);
1904 	error2 = sbuf_finish(&sb);
1905 	PRELE(p);
1906 	sbuf_delete(&sb);
1907 	return (error != 0 ? error : error2);
1908 }
1909 
1910 /*
1911  * This sysctl allows a process to retrieve ELF auxiliary vector of
1912  * another process.
1913  */
1914 static int
1915 sysctl_kern_proc_auxv(SYSCTL_HANDLER_ARGS)
1916 {
1917 	int *name = (int *)arg1;
1918 	u_int namelen = arg2;
1919 	struct proc *p;
1920 	struct sbuf sb;
1921 	int error, error2;
1922 
1923 	if (namelen != 1)
1924 		return (EINVAL);
1925 
1926 	error = pget((pid_t)name[0], PGET_WANTREAD, &p);
1927 	if (error != 0)
1928 		return (error);
1929 	if ((p->p_flag & P_SYSTEM) != 0) {
1930 		PRELE(p);
1931 		return (0);
1932 	}
1933 	sbuf_new_for_sysctl(&sb, NULL, GET_PS_STRINGS_CHUNK_SZ, req);
1934 	error = proc_getauxv(curthread, p, &sb);
1935 	error2 = sbuf_finish(&sb);
1936 	PRELE(p);
1937 	sbuf_delete(&sb);
1938 	return (error != 0 ? error : error2);
1939 }
1940 
1941 /*
1942  * This sysctl allows a process to retrieve the path of the executable for
1943  * itself or another process.
1944  */
1945 static int
1946 sysctl_kern_proc_pathname(SYSCTL_HANDLER_ARGS)
1947 {
1948 	pid_t *pidp = (pid_t *)arg1;
1949 	unsigned int arglen = arg2;
1950 	struct proc *p;
1951 	struct vnode *vp;
1952 	char *retbuf, *freebuf;
1953 	int error;
1954 
1955 	if (arglen != 1)
1956 		return (EINVAL);
1957 	if (*pidp == -1) {	/* -1 means this process */
1958 		p = req->td->td_proc;
1959 	} else {
1960 		error = pget(*pidp, PGET_CANSEE, &p);
1961 		if (error != 0)
1962 			return (error);
1963 	}
1964 
1965 	vp = p->p_textvp;
1966 	if (vp == NULL) {
1967 		if (*pidp != -1)
1968 			PROC_UNLOCK(p);
1969 		return (0);
1970 	}
1971 	vref(vp);
1972 	if (*pidp != -1)
1973 		PROC_UNLOCK(p);
1974 	error = vn_fullpath(req->td, vp, &retbuf, &freebuf);
1975 	vrele(vp);
1976 	if (error)
1977 		return (error);
1978 	error = SYSCTL_OUT(req, retbuf, strlen(retbuf) + 1);
1979 	free(freebuf, M_TEMP);
1980 	return (error);
1981 }
1982 
1983 static int
1984 sysctl_kern_proc_sv_name(SYSCTL_HANDLER_ARGS)
1985 {
1986 	struct proc *p;
1987 	char *sv_name;
1988 	int *name;
1989 	int namelen;
1990 	int error;
1991 
1992 	namelen = arg2;
1993 	if (namelen != 1)
1994 		return (EINVAL);
1995 
1996 	name = (int *)arg1;
1997 	error = pget((pid_t)name[0], PGET_CANSEE, &p);
1998 	if (error != 0)
1999 		return (error);
2000 	sv_name = p->p_sysent->sv_name;
2001 	PROC_UNLOCK(p);
2002 	return (sysctl_handle_string(oidp, sv_name, 0, req));
2003 }
2004 
2005 #ifdef KINFO_OVMENTRY_SIZE
2006 CTASSERT(sizeof(struct kinfo_ovmentry) == KINFO_OVMENTRY_SIZE);
2007 #endif
2008 
2009 #ifdef COMPAT_FREEBSD7
2010 static int
2011 sysctl_kern_proc_ovmmap(SYSCTL_HANDLER_ARGS)
2012 {
2013 	vm_map_entry_t entry, tmp_entry;
2014 	unsigned int last_timestamp;
2015 	char *fullpath, *freepath;
2016 	struct kinfo_ovmentry *kve;
2017 	struct vattr va;
2018 	struct ucred *cred;
2019 	int error, *name;
2020 	struct vnode *vp;
2021 	struct proc *p;
2022 	vm_map_t map;
2023 	struct vmspace *vm;
2024 
2025 	name = (int *)arg1;
2026 	error = pget((pid_t)name[0], PGET_WANTREAD, &p);
2027 	if (error != 0)
2028 		return (error);
2029 	vm = vmspace_acquire_ref(p);
2030 	if (vm == NULL) {
2031 		PRELE(p);
2032 		return (ESRCH);
2033 	}
2034 	kve = malloc(sizeof(*kve), M_TEMP, M_WAITOK);
2035 
2036 	map = &vm->vm_map;
2037 	vm_map_lock_read(map);
2038 	for (entry = map->header.next; entry != &map->header;
2039 	    entry = entry->next) {
2040 		vm_object_t obj, tobj, lobj;
2041 		vm_offset_t addr;
2042 
2043 		if (entry->eflags & MAP_ENTRY_IS_SUB_MAP)
2044 			continue;
2045 
2046 		bzero(kve, sizeof(*kve));
2047 		kve->kve_structsize = sizeof(*kve);
2048 
2049 		kve->kve_private_resident = 0;
2050 		obj = entry->object.vm_object;
2051 		if (obj != NULL) {
2052 			VM_OBJECT_RLOCK(obj);
2053 			if (obj->shadow_count == 1)
2054 				kve->kve_private_resident =
2055 				    obj->resident_page_count;
2056 		}
2057 		kve->kve_resident = 0;
2058 		addr = entry->start;
2059 		while (addr < entry->end) {
2060 			if (pmap_extract(map->pmap, addr))
2061 				kve->kve_resident++;
2062 			addr += PAGE_SIZE;
2063 		}
2064 
2065 		for (lobj = tobj = obj; tobj; tobj = tobj->backing_object) {
2066 			if (tobj != obj)
2067 				VM_OBJECT_RLOCK(tobj);
2068 			if (lobj != obj)
2069 				VM_OBJECT_RUNLOCK(lobj);
2070 			lobj = tobj;
2071 		}
2072 
2073 		kve->kve_start = (void*)entry->start;
2074 		kve->kve_end = (void*)entry->end;
2075 		kve->kve_offset = (off_t)entry->offset;
2076 
2077 		if (entry->protection & VM_PROT_READ)
2078 			kve->kve_protection |= KVME_PROT_READ;
2079 		if (entry->protection & VM_PROT_WRITE)
2080 			kve->kve_protection |= KVME_PROT_WRITE;
2081 		if (entry->protection & VM_PROT_EXECUTE)
2082 			kve->kve_protection |= KVME_PROT_EXEC;
2083 
2084 		if (entry->eflags & MAP_ENTRY_COW)
2085 			kve->kve_flags |= KVME_FLAG_COW;
2086 		if (entry->eflags & MAP_ENTRY_NEEDS_COPY)
2087 			kve->kve_flags |= KVME_FLAG_NEEDS_COPY;
2088 		if (entry->eflags & MAP_ENTRY_NOCOREDUMP)
2089 			kve->kve_flags |= KVME_FLAG_NOCOREDUMP;
2090 
2091 		last_timestamp = map->timestamp;
2092 		vm_map_unlock_read(map);
2093 
2094 		kve->kve_fileid = 0;
2095 		kve->kve_fsid = 0;
2096 		freepath = NULL;
2097 		fullpath = "";
2098 		if (lobj) {
2099 			vp = NULL;
2100 			switch (lobj->type) {
2101 			case OBJT_DEFAULT:
2102 				kve->kve_type = KVME_TYPE_DEFAULT;
2103 				break;
2104 			case OBJT_VNODE:
2105 				kve->kve_type = KVME_TYPE_VNODE;
2106 				vp = lobj->handle;
2107 				vref(vp);
2108 				break;
2109 			case OBJT_SWAP:
2110 				kve->kve_type = KVME_TYPE_SWAP;
2111 				break;
2112 			case OBJT_DEVICE:
2113 				kve->kve_type = KVME_TYPE_DEVICE;
2114 				break;
2115 			case OBJT_PHYS:
2116 				kve->kve_type = KVME_TYPE_PHYS;
2117 				break;
2118 			case OBJT_DEAD:
2119 				kve->kve_type = KVME_TYPE_DEAD;
2120 				break;
2121 			case OBJT_SG:
2122 				kve->kve_type = KVME_TYPE_SG;
2123 				break;
2124 			default:
2125 				kve->kve_type = KVME_TYPE_UNKNOWN;
2126 				break;
2127 			}
2128 			if (lobj != obj)
2129 				VM_OBJECT_RUNLOCK(lobj);
2130 
2131 			kve->kve_ref_count = obj->ref_count;
2132 			kve->kve_shadow_count = obj->shadow_count;
2133 			VM_OBJECT_RUNLOCK(obj);
2134 			if (vp != NULL) {
2135 				vn_fullpath(curthread, vp, &fullpath,
2136 				    &freepath);
2137 				cred = curthread->td_ucred;
2138 				vn_lock(vp, LK_SHARED | LK_RETRY);
2139 				if (VOP_GETATTR(vp, &va, cred) == 0) {
2140 					kve->kve_fileid = va.va_fileid;
2141 					kve->kve_fsid = va.va_fsid;
2142 				}
2143 				vput(vp);
2144 			}
2145 		} else {
2146 			kve->kve_type = KVME_TYPE_NONE;
2147 			kve->kve_ref_count = 0;
2148 			kve->kve_shadow_count = 0;
2149 		}
2150 
2151 		strlcpy(kve->kve_path, fullpath, sizeof(kve->kve_path));
2152 		if (freepath != NULL)
2153 			free(freepath, M_TEMP);
2154 
2155 		error = SYSCTL_OUT(req, kve, sizeof(*kve));
2156 		vm_map_lock_read(map);
2157 		if (error)
2158 			break;
2159 		if (last_timestamp != map->timestamp) {
2160 			vm_map_lookup_entry(map, addr - 1, &tmp_entry);
2161 			entry = tmp_entry;
2162 		}
2163 	}
2164 	vm_map_unlock_read(map);
2165 	vmspace_free(vm);
2166 	PRELE(p);
2167 	free(kve, M_TEMP);
2168 	return (error);
2169 }
2170 #endif	/* COMPAT_FREEBSD7 */
2171 
2172 #ifdef KINFO_VMENTRY_SIZE
2173 CTASSERT(sizeof(struct kinfo_vmentry) == KINFO_VMENTRY_SIZE);
2174 #endif
2175 
2176 static void
2177 kern_proc_vmmap_resident(vm_map_t map, vm_map_entry_t entry,
2178     struct kinfo_vmentry *kve)
2179 {
2180 	vm_object_t obj, tobj;
2181 	vm_page_t m, m_adv;
2182 	vm_offset_t addr;
2183 	vm_paddr_t locked_pa;
2184 	vm_pindex_t pi, pi_adv, pindex;
2185 
2186 	locked_pa = 0;
2187 	obj = entry->object.vm_object;
2188 	addr = entry->start;
2189 	m_adv = NULL;
2190 	pi = OFF_TO_IDX(entry->offset);
2191 	for (; addr < entry->end; addr += IDX_TO_OFF(pi_adv), pi += pi_adv) {
2192 		if (m_adv != NULL) {
2193 			m = m_adv;
2194 		} else {
2195 			pi_adv = OFF_TO_IDX(entry->end - addr);
2196 			pindex = pi;
2197 			for (tobj = obj;; tobj = tobj->backing_object) {
2198 				m = vm_page_find_least(tobj, pindex);
2199 				if (m != NULL) {
2200 					if (m->pindex == pindex)
2201 						break;
2202 					if (pi_adv > m->pindex - pindex) {
2203 						pi_adv = m->pindex - pindex;
2204 						m_adv = m;
2205 					}
2206 				}
2207 				if (tobj->backing_object == NULL)
2208 					goto next;
2209 				pindex += OFF_TO_IDX(tobj->
2210 				    backing_object_offset);
2211 			}
2212 		}
2213 		m_adv = NULL;
2214 		if (m->psind != 0 && addr + pagesizes[1] <= entry->end &&
2215 		    (addr & (pagesizes[1] - 1)) == 0 &&
2216 		    (pmap_mincore(map->pmap, addr, &locked_pa) &
2217 		    MINCORE_SUPER) != 0) {
2218 			kve->kve_flags |= KVME_FLAG_SUPER;
2219 			pi_adv = OFF_TO_IDX(pagesizes[1]);
2220 		} else {
2221 			/*
2222 			 * We do not test the found page on validity.
2223 			 * Either the page is busy and being paged in,
2224 			 * or it was invalidated.  The first case
2225 			 * should be counted as resident, the second
2226 			 * is not so clear; we do account both.
2227 			 */
2228 			pi_adv = 1;
2229 		}
2230 		kve->kve_resident += pi_adv;
2231 next:;
2232 	}
2233 	PA_UNLOCK_COND(locked_pa);
2234 }
2235 
2236 /*
2237  * Must be called with the process locked and will return unlocked.
2238  */
2239 int
2240 kern_proc_vmmap_out(struct proc *p, struct sbuf *sb)
2241 {
2242 	vm_map_entry_t entry, tmp_entry;
2243 	struct vattr va;
2244 	vm_map_t map;
2245 	vm_object_t obj, tobj, lobj;
2246 	char *fullpath, *freepath;
2247 	struct kinfo_vmentry *kve;
2248 	struct ucred *cred;
2249 	struct vnode *vp;
2250 	struct vmspace *vm;
2251 	vm_offset_t addr;
2252 	unsigned int last_timestamp;
2253 	int error;
2254 
2255 	PROC_LOCK_ASSERT(p, MA_OWNED);
2256 
2257 	_PHOLD(p);
2258 	PROC_UNLOCK(p);
2259 	vm = vmspace_acquire_ref(p);
2260 	if (vm == NULL) {
2261 		PRELE(p);
2262 		return (ESRCH);
2263 	}
2264 	kve = malloc(sizeof(*kve), M_TEMP, M_WAITOK);
2265 
2266 	error = 0;
2267 	map = &vm->vm_map;
2268 	vm_map_lock_read(map);
2269 	for (entry = map->header.next; entry != &map->header;
2270 	    entry = entry->next) {
2271 		if (entry->eflags & MAP_ENTRY_IS_SUB_MAP)
2272 			continue;
2273 
2274 		addr = entry->end;
2275 		bzero(kve, sizeof(*kve));
2276 		obj = entry->object.vm_object;
2277 		if (obj != NULL) {
2278 			for (tobj = obj; tobj != NULL;
2279 			    tobj = tobj->backing_object) {
2280 				VM_OBJECT_RLOCK(tobj);
2281 				lobj = tobj;
2282 			}
2283 			if (obj->backing_object == NULL)
2284 				kve->kve_private_resident =
2285 				    obj->resident_page_count;
2286 			if (!vmmap_skip_res_cnt)
2287 				kern_proc_vmmap_resident(map, entry, kve);
2288 			for (tobj = obj; tobj != NULL;
2289 			    tobj = tobj->backing_object) {
2290 				if (tobj != obj && tobj != lobj)
2291 					VM_OBJECT_RUNLOCK(tobj);
2292 			}
2293 		} else {
2294 			lobj = NULL;
2295 		}
2296 
2297 		kve->kve_start = entry->start;
2298 		kve->kve_end = entry->end;
2299 		kve->kve_offset = entry->offset;
2300 
2301 		if (entry->protection & VM_PROT_READ)
2302 			kve->kve_protection |= KVME_PROT_READ;
2303 		if (entry->protection & VM_PROT_WRITE)
2304 			kve->kve_protection |= KVME_PROT_WRITE;
2305 		if (entry->protection & VM_PROT_EXECUTE)
2306 			kve->kve_protection |= KVME_PROT_EXEC;
2307 
2308 		if (entry->eflags & MAP_ENTRY_COW)
2309 			kve->kve_flags |= KVME_FLAG_COW;
2310 		if (entry->eflags & MAP_ENTRY_NEEDS_COPY)
2311 			kve->kve_flags |= KVME_FLAG_NEEDS_COPY;
2312 		if (entry->eflags & MAP_ENTRY_NOCOREDUMP)
2313 			kve->kve_flags |= KVME_FLAG_NOCOREDUMP;
2314 		if (entry->eflags & MAP_ENTRY_GROWS_UP)
2315 			kve->kve_flags |= KVME_FLAG_GROWS_UP;
2316 		if (entry->eflags & MAP_ENTRY_GROWS_DOWN)
2317 			kve->kve_flags |= KVME_FLAG_GROWS_DOWN;
2318 
2319 		last_timestamp = map->timestamp;
2320 		vm_map_unlock_read(map);
2321 
2322 		freepath = NULL;
2323 		fullpath = "";
2324 		if (lobj != NULL) {
2325 			vp = NULL;
2326 			switch (lobj->type) {
2327 			case OBJT_DEFAULT:
2328 				kve->kve_type = KVME_TYPE_DEFAULT;
2329 				break;
2330 			case OBJT_VNODE:
2331 				kve->kve_type = KVME_TYPE_VNODE;
2332 				vp = lobj->handle;
2333 				vref(vp);
2334 				break;
2335 			case OBJT_SWAP:
2336 				kve->kve_type = KVME_TYPE_SWAP;
2337 				break;
2338 			case OBJT_DEVICE:
2339 				kve->kve_type = KVME_TYPE_DEVICE;
2340 				break;
2341 			case OBJT_PHYS:
2342 				kve->kve_type = KVME_TYPE_PHYS;
2343 				break;
2344 			case OBJT_DEAD:
2345 				kve->kve_type = KVME_TYPE_DEAD;
2346 				break;
2347 			case OBJT_SG:
2348 				kve->kve_type = KVME_TYPE_SG;
2349 				break;
2350 			case OBJT_MGTDEVICE:
2351 				kve->kve_type = KVME_TYPE_MGTDEVICE;
2352 				break;
2353 			default:
2354 				kve->kve_type = KVME_TYPE_UNKNOWN;
2355 				break;
2356 			}
2357 			if (lobj != obj)
2358 				VM_OBJECT_RUNLOCK(lobj);
2359 
2360 			kve->kve_ref_count = obj->ref_count;
2361 			kve->kve_shadow_count = obj->shadow_count;
2362 			VM_OBJECT_RUNLOCK(obj);
2363 			if (vp != NULL) {
2364 				vn_fullpath(curthread, vp, &fullpath,
2365 				    &freepath);
2366 				kve->kve_vn_type = vntype_to_kinfo(vp->v_type);
2367 				cred = curthread->td_ucred;
2368 				vn_lock(vp, LK_SHARED | LK_RETRY);
2369 				if (VOP_GETATTR(vp, &va, cred) == 0) {
2370 					kve->kve_vn_fileid = va.va_fileid;
2371 					kve->kve_vn_fsid = va.va_fsid;
2372 					kve->kve_vn_mode =
2373 					    MAKEIMODE(va.va_type, va.va_mode);
2374 					kve->kve_vn_size = va.va_size;
2375 					kve->kve_vn_rdev = va.va_rdev;
2376 					kve->kve_status = KF_ATTR_VALID;
2377 				}
2378 				vput(vp);
2379 			}
2380 		} else {
2381 			kve->kve_type = KVME_TYPE_NONE;
2382 			kve->kve_ref_count = 0;
2383 			kve->kve_shadow_count = 0;
2384 		}
2385 
2386 		strlcpy(kve->kve_path, fullpath, sizeof(kve->kve_path));
2387 		if (freepath != NULL)
2388 			free(freepath, M_TEMP);
2389 
2390 		/* Pack record size down */
2391 		kve->kve_structsize = offsetof(struct kinfo_vmentry, kve_path) +
2392 		    strlen(kve->kve_path) + 1;
2393 		kve->kve_structsize = roundup(kve->kve_structsize,
2394 		    sizeof(uint64_t));
2395 		if (sbuf_bcat(sb, kve, kve->kve_structsize) != 0)
2396 			error = ENOMEM;
2397 		vm_map_lock_read(map);
2398 		if (error != 0)
2399 			break;
2400 		if (last_timestamp != map->timestamp) {
2401 			vm_map_lookup_entry(map, addr - 1, &tmp_entry);
2402 			entry = tmp_entry;
2403 		}
2404 	}
2405 	vm_map_unlock_read(map);
2406 	vmspace_free(vm);
2407 	PRELE(p);
2408 	free(kve, M_TEMP);
2409 	return (error);
2410 }
2411 
2412 static int
2413 sysctl_kern_proc_vmmap(SYSCTL_HANDLER_ARGS)
2414 {
2415 	struct proc *p;
2416 	struct sbuf sb;
2417 	int error, error2, *name;
2418 
2419 	name = (int *)arg1;
2420 	sbuf_new_for_sysctl(&sb, NULL, sizeof(struct kinfo_vmentry), req);
2421 	error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
2422 	if (error != 0) {
2423 		sbuf_delete(&sb);
2424 		return (error);
2425 	}
2426 	error = kern_proc_vmmap_out(p, &sb);
2427 	error2 = sbuf_finish(&sb);
2428 	sbuf_delete(&sb);
2429 	return (error != 0 ? error : error2);
2430 }
2431 
2432 #if defined(STACK) || defined(DDB)
2433 static int
2434 sysctl_kern_proc_kstack(SYSCTL_HANDLER_ARGS)
2435 {
2436 	struct kinfo_kstack *kkstp;
2437 	int error, i, *name, numthreads;
2438 	lwpid_t *lwpidarray;
2439 	struct thread *td;
2440 	struct stack *st;
2441 	struct sbuf sb;
2442 	struct proc *p;
2443 
2444 	name = (int *)arg1;
2445 	error = pget((pid_t)name[0], PGET_NOTINEXEC | PGET_WANTREAD, &p);
2446 	if (error != 0)
2447 		return (error);
2448 
2449 	kkstp = malloc(sizeof(*kkstp), M_TEMP, M_WAITOK);
2450 	st = stack_create();
2451 
2452 	lwpidarray = NULL;
2453 	numthreads = 0;
2454 	PROC_LOCK(p);
2455 repeat:
2456 	if (numthreads < p->p_numthreads) {
2457 		if (lwpidarray != NULL) {
2458 			free(lwpidarray, M_TEMP);
2459 			lwpidarray = NULL;
2460 		}
2461 		numthreads = p->p_numthreads;
2462 		PROC_UNLOCK(p);
2463 		lwpidarray = malloc(sizeof(*lwpidarray) * numthreads, M_TEMP,
2464 		    M_WAITOK | M_ZERO);
2465 		PROC_LOCK(p);
2466 		goto repeat;
2467 	}
2468 	i = 0;
2469 
2470 	/*
2471 	 * XXXRW: During the below loop, execve(2) and countless other sorts
2472 	 * of changes could have taken place.  Should we check to see if the
2473 	 * vmspace has been replaced, or the like, in order to prevent
2474 	 * giving a snapshot that spans, say, execve(2), with some threads
2475 	 * before and some after?  Among other things, the credentials could
2476 	 * have changed, in which case the right to extract debug info might
2477 	 * no longer be assured.
2478 	 */
2479 	FOREACH_THREAD_IN_PROC(p, td) {
2480 		KASSERT(i < numthreads,
2481 		    ("sysctl_kern_proc_kstack: numthreads"));
2482 		lwpidarray[i] = td->td_tid;
2483 		i++;
2484 	}
2485 	numthreads = i;
2486 	for (i = 0; i < numthreads; i++) {
2487 		td = thread_find(p, lwpidarray[i]);
2488 		if (td == NULL) {
2489 			continue;
2490 		}
2491 		bzero(kkstp, sizeof(*kkstp));
2492 		(void)sbuf_new(&sb, kkstp->kkst_trace,
2493 		    sizeof(kkstp->kkst_trace), SBUF_FIXEDLEN);
2494 		thread_lock(td);
2495 		kkstp->kkst_tid = td->td_tid;
2496 		if (TD_IS_SWAPPED(td))
2497 			kkstp->kkst_state = KKST_STATE_SWAPPED;
2498 		else if (TD_IS_RUNNING(td))
2499 			kkstp->kkst_state = KKST_STATE_RUNNING;
2500 		else {
2501 			kkstp->kkst_state = KKST_STATE_STACKOK;
2502 			stack_save_td(st, td);
2503 		}
2504 		thread_unlock(td);
2505 		PROC_UNLOCK(p);
2506 		stack_sbuf_print(&sb, st);
2507 		sbuf_finish(&sb);
2508 		sbuf_delete(&sb);
2509 		error = SYSCTL_OUT(req, kkstp, sizeof(*kkstp));
2510 		PROC_LOCK(p);
2511 		if (error)
2512 			break;
2513 	}
2514 	_PRELE(p);
2515 	PROC_UNLOCK(p);
2516 	if (lwpidarray != NULL)
2517 		free(lwpidarray, M_TEMP);
2518 	stack_destroy(st);
2519 	free(kkstp, M_TEMP);
2520 	return (error);
2521 }
2522 #endif
2523 
2524 /*
2525  * This sysctl allows a process to retrieve the full list of groups from
2526  * itself or another process.
2527  */
2528 static int
2529 sysctl_kern_proc_groups(SYSCTL_HANDLER_ARGS)
2530 {
2531 	pid_t *pidp = (pid_t *)arg1;
2532 	unsigned int arglen = arg2;
2533 	struct proc *p;
2534 	struct ucred *cred;
2535 	int error;
2536 
2537 	if (arglen != 1)
2538 		return (EINVAL);
2539 	if (*pidp == -1) {	/* -1 means this process */
2540 		p = req->td->td_proc;
2541 		PROC_LOCK(p);
2542 	} else {
2543 		error = pget(*pidp, PGET_CANSEE, &p);
2544 		if (error != 0)
2545 			return (error);
2546 	}
2547 
2548 	cred = crhold(p->p_ucred);
2549 	PROC_UNLOCK(p);
2550 
2551 	error = SYSCTL_OUT(req, cred->cr_groups,
2552 	    cred->cr_ngroups * sizeof(gid_t));
2553 	crfree(cred);
2554 	return (error);
2555 }
2556 
2557 /*
2558  * This sysctl allows a process to retrieve or/and set the resource limit for
2559  * another process.
2560  */
2561 static int
2562 sysctl_kern_proc_rlimit(SYSCTL_HANDLER_ARGS)
2563 {
2564 	int *name = (int *)arg1;
2565 	u_int namelen = arg2;
2566 	struct rlimit rlim;
2567 	struct proc *p;
2568 	u_int which;
2569 	int flags, error;
2570 
2571 	if (namelen != 2)
2572 		return (EINVAL);
2573 
2574 	which = (u_int)name[1];
2575 	if (which >= RLIM_NLIMITS)
2576 		return (EINVAL);
2577 
2578 	if (req->newptr != NULL && req->newlen != sizeof(rlim))
2579 		return (EINVAL);
2580 
2581 	flags = PGET_HOLD | PGET_NOTWEXIT;
2582 	if (req->newptr != NULL)
2583 		flags |= PGET_CANDEBUG;
2584 	else
2585 		flags |= PGET_CANSEE;
2586 	error = pget((pid_t)name[0], flags, &p);
2587 	if (error != 0)
2588 		return (error);
2589 
2590 	/*
2591 	 * Retrieve limit.
2592 	 */
2593 	if (req->oldptr != NULL) {
2594 		PROC_LOCK(p);
2595 		lim_rlimit(p, which, &rlim);
2596 		PROC_UNLOCK(p);
2597 	}
2598 	error = SYSCTL_OUT(req, &rlim, sizeof(rlim));
2599 	if (error != 0)
2600 		goto errout;
2601 
2602 	/*
2603 	 * Set limit.
2604 	 */
2605 	if (req->newptr != NULL) {
2606 		error = SYSCTL_IN(req, &rlim, sizeof(rlim));
2607 		if (error == 0)
2608 			error = kern_proc_setrlimit(curthread, p, which, &rlim);
2609 	}
2610 
2611 errout:
2612 	PRELE(p);
2613 	return (error);
2614 }
2615 
2616 /*
2617  * This sysctl allows a process to retrieve ps_strings structure location of
2618  * another process.
2619  */
2620 static int
2621 sysctl_kern_proc_ps_strings(SYSCTL_HANDLER_ARGS)
2622 {
2623 	int *name = (int *)arg1;
2624 	u_int namelen = arg2;
2625 	struct proc *p;
2626 	vm_offset_t ps_strings;
2627 	int error;
2628 #ifdef COMPAT_FREEBSD32
2629 	uint32_t ps_strings32;
2630 #endif
2631 
2632 	if (namelen != 1)
2633 		return (EINVAL);
2634 
2635 	error = pget((pid_t)name[0], PGET_CANDEBUG, &p);
2636 	if (error != 0)
2637 		return (error);
2638 #ifdef COMPAT_FREEBSD32
2639 	if ((req->flags & SCTL_MASK32) != 0) {
2640 		/*
2641 		 * We return 0 if the 32 bit emulation request is for a 64 bit
2642 		 * process.
2643 		 */
2644 		ps_strings32 = SV_PROC_FLAG(p, SV_ILP32) != 0 ?
2645 		    PTROUT(p->p_sysent->sv_psstrings) : 0;
2646 		PROC_UNLOCK(p);
2647 		error = SYSCTL_OUT(req, &ps_strings32, sizeof(ps_strings32));
2648 		return (error);
2649 	}
2650 #endif
2651 	ps_strings = p->p_sysent->sv_psstrings;
2652 	PROC_UNLOCK(p);
2653 	error = SYSCTL_OUT(req, &ps_strings, sizeof(ps_strings));
2654 	return (error);
2655 }
2656 
2657 /*
2658  * This sysctl allows a process to retrieve umask of another process.
2659  */
2660 static int
2661 sysctl_kern_proc_umask(SYSCTL_HANDLER_ARGS)
2662 {
2663 	int *name = (int *)arg1;
2664 	u_int namelen = arg2;
2665 	struct proc *p;
2666 	int error;
2667 	u_short fd_cmask;
2668 
2669 	if (namelen != 1)
2670 		return (EINVAL);
2671 
2672 	error = pget((pid_t)name[0], PGET_WANTREAD, &p);
2673 	if (error != 0)
2674 		return (error);
2675 
2676 	FILEDESC_SLOCK(p->p_fd);
2677 	fd_cmask = p->p_fd->fd_cmask;
2678 	FILEDESC_SUNLOCK(p->p_fd);
2679 	PRELE(p);
2680 	error = SYSCTL_OUT(req, &fd_cmask, sizeof(fd_cmask));
2681 	return (error);
2682 }
2683 
2684 /*
2685  * This sysctl allows a process to set and retrieve binary osreldate of
2686  * another process.
2687  */
2688 static int
2689 sysctl_kern_proc_osrel(SYSCTL_HANDLER_ARGS)
2690 {
2691 	int *name = (int *)arg1;
2692 	u_int namelen = arg2;
2693 	struct proc *p;
2694 	int flags, error, osrel;
2695 
2696 	if (namelen != 1)
2697 		return (EINVAL);
2698 
2699 	if (req->newptr != NULL && req->newlen != sizeof(osrel))
2700 		return (EINVAL);
2701 
2702 	flags = PGET_HOLD | PGET_NOTWEXIT;
2703 	if (req->newptr != NULL)
2704 		flags |= PGET_CANDEBUG;
2705 	else
2706 		flags |= PGET_CANSEE;
2707 	error = pget((pid_t)name[0], flags, &p);
2708 	if (error != 0)
2709 		return (error);
2710 
2711 	error = SYSCTL_OUT(req, &p->p_osrel, sizeof(p->p_osrel));
2712 	if (error != 0)
2713 		goto errout;
2714 
2715 	if (req->newptr != NULL) {
2716 		error = SYSCTL_IN(req, &osrel, sizeof(osrel));
2717 		if (error != 0)
2718 			goto errout;
2719 		if (osrel < 0) {
2720 			error = EINVAL;
2721 			goto errout;
2722 		}
2723 		p->p_osrel = osrel;
2724 	}
2725 errout:
2726 	PRELE(p);
2727 	return (error);
2728 }
2729 
2730 static int
2731 sysctl_kern_proc_sigtramp(SYSCTL_HANDLER_ARGS)
2732 {
2733 	int *name = (int *)arg1;
2734 	u_int namelen = arg2;
2735 	struct proc *p;
2736 	struct kinfo_sigtramp kst;
2737 	const struct sysentvec *sv;
2738 	int error;
2739 #ifdef COMPAT_FREEBSD32
2740 	struct kinfo_sigtramp32 kst32;
2741 #endif
2742 
2743 	if (namelen != 1)
2744 		return (EINVAL);
2745 
2746 	error = pget((pid_t)name[0], PGET_CANDEBUG, &p);
2747 	if (error != 0)
2748 		return (error);
2749 	sv = p->p_sysent;
2750 #ifdef COMPAT_FREEBSD32
2751 	if ((req->flags & SCTL_MASK32) != 0) {
2752 		bzero(&kst32, sizeof(kst32));
2753 		if (SV_PROC_FLAG(p, SV_ILP32)) {
2754 			if (sv->sv_sigcode_base != 0) {
2755 				kst32.ksigtramp_start = sv->sv_sigcode_base;
2756 				kst32.ksigtramp_end = sv->sv_sigcode_base +
2757 				    *sv->sv_szsigcode;
2758 			} else {
2759 				kst32.ksigtramp_start = sv->sv_psstrings -
2760 				    *sv->sv_szsigcode;
2761 				kst32.ksigtramp_end = sv->sv_psstrings;
2762 			}
2763 		}
2764 		PROC_UNLOCK(p);
2765 		error = SYSCTL_OUT(req, &kst32, sizeof(kst32));
2766 		return (error);
2767 	}
2768 #endif
2769 	bzero(&kst, sizeof(kst));
2770 	if (sv->sv_sigcode_base != 0) {
2771 		kst.ksigtramp_start = (char *)sv->sv_sigcode_base;
2772 		kst.ksigtramp_end = (char *)sv->sv_sigcode_base +
2773 		    *sv->sv_szsigcode;
2774 	} else {
2775 		kst.ksigtramp_start = (char *)sv->sv_psstrings -
2776 		    *sv->sv_szsigcode;
2777 		kst.ksigtramp_end = (char *)sv->sv_psstrings;
2778 	}
2779 	PROC_UNLOCK(p);
2780 	error = SYSCTL_OUT(req, &kst, sizeof(kst));
2781 	return (error);
2782 }
2783 
2784 SYSCTL_NODE(_kern, KERN_PROC, proc, CTLFLAG_RD,  0, "Process table");
2785 
2786 SYSCTL_PROC(_kern_proc, KERN_PROC_ALL, all, CTLFLAG_RD|CTLTYPE_STRUCT|
2787 	CTLFLAG_MPSAFE, 0, 0, sysctl_kern_proc, "S,proc",
2788 	"Return entire process table");
2789 
2790 static SYSCTL_NODE(_kern_proc, KERN_PROC_GID, gid, CTLFLAG_RD | CTLFLAG_MPSAFE,
2791 	sysctl_kern_proc, "Process table");
2792 
2793 static SYSCTL_NODE(_kern_proc, KERN_PROC_PGRP, pgrp, CTLFLAG_RD | CTLFLAG_MPSAFE,
2794 	sysctl_kern_proc, "Process table");
2795 
2796 static SYSCTL_NODE(_kern_proc, KERN_PROC_RGID, rgid, CTLFLAG_RD | CTLFLAG_MPSAFE,
2797 	sysctl_kern_proc, "Process table");
2798 
2799 static SYSCTL_NODE(_kern_proc, KERN_PROC_SESSION, sid, CTLFLAG_RD |
2800 	CTLFLAG_MPSAFE, sysctl_kern_proc, "Process table");
2801 
2802 static SYSCTL_NODE(_kern_proc, KERN_PROC_TTY, tty, CTLFLAG_RD | CTLFLAG_MPSAFE,
2803 	sysctl_kern_proc, "Process table");
2804 
2805 static SYSCTL_NODE(_kern_proc, KERN_PROC_UID, uid, CTLFLAG_RD | CTLFLAG_MPSAFE,
2806 	sysctl_kern_proc, "Process table");
2807 
2808 static SYSCTL_NODE(_kern_proc, KERN_PROC_RUID, ruid, CTLFLAG_RD | CTLFLAG_MPSAFE,
2809 	sysctl_kern_proc, "Process table");
2810 
2811 static SYSCTL_NODE(_kern_proc, KERN_PROC_PID, pid, CTLFLAG_RD | CTLFLAG_MPSAFE,
2812 	sysctl_kern_proc, "Process table");
2813 
2814 static SYSCTL_NODE(_kern_proc, KERN_PROC_PROC, proc, CTLFLAG_RD | CTLFLAG_MPSAFE,
2815 	sysctl_kern_proc, "Return process table, no threads");
2816 
2817 static SYSCTL_NODE(_kern_proc, KERN_PROC_ARGS, args,
2818 	CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_MPSAFE,
2819 	sysctl_kern_proc_args, "Process argument list");
2820 
2821 static SYSCTL_NODE(_kern_proc, KERN_PROC_ENV, env, CTLFLAG_RD | CTLFLAG_MPSAFE,
2822 	sysctl_kern_proc_env, "Process environment");
2823 
2824 static SYSCTL_NODE(_kern_proc, KERN_PROC_AUXV, auxv, CTLFLAG_RD |
2825 	CTLFLAG_MPSAFE, sysctl_kern_proc_auxv, "Process ELF auxiliary vector");
2826 
2827 static SYSCTL_NODE(_kern_proc, KERN_PROC_PATHNAME, pathname, CTLFLAG_RD |
2828 	CTLFLAG_MPSAFE, sysctl_kern_proc_pathname, "Process executable path");
2829 
2830 static SYSCTL_NODE(_kern_proc, KERN_PROC_SV_NAME, sv_name, CTLFLAG_RD |
2831 	CTLFLAG_MPSAFE, sysctl_kern_proc_sv_name,
2832 	"Process syscall vector name (ABI type)");
2833 
2834 static SYSCTL_NODE(_kern_proc, (KERN_PROC_GID | KERN_PROC_INC_THREAD), gid_td,
2835 	CTLFLAG_RD | CTLFLAG_MPSAFE, sysctl_kern_proc, "Process table");
2836 
2837 static SYSCTL_NODE(_kern_proc, (KERN_PROC_PGRP | KERN_PROC_INC_THREAD), pgrp_td,
2838 	CTLFLAG_RD | CTLFLAG_MPSAFE, sysctl_kern_proc, "Process table");
2839 
2840 static SYSCTL_NODE(_kern_proc, (KERN_PROC_RGID | KERN_PROC_INC_THREAD), rgid_td,
2841 	CTLFLAG_RD | CTLFLAG_MPSAFE, sysctl_kern_proc, "Process table");
2842 
2843 static SYSCTL_NODE(_kern_proc, (KERN_PROC_SESSION | KERN_PROC_INC_THREAD),
2844 	sid_td, CTLFLAG_RD | CTLFLAG_MPSAFE, sysctl_kern_proc, "Process table");
2845 
2846 static SYSCTL_NODE(_kern_proc, (KERN_PROC_TTY | KERN_PROC_INC_THREAD), tty_td,
2847 	CTLFLAG_RD | CTLFLAG_MPSAFE, sysctl_kern_proc, "Process table");
2848 
2849 static SYSCTL_NODE(_kern_proc, (KERN_PROC_UID | KERN_PROC_INC_THREAD), uid_td,
2850 	CTLFLAG_RD | CTLFLAG_MPSAFE, sysctl_kern_proc, "Process table");
2851 
2852 static SYSCTL_NODE(_kern_proc, (KERN_PROC_RUID | KERN_PROC_INC_THREAD), ruid_td,
2853 	CTLFLAG_RD | CTLFLAG_MPSAFE, sysctl_kern_proc, "Process table");
2854 
2855 static SYSCTL_NODE(_kern_proc, (KERN_PROC_PID | KERN_PROC_INC_THREAD), pid_td,
2856 	CTLFLAG_RD | CTLFLAG_MPSAFE, sysctl_kern_proc, "Process table");
2857 
2858 static SYSCTL_NODE(_kern_proc, (KERN_PROC_PROC | KERN_PROC_INC_THREAD), proc_td,
2859 	CTLFLAG_RD | CTLFLAG_MPSAFE, sysctl_kern_proc,
2860 	"Return process table, no threads");
2861 
2862 #ifdef COMPAT_FREEBSD7
2863 static SYSCTL_NODE(_kern_proc, KERN_PROC_OVMMAP, ovmmap, CTLFLAG_RD |
2864 	CTLFLAG_MPSAFE, sysctl_kern_proc_ovmmap, "Old Process vm map entries");
2865 #endif
2866 
2867 static SYSCTL_NODE(_kern_proc, KERN_PROC_VMMAP, vmmap, CTLFLAG_RD |
2868 	CTLFLAG_MPSAFE, sysctl_kern_proc_vmmap, "Process vm map entries");
2869 
2870 #if defined(STACK) || defined(DDB)
2871 static SYSCTL_NODE(_kern_proc, KERN_PROC_KSTACK, kstack, CTLFLAG_RD |
2872 	CTLFLAG_MPSAFE, sysctl_kern_proc_kstack, "Process kernel stacks");
2873 #endif
2874 
2875 static SYSCTL_NODE(_kern_proc, KERN_PROC_GROUPS, groups, CTLFLAG_RD |
2876 	CTLFLAG_MPSAFE, sysctl_kern_proc_groups, "Process groups");
2877 
2878 static SYSCTL_NODE(_kern_proc, KERN_PROC_RLIMIT, rlimit, CTLFLAG_RW |
2879 	CTLFLAG_ANYBODY | CTLFLAG_MPSAFE, sysctl_kern_proc_rlimit,
2880 	"Process resource limits");
2881 
2882 static SYSCTL_NODE(_kern_proc, KERN_PROC_PS_STRINGS, ps_strings, CTLFLAG_RD |
2883 	CTLFLAG_MPSAFE, sysctl_kern_proc_ps_strings,
2884 	"Process ps_strings location");
2885 
2886 static SYSCTL_NODE(_kern_proc, KERN_PROC_UMASK, umask, CTLFLAG_RD |
2887 	CTLFLAG_MPSAFE, sysctl_kern_proc_umask, "Process umask");
2888 
2889 static SYSCTL_NODE(_kern_proc, KERN_PROC_OSREL, osrel, CTLFLAG_RW |
2890 	CTLFLAG_ANYBODY | CTLFLAG_MPSAFE, sysctl_kern_proc_osrel,
2891 	"Process binary osreldate");
2892 
2893 static SYSCTL_NODE(_kern_proc, KERN_PROC_SIGTRAMP, sigtramp, CTLFLAG_RD |
2894 	CTLFLAG_MPSAFE, sysctl_kern_proc_sigtramp,
2895 	"Process signal trampoline location");
2896