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