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