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