kern_proc.c revision 1.251 1 /* $NetBSD: kern_proc.c,v 1.251 2020/04/29 01:52:26 thorpej Exp $ */
2
3 /*-
4 * Copyright (c) 1999, 2006, 2007, 2008, 2020 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
9 * NASA Ames Research Center, and by Andrew Doran.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
22 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
24 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30 * POSSIBILITY OF SUCH DAMAGE.
31 */
32
33 /*
34 * Copyright (c) 1982, 1986, 1989, 1991, 1993
35 * The Regents of the University of California. All rights reserved.
36 *
37 * Redistribution and use in source and binary forms, with or without
38 * modification, are permitted provided that the following conditions
39 * are met:
40 * 1. Redistributions of source code must retain the above copyright
41 * notice, this list of conditions and the following disclaimer.
42 * 2. Redistributions in binary form must reproduce the above copyright
43 * notice, this list of conditions and the following disclaimer in the
44 * documentation and/or other materials provided with the distribution.
45 * 3. Neither the name of the University nor the names of its contributors
46 * may be used to endorse or promote products derived from this software
47 * without specific prior written permission.
48 *
49 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
50 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
51 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
52 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
53 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
54 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
55 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
56 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
57 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
58 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
59 * SUCH DAMAGE.
60 *
61 * @(#)kern_proc.c 8.7 (Berkeley) 2/14/95
62 */
63
64 #include <sys/cdefs.h>
65 __KERNEL_RCSID(0, "$NetBSD: kern_proc.c,v 1.251 2020/04/29 01:52:26 thorpej Exp $");
66
67 #ifdef _KERNEL_OPT
68 #include "opt_kstack.h"
69 #include "opt_maxuprc.h"
70 #include "opt_dtrace.h"
71 #include "opt_compat_netbsd32.h"
72 #include "opt_kaslr.h"
73 #endif
74
75 #if defined(__HAVE_COMPAT_NETBSD32) && !defined(COMPAT_NETBSD32) \
76 && !defined(_RUMPKERNEL)
77 #define COMPAT_NETBSD32
78 #endif
79
80 #include <sys/param.h>
81 #include <sys/systm.h>
82 #include <sys/kernel.h>
83 #include <sys/proc.h>
84 #include <sys/resourcevar.h>
85 #include <sys/buf.h>
86 #include <sys/acct.h>
87 #include <sys/wait.h>
88 #include <sys/file.h>
89 #include <ufs/ufs/quota.h>
90 #include <sys/uio.h>
91 #include <sys/pool.h>
92 #include <sys/pset.h>
93 #include <sys/ioctl.h>
94 #include <sys/tty.h>
95 #include <sys/signalvar.h>
96 #include <sys/ras.h>
97 #include <sys/filedesc.h>
98 #include <sys/syscall_stats.h>
99 #include <sys/kauth.h>
100 #include <sys/sleepq.h>
101 #include <sys/atomic.h>
102 #include <sys/kmem.h>
103 #include <sys/namei.h>
104 #include <sys/dtrace_bsd.h>
105 #include <sys/sysctl.h>
106 #include <sys/exec.h>
107 #include <sys/cpu.h>
108 #include <sys/compat_stub.h>
109 #include <sys/futex.h>
110
111 #include <uvm/uvm_extern.h>
112 #include <uvm/uvm.h>
113
114 /*
115 * Process lists.
116 */
117
118 struct proclist allproc __cacheline_aligned;
119 struct proclist zombproc __cacheline_aligned;
120
121 static kmutex_t proc_lock_s __cacheline_aligned;
122 kmutex_t * proc_lock __read_mostly;
123
124 /*
125 * pid to lwp/proc lookup is done by indexing the pid_table array.
126 * Since pid numbers are only allocated when an empty slot
127 * has been found, there is no need to search any lists ever.
128 * (an orphaned pgrp will lock the slot, a session will lock
129 * the pgrp with the same number.)
130 * If the table is too small it is reallocated with twice the
131 * previous size and the entries 'unzipped' into the two halves.
132 * A linked list of free entries is passed through the pt_lwp
133 * field of 'free' items - set odd to be an invalid ptr. Two
134 * additional bits are also used to indicate if the slot is
135 * currently occupied by a proc or lwp, and if the PID is
136 * hidden from certain kinds of lookups. We thus require a
137 * minimum alignment for proc and lwp structures (LWPs are
138 * at least 32-byte aligned).
139 */
140
141 struct pid_table {
142 uintptr_t pt_slot;
143 struct pgrp *pt_pgrp;
144 pid_t pt_pid;
145 };
146
147 #define PT_F_FREE ((uintptr_t)__BIT(0))
148 #define PT_F_LWP 0 /* pseudo-flag */
149 #define PT_F_PROC ((uintptr_t)__BIT(1))
150
151 #define PT_F_TYPEBITS (PT_F_FREE|PT_F_PROC)
152 #define PT_F_ALLBITS (PT_F_FREE|PT_F_PROC)
153
154 #define PT_VALID(s) (((s) & PT_F_FREE) == 0)
155 #define PT_RESERVED(s) ((s) == 0)
156 #define PT_NEXT(s) ((u_int)(s) >> 1)
157 #define PT_SET_FREE(pid) (((pid) << 1) | PT_F_FREE)
158 #define PT_SET_LWP(l) ((uintptr_t)(l))
159 #define PT_SET_PROC(p) (((uintptr_t)(p)) | PT_F_PROC)
160 #define PT_SET_RESERVED 0
161 #define PT_GET_LWP(s) ((struct lwp *)((s) & ~PT_F_ALLBITS))
162 #define PT_GET_PROC(s) ((struct proc *)((s) & ~PT_F_ALLBITS))
163 #define PT_GET_TYPE(s) ((s) & PT_F_TYPEBITS)
164 #define PT_IS_LWP(s) (PT_GET_TYPE(s) == PT_F_LWP && (s) != 0)
165 #define PT_IS_PROC(s) (PT_GET_TYPE(s) == PT_F_PROC)
166
167 #define MIN_PROC_ALIGNMENT (PT_F_ALLBITS + 1)
168
169 /*
170 * Table of process IDs (PIDs).
171 *
172 * Locking order:
173 * proc_lock -> pid_table_lock
174 * or
175 * proc::p_lock -> pid_table_lock
176 */
177 static krwlock_t pid_table_lock __cacheline_aligned;
178 static struct pid_table *pid_table __read_mostly;
179
180 #define INITIAL_PID_TABLE_SIZE (1 << 5)
181
182 /* Table mask, threshold for growing and number of allocated PIDs. */
183 static u_int pid_tbl_mask __read_mostly;
184 static u_int pid_alloc_lim __read_mostly;
185 static u_int pid_alloc_cnt __cacheline_aligned;
186
187 /* Next free, last free and maximum PIDs. */
188 static u_int next_free_pt __cacheline_aligned;
189 static u_int last_free_pt __cacheline_aligned;
190 static pid_t pid_max __read_mostly;
191
192 /* Components of the first process -- never freed. */
193
194 extern struct emul emul_netbsd; /* defined in kern_exec.c */
195
196 struct session session0 = {
197 .s_count = 1,
198 .s_sid = 0,
199 };
200 struct pgrp pgrp0 = {
201 .pg_members = LIST_HEAD_INITIALIZER(&pgrp0.pg_members),
202 .pg_session = &session0,
203 };
204 filedesc_t filedesc0;
205 struct cwdinfo cwdi0 = {
206 .cwdi_cmask = CMASK,
207 .cwdi_refcnt = 1,
208 };
209 struct plimit limit0;
210 struct pstats pstat0;
211 struct vmspace vmspace0;
212 struct sigacts sigacts0;
213 struct proc proc0 = {
214 .p_lwps = LIST_HEAD_INITIALIZER(&proc0.p_lwps),
215 .p_sigwaiters = LIST_HEAD_INITIALIZER(&proc0.p_sigwaiters),
216 .p_nlwps = 1,
217 .p_nrlwps = 1,
218 .p_pgrp = &pgrp0,
219 .p_comm = "system",
220 /*
221 * Set P_NOCLDWAIT so that kernel threads are reparented to init(8)
222 * when they exit. init(8) can easily wait them out for us.
223 */
224 .p_flag = PK_SYSTEM | PK_NOCLDWAIT,
225 .p_stat = SACTIVE,
226 .p_nice = NZERO,
227 .p_emul = &emul_netbsd,
228 .p_cwdi = &cwdi0,
229 .p_limit = &limit0,
230 .p_fd = &filedesc0,
231 .p_vmspace = &vmspace0,
232 .p_stats = &pstat0,
233 .p_sigacts = &sigacts0,
234 #ifdef PROC0_MD_INITIALIZERS
235 PROC0_MD_INITIALIZERS
236 #endif
237 };
238 kauth_cred_t cred0;
239
240 static const int nofile = NOFILE;
241 static const int maxuprc = MAXUPRC;
242
243 static int sysctl_doeproc(SYSCTLFN_PROTO);
244 static int sysctl_kern_proc_args(SYSCTLFN_PROTO);
245 static int sysctl_security_expose_address(SYSCTLFN_PROTO);
246
247 #ifdef KASLR
248 static int kern_expose_address = 0;
249 #else
250 static int kern_expose_address = 1;
251 #endif
252 /*
253 * The process list descriptors, used during pid allocation and
254 * by sysctl. No locking on this data structure is needed since
255 * it is completely static.
256 */
257 const struct proclist_desc proclists[] = {
258 { &allproc },
259 { &zombproc },
260 { NULL },
261 };
262
263 static struct pgrp * pg_remove(pid_t);
264 static void pg_delete(pid_t);
265 static void orphanpg(struct pgrp *);
266
267 static specificdata_domain_t proc_specificdata_domain;
268
269 static pool_cache_t proc_cache;
270
271 static kauth_listener_t proc_listener;
272
273 static void fill_proc(const struct proc *, struct proc *, bool);
274 static int fill_pathname(struct lwp *, pid_t, void *, size_t *);
275 static int fill_cwd(struct lwp *, pid_t, void *, size_t *);
276
277 static int
278 proc_listener_cb(kauth_cred_t cred, kauth_action_t action, void *cookie,
279 void *arg0, void *arg1, void *arg2, void *arg3)
280 {
281 struct proc *p;
282 int result;
283
284 result = KAUTH_RESULT_DEFER;
285 p = arg0;
286
287 switch (action) {
288 case KAUTH_PROCESS_CANSEE: {
289 enum kauth_process_req req;
290
291 req = (enum kauth_process_req)(uintptr_t)arg1;
292
293 switch (req) {
294 case KAUTH_REQ_PROCESS_CANSEE_ARGS:
295 case KAUTH_REQ_PROCESS_CANSEE_ENTRY:
296 case KAUTH_REQ_PROCESS_CANSEE_OPENFILES:
297 case KAUTH_REQ_PROCESS_CANSEE_EPROC:
298 result = KAUTH_RESULT_ALLOW;
299 break;
300
301 case KAUTH_REQ_PROCESS_CANSEE_ENV:
302 if (kauth_cred_getuid(cred) !=
303 kauth_cred_getuid(p->p_cred) ||
304 kauth_cred_getuid(cred) !=
305 kauth_cred_getsvuid(p->p_cred))
306 break;
307
308 result = KAUTH_RESULT_ALLOW;
309
310 break;
311
312 case KAUTH_REQ_PROCESS_CANSEE_KPTR:
313 if (!kern_expose_address)
314 break;
315
316 if (kern_expose_address == 1 && !(p->p_flag & PK_KMEM))
317 break;
318
319 result = KAUTH_RESULT_ALLOW;
320
321 break;
322
323 default:
324 break;
325 }
326
327 break;
328 }
329
330 case KAUTH_PROCESS_FORK: {
331 int lnprocs = (int)(unsigned long)arg2;
332
333 /*
334 * Don't allow a nonprivileged user to use the last few
335 * processes. The variable lnprocs is the current number of
336 * processes, maxproc is the limit.
337 */
338 if (__predict_false((lnprocs >= maxproc - 5)))
339 break;
340
341 result = KAUTH_RESULT_ALLOW;
342
343 break;
344 }
345
346 case KAUTH_PROCESS_CORENAME:
347 case KAUTH_PROCESS_STOPFLAG:
348 if (proc_uidmatch(cred, p->p_cred) == 0)
349 result = KAUTH_RESULT_ALLOW;
350
351 break;
352
353 default:
354 break;
355 }
356
357 return result;
358 }
359
360 static int
361 proc_ctor(void *arg __unused, void *obj, int flags __unused)
362 {
363 memset(obj, 0, sizeof(struct proc));
364 return 0;
365 }
366
367 static pid_t proc_alloc_pid_slot(struct proc *, uintptr_t);
368
369 /*
370 * Initialize global process hashing structures.
371 */
372 void
373 procinit(void)
374 {
375 const struct proclist_desc *pd;
376 u_int i;
377 #define LINK_EMPTY ((PID_MAX + INITIAL_PID_TABLE_SIZE) & ~(INITIAL_PID_TABLE_SIZE - 1))
378
379 for (pd = proclists; pd->pd_list != NULL; pd++)
380 LIST_INIT(pd->pd_list);
381
382 mutex_init(&proc_lock_s, MUTEX_DEFAULT, IPL_NONE);
383 proc_lock = &proc_lock_s;
384
385 rw_init(&pid_table_lock);
386
387 pid_table = kmem_alloc(INITIAL_PID_TABLE_SIZE
388 * sizeof(struct pid_table), KM_SLEEP);
389 pid_tbl_mask = INITIAL_PID_TABLE_SIZE - 1;
390 pid_max = PID_MAX;
391
392 /* Set free list running through table...
393 Preset 'use count' above PID_MAX so we allocate pid 1 next. */
394 for (i = 0; i <= pid_tbl_mask; i++) {
395 pid_table[i].pt_slot = PT_SET_FREE(LINK_EMPTY + i + 1);
396 pid_table[i].pt_pgrp = 0;
397 pid_table[i].pt_pid = 0;
398 }
399 /* slot 0 is just grabbed */
400 next_free_pt = 1;
401 /* Need to fix last entry. */
402 last_free_pt = pid_tbl_mask;
403 pid_table[last_free_pt].pt_slot = PT_SET_FREE(LINK_EMPTY);
404 /* point at which we grow table - to avoid reusing pids too often */
405 pid_alloc_lim = pid_tbl_mask - 1;
406 #undef LINK_EMPTY
407
408 /* Reserve PID 1 for init(8). */ /* XXX slightly gross */
409 rw_enter(&pid_table_lock, RW_WRITER);
410 if (proc_alloc_pid_slot(&proc0, PT_SET_RESERVED) != 1)
411 panic("failed to reserve PID 1 for init(8)");
412 rw_exit(&pid_table_lock);
413
414 proc_specificdata_domain = specificdata_domain_create();
415 KASSERT(proc_specificdata_domain != NULL);
416
417 size_t proc_alignment = coherency_unit;
418 if (proc_alignment < MIN_PROC_ALIGNMENT)
419 proc_alignment = MIN_PROC_ALIGNMENT;
420
421 proc_cache = pool_cache_init(sizeof(struct proc), proc_alignment, 0, 0,
422 "procpl", NULL, IPL_NONE, proc_ctor, NULL, NULL);
423
424 proc_listener = kauth_listen_scope(KAUTH_SCOPE_PROCESS,
425 proc_listener_cb, NULL);
426 }
427
428 void
429 procinit_sysctl(void)
430 {
431 static struct sysctllog *clog;
432
433 sysctl_createv(&clog, 0, NULL, NULL,
434 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
435 CTLTYPE_INT, "expose_address",
436 SYSCTL_DESCR("Enable exposing kernel addresses"),
437 sysctl_security_expose_address, 0,
438 &kern_expose_address, 0, CTL_KERN, CTL_CREATE, CTL_EOL);
439 sysctl_createv(&clog, 0, NULL, NULL,
440 CTLFLAG_PERMANENT,
441 CTLTYPE_NODE, "proc",
442 SYSCTL_DESCR("System-wide process information"),
443 sysctl_doeproc, 0, NULL, 0,
444 CTL_KERN, KERN_PROC, CTL_EOL);
445 sysctl_createv(&clog, 0, NULL, NULL,
446 CTLFLAG_PERMANENT,
447 CTLTYPE_NODE, "proc2",
448 SYSCTL_DESCR("Machine-independent process information"),
449 sysctl_doeproc, 0, NULL, 0,
450 CTL_KERN, KERN_PROC2, CTL_EOL);
451 sysctl_createv(&clog, 0, NULL, NULL,
452 CTLFLAG_PERMANENT,
453 CTLTYPE_NODE, "proc_args",
454 SYSCTL_DESCR("Process argument information"),
455 sysctl_kern_proc_args, 0, NULL, 0,
456 CTL_KERN, KERN_PROC_ARGS, CTL_EOL);
457
458 /*
459 "nodes" under these:
460
461 KERN_PROC_ALL
462 KERN_PROC_PID pid
463 KERN_PROC_PGRP pgrp
464 KERN_PROC_SESSION sess
465 KERN_PROC_TTY tty
466 KERN_PROC_UID uid
467 KERN_PROC_RUID uid
468 KERN_PROC_GID gid
469 KERN_PROC_RGID gid
470
471 all in all, probably not worth the effort...
472 */
473 }
474
475 /*
476 * Initialize process 0.
477 */
478 void
479 proc0_init(void)
480 {
481 struct proc *p;
482 struct pgrp *pg;
483 struct rlimit *rlim;
484 rlim_t lim;
485 int i;
486
487 p = &proc0;
488 pg = &pgrp0;
489
490 mutex_init(&p->p_stmutex, MUTEX_DEFAULT, IPL_HIGH);
491 mutex_init(&p->p_auxlock, MUTEX_DEFAULT, IPL_NONE);
492 p->p_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE);
493
494 rw_init(&p->p_reflock);
495 cv_init(&p->p_waitcv, "wait");
496 cv_init(&p->p_lwpcv, "lwpwait");
497
498 LIST_INSERT_HEAD(&p->p_lwps, &lwp0, l_sibling);
499
500 KASSERT(lwp0.l_lid == 0);
501 pid_table[lwp0.l_lid].pt_slot = PT_SET_LWP(&lwp0);
502 LIST_INSERT_HEAD(&allproc, p, p_list);
503
504 pid_table[lwp0.l_lid].pt_pgrp = pg;
505 LIST_INSERT_HEAD(&pg->pg_members, p, p_pglist);
506
507 #ifdef __HAVE_SYSCALL_INTERN
508 (*p->p_emul->e_syscall_intern)(p);
509 #endif
510
511 /* Create credentials. */
512 cred0 = kauth_cred_alloc();
513 p->p_cred = cred0;
514
515 /* Create the CWD info. */
516 rw_init(&cwdi0.cwdi_lock);
517
518 /* Create the limits structures. */
519 mutex_init(&limit0.pl_lock, MUTEX_DEFAULT, IPL_NONE);
520
521 rlim = limit0.pl_rlimit;
522 for (i = 0; i < __arraycount(limit0.pl_rlimit); i++) {
523 rlim[i].rlim_cur = RLIM_INFINITY;
524 rlim[i].rlim_max = RLIM_INFINITY;
525 }
526
527 rlim[RLIMIT_NOFILE].rlim_max = maxfiles;
528 rlim[RLIMIT_NOFILE].rlim_cur = maxfiles < nofile ? maxfiles : nofile;
529
530 rlim[RLIMIT_NPROC].rlim_max = maxproc;
531 rlim[RLIMIT_NPROC].rlim_cur = maxproc < maxuprc ? maxproc : maxuprc;
532
533 lim = MIN(VM_MAXUSER_ADDRESS, ctob((rlim_t)uvm_availmem()));
534 rlim[RLIMIT_RSS].rlim_max = lim;
535 rlim[RLIMIT_MEMLOCK].rlim_max = lim;
536 rlim[RLIMIT_MEMLOCK].rlim_cur = lim / 3;
537
538 rlim[RLIMIT_NTHR].rlim_max = maxlwp;
539 rlim[RLIMIT_NTHR].rlim_cur = maxlwp < maxuprc ? maxlwp : maxuprc;
540
541 /* Note that default core name has zero length. */
542 limit0.pl_corename = defcorename;
543 limit0.pl_cnlen = 0;
544 limit0.pl_refcnt = 1;
545 limit0.pl_writeable = false;
546 limit0.pl_sv_limit = NULL;
547
548 /* Configure virtual memory system, set vm rlimits. */
549 uvm_init_limits(p);
550
551 /* Initialize file descriptor table for proc0. */
552 fd_init(&filedesc0);
553
554 /*
555 * Initialize proc0's vmspace, which uses the kernel pmap.
556 * All kernel processes (which never have user space mappings)
557 * share proc0's vmspace, and thus, the kernel pmap.
558 */
559 uvmspace_init(&vmspace0, pmap_kernel(), round_page(VM_MIN_ADDRESS),
560 trunc_page(VM_MAXUSER_ADDRESS),
561 #ifdef __USE_TOPDOWN_VM
562 true
563 #else
564 false
565 #endif
566 );
567
568 /* Initialize signal state for proc0. XXX IPL_SCHED */
569 mutex_init(&p->p_sigacts->sa_mutex, MUTEX_DEFAULT, IPL_SCHED);
570 siginit(p);
571
572 proc_initspecific(p);
573 kdtrace_proc_ctor(NULL, p);
574 }
575
576 /*
577 * Session reference counting.
578 */
579
580 void
581 proc_sesshold(struct session *ss)
582 {
583
584 KASSERT(mutex_owned(proc_lock));
585 ss->s_count++;
586 }
587
588 static void
589 proc_sessrele_pid_table_write_locked(struct session *ss)
590 {
591 struct pgrp *pg;
592
593 KASSERT(mutex_owned(proc_lock));
594 KASSERT(rw_write_held(&pid_table_lock));
595 KASSERT(ss->s_count > 0);
596
597 /*
598 * We keep the pgrp with the same id as the session in order to
599 * stop a process being given the same pid. Since the pgrp holds
600 * a reference to the session, it must be a 'zombie' pgrp by now.
601 */
602 if (--ss->s_count == 0) {
603 pg = pg_remove(ss->s_sid);
604 } else {
605 pg = NULL;
606 ss = NULL;
607 }
608
609 rw_exit(&pid_table_lock);
610 mutex_exit(proc_lock);
611
612 if (pg)
613 kmem_free(pg, sizeof(struct pgrp));
614 if (ss)
615 kmem_free(ss, sizeof(struct session));
616 }
617
618 void
619 proc_sessrele(struct session *ss)
620 {
621 rw_enter(&pid_table_lock, RW_WRITER);
622 proc_sessrele_pid_table_write_locked(ss);
623 }
624
625 /*
626 * Check that the specified process group is in the session of the
627 * specified process.
628 * Treats -ve ids as process ids.
629 * Used to validate TIOCSPGRP requests.
630 */
631 int
632 pgid_in_session(struct proc *p, pid_t pg_id)
633 {
634 struct pgrp *pgrp;
635 struct session *session;
636 int error;
637
638 mutex_enter(proc_lock);
639 if (pg_id < 0) {
640 struct proc *p1 = proc_find(-pg_id);
641 if (p1 == NULL) {
642 error = EINVAL;
643 goto fail;
644 }
645 pgrp = p1->p_pgrp;
646 } else {
647 pgrp = pgrp_find(pg_id);
648 if (pgrp == NULL) {
649 error = EINVAL;
650 goto fail;
651 }
652 }
653 session = pgrp->pg_session;
654 error = (session != p->p_pgrp->pg_session) ? EPERM : 0;
655 fail:
656 mutex_exit(proc_lock);
657 return error;
658 }
659
660 /*
661 * p_inferior: is p an inferior of q?
662 */
663 static inline bool
664 p_inferior(struct proc *p, struct proc *q)
665 {
666
667 KASSERT(mutex_owned(proc_lock));
668
669 for (; p != q; p = p->p_pptr)
670 if (p->p_pid == 0)
671 return false;
672 return true;
673 }
674
675 /*
676 * proc_find_lwp: locate an lwp in said proc by the ID.
677 *
678 * => Must be called with p::p_lock held.
679 * => LARVAL lwps are not returned because they are only partially
680 * constructed while occupying the slot.
681 * => Callers need to be careful about lwp::l_stat of the returned
682 * lwp.
683 */
684 struct lwp *
685 proc_find_lwp(proc_t *p, pid_t pid)
686 {
687 struct pid_table *pt;
688 struct lwp *l = NULL;
689 uintptr_t slot;
690
691 KASSERT(mutex_owned(p->p_lock));
692 rw_enter(&pid_table_lock, RW_READER);
693 pt = &pid_table[pid & pid_tbl_mask];
694
695 slot = pt->pt_slot;
696 if (__predict_true(PT_IS_LWP(slot) && pt->pt_pid == pid)) {
697 l = PT_GET_LWP(slot);
698 if (__predict_false(l->l_proc != p || l->l_stat == LSLARVAL)) {
699 l = NULL;
700 }
701 }
702 rw_exit(&pid_table_lock);
703
704 return l;
705 }
706
707 /*
708 * proc_find_lwp_acquire_proc: locate an lwp and acquire a lock
709 * on its containing proc.
710 *
711 * => Similar to proc_find_lwp(), but does not require you to have
712 * the proc a priori.
713 * => Also returns proc * to caller, with p::p_lock held.
714 * => Same caveats apply.
715 */
716 struct lwp *
717 proc_find_lwp_acquire_proc(pid_t pid, struct proc **pp)
718 {
719 struct pid_table *pt;
720 struct proc *p = NULL;
721 struct lwp *l = NULL;
722 uintptr_t slot;
723
724 KASSERT(pp != NULL);
725 mutex_enter(proc_lock);
726 rw_enter(&pid_table_lock, RW_READER);
727 pt = &pid_table[pid & pid_tbl_mask];
728
729 slot = pt->pt_slot;
730 if (__predict_true(PT_IS_LWP(slot) && pt->pt_pid == pid)) {
731 /*
732 * Locking order is p::p_lock -> pid_table_lock, but
733 * we're already holding pid_table_lock; we need to
734 * release it before acquiring p::p_lock. This is
735 * safe because p will be stable by virtue of holding
736 * proc_lock.
737 */
738 l = PT_GET_LWP(slot);
739 p = l->l_proc;
740 rw_exit(&pid_table_lock);
741 mutex_enter(p->p_lock);
742 if (__predict_false(l->l_stat == LSLARVAL)) {
743 mutex_exit(p->p_lock);
744 l = NULL;
745 p = NULL;
746 }
747 } else {
748 rw_exit(&pid_table_lock);
749 }
750 mutex_exit(proc_lock);
751
752 KASSERT(p == NULL || mutex_owned(p->p_lock));
753 *pp = p;
754 return l;
755 }
756
757 /*
758 * proc_find_raw_pid_table_locked: locate a process by the ID.
759 *
760 * => Must be called with proc_lock held and the pid_table_lock
761 * at least held for reading.
762 */
763 static proc_t *
764 proc_find_raw_pid_table_locked(pid_t pid, bool any_lwpid)
765 {
766 struct pid_table *pt;
767 proc_t *p = NULL;
768 uintptr_t slot;
769
770 KASSERT(mutex_owned(proc_lock));
771 pt = &pid_table[pid & pid_tbl_mask];
772
773 slot = pt->pt_slot;
774 if (__predict_true(PT_IS_LWP(slot) && pt->pt_pid == pid)) {
775 /*
776 * When looking up processes, require a direct match
777 * on the PID assigned to the proc, not just one of
778 * its LWPs.
779 *
780 * N.B. We require lwp::l_proc of LARVAL LWPs to be
781 * valid here.
782 */
783 p = PT_GET_LWP(slot)->l_proc;
784 if (__predict_false(p->p_pid != pid && !any_lwpid))
785 p = NULL;
786 } else if (PT_IS_PROC(slot) && pt->pt_pid == pid) {
787 p = PT_GET_PROC(slot);
788 }
789 return p;
790 }
791
792 proc_t *
793 proc_find_raw(pid_t pid)
794 {
795 KASSERT(mutex_owned(proc_lock));
796 rw_enter(&pid_table_lock, RW_READER);
797 proc_t *p = proc_find_raw_pid_table_locked(pid, false);
798 rw_exit(&pid_table_lock);
799 return p;
800 }
801
802 static proc_t *
803 proc_find_pid_table_locked(pid_t pid, bool any_lwpid)
804 {
805 proc_t *p;
806
807 KASSERT(mutex_owned(proc_lock));
808
809 p = proc_find_raw_pid_table_locked(pid, any_lwpid);
810 if (__predict_false(p == NULL)) {
811 return NULL;
812 }
813
814 /*
815 * Only allow live processes to be found by PID.
816 * XXX: p_stat might change, since proc unlocked.
817 */
818 if (__predict_true(p->p_stat == SACTIVE || p->p_stat == SSTOP)) {
819 return p;
820 }
821 return NULL;
822 }
823
824 static proc_t *
825 proc_find_internal(pid_t pid, bool any_lwpid)
826 {
827 KASSERT(mutex_owned(proc_lock));
828 rw_enter(&pid_table_lock, RW_READER);
829 proc_t *p = proc_find_pid_table_locked(pid, any_lwpid);
830 rw_exit(&pid_table_lock);
831 return p;
832 }
833
834 proc_t *
835 proc_find(pid_t pid)
836 {
837 return proc_find_internal(pid, false);
838 }
839
840 proc_t *
841 proc_find_lwpid(pid_t pid)
842 {
843 return proc_find_internal(pid, true);
844 }
845
846 /*
847 * pgrp_find_pid_table_locked: locate a process group by the ID.
848 *
849 * => Must be called with proc_lock held and the pid_table_lock
850 * held at least for reading.
851 */
852 static struct pgrp *
853 pgrp_find_pid_table_locked(pid_t pgid)
854 {
855 struct pgrp *pg;
856
857 KASSERT(mutex_owned(proc_lock));
858
859 pg = pid_table[pgid & pid_tbl_mask].pt_pgrp;
860
861 /*
862 * Cannot look up a process group that only exists because the
863 * session has not died yet (traditional).
864 */
865 if (pg == NULL || pg->pg_id != pgid || LIST_EMPTY(&pg->pg_members)) {
866 return NULL;
867 }
868 return pg;
869 }
870
871 struct pgrp *
872 pgrp_find(pid_t pgid)
873 {
874 KASSERT(mutex_owned(proc_lock));
875 rw_enter(&pid_table_lock, RW_READER);
876 struct pgrp *pg = pgrp_find_pid_table_locked(pgid);
877 rw_exit(&pid_table_lock);
878 return pg;
879 }
880
881 static void
882 expand_pid_table(void)
883 {
884 size_t pt_size, tsz;
885 struct pid_table *n_pt, *new_pt;
886 uintptr_t slot;
887 struct pgrp *pgrp;
888 pid_t pid, rpid;
889 u_int i;
890 uint new_pt_mask;
891
892 KASSERT(rw_write_held(&pid_table_lock));
893
894 /* Unlock the pid_table briefly to allocate memory. */
895 pt_size = pid_tbl_mask + 1;
896 rw_exit(&pid_table_lock);
897
898 tsz = pt_size * 2 * sizeof(struct pid_table);
899 new_pt = kmem_alloc(tsz, KM_SLEEP);
900 new_pt_mask = pt_size * 2 - 1;
901
902 /* XXX For now. The pratical limit is much lower anyway. */
903 KASSERT(new_pt_mask <= FUTEX_TID_MASK);
904
905 rw_enter(&pid_table_lock, RW_WRITER);
906 if (pt_size != pid_tbl_mask + 1) {
907 /* Another process beat us to it... */
908 rw_exit(&pid_table_lock);
909 kmem_free(new_pt, tsz);
910 goto out;
911 }
912
913 /*
914 * Copy entries from old table into new one.
915 * If 'pid' is 'odd' we need to place in the upper half,
916 * even pid's to the lower half.
917 * Free items stay in the low half so we don't have to
918 * fixup the reference to them.
919 * We stuff free items on the front of the freelist
920 * because we can't write to unmodified entries.
921 * Processing the table backwards maintains a semblance
922 * of issuing pid numbers that increase with time.
923 */
924 i = pt_size - 1;
925 n_pt = new_pt + i;
926 for (; ; i--, n_pt--) {
927 slot = pid_table[i].pt_slot;
928 pgrp = pid_table[i].pt_pgrp;
929 if (!PT_VALID(slot)) {
930 /* Up 'use count' so that link is valid */
931 pid = (PT_NEXT(slot) + pt_size) & ~pt_size;
932 rpid = 0;
933 slot = PT_SET_FREE(pid);
934 if (pgrp)
935 pid = pgrp->pg_id;
936 } else {
937 pid = pid_table[i].pt_pid;
938 rpid = pid;
939 }
940
941 /* Save entry in appropriate half of table */
942 n_pt[pid & pt_size].pt_slot = slot;
943 n_pt[pid & pt_size].pt_pgrp = pgrp;
944 n_pt[pid & pt_size].pt_pid = rpid;
945
946 /* Put other piece on start of free list */
947 pid = (pid ^ pt_size) & ~pid_tbl_mask;
948 n_pt[pid & pt_size].pt_slot =
949 PT_SET_FREE((pid & ~pt_size) | next_free_pt);
950 n_pt[pid & pt_size].pt_pgrp = 0;
951 n_pt[pid & pt_size].pt_pid = 0;
952
953 next_free_pt = i | (pid & pt_size);
954 if (i == 0)
955 break;
956 }
957
958 /* Save old table size and switch tables */
959 tsz = pt_size * sizeof(struct pid_table);
960 n_pt = pid_table;
961 pid_table = new_pt;
962 pid_tbl_mask = new_pt_mask;
963
964 /*
965 * pid_max starts as PID_MAX (= 30000), once we have 16384
966 * allocated pids we need it to be larger!
967 */
968 if (pid_tbl_mask > PID_MAX) {
969 pid_max = pid_tbl_mask * 2 + 1;
970 pid_alloc_lim |= pid_alloc_lim << 1;
971 } else
972 pid_alloc_lim <<= 1; /* doubles number of free slots... */
973
974 rw_exit(&pid_table_lock);
975 kmem_free(n_pt, tsz);
976
977 out: /* Return with the pid_table_lock held again. */
978 rw_enter(&pid_table_lock, RW_WRITER);
979 }
980
981 struct proc *
982 proc_alloc(void)
983 {
984 struct proc *p;
985
986 p = pool_cache_get(proc_cache, PR_WAITOK);
987 p->p_stat = SIDL; /* protect against others */
988 proc_initspecific(p);
989 kdtrace_proc_ctor(NULL, p);
990
991 /*
992 * Allocate a placeholder in the pid_table. When we create the
993 * first LWP for this process, it will take ownership of the
994 * slot.
995 */
996 if (__predict_false(proc_alloc_pid(p) == -1)) {
997 /* Allocating the PID failed; unwind. */
998 proc_finispecific(p);
999 proc_free_mem(p);
1000 p = NULL;
1001 }
1002 return p;
1003 }
1004
1005 /*
1006 * proc_alloc_pid_slot: allocate PID and record the occcupant so that
1007 * proc_find_raw() can find it by the PID.
1008 */
1009 static pid_t __noinline
1010 proc_alloc_pid_slot(struct proc *p, uintptr_t slot)
1011 {
1012 struct pid_table *pt;
1013 pid_t pid;
1014 int nxt;
1015
1016 KASSERT(rw_write_held(&pid_table_lock));
1017
1018 for (;;expand_pid_table()) {
1019 if (__predict_false(pid_alloc_cnt >= pid_alloc_lim)) {
1020 /* ensure pids cycle through 2000+ values */
1021 continue;
1022 }
1023 /*
1024 * The first user process *must* be given PID 1.
1025 * it has already been reserved for us. This
1026 * will be coming in from the proc_alloc() call
1027 * above, and the entry will be usurped later when
1028 * the first user LWP is created.
1029 * XXX this is slightly gross.
1030 */
1031 if (__predict_false(PT_RESERVED(pid_table[1].pt_slot) &&
1032 p != &proc0)) {
1033 KASSERT(PT_IS_PROC(slot));
1034 pt = &pid_table[1];
1035 pt->pt_slot = slot;
1036 return 1;
1037 }
1038 pt = &pid_table[next_free_pt];
1039 #ifdef DIAGNOSTIC
1040 if (__predict_false(PT_VALID(pt->pt_slot) || pt->pt_pgrp))
1041 panic("proc_alloc: slot busy");
1042 #endif
1043 nxt = PT_NEXT(pt->pt_slot);
1044 if (nxt & pid_tbl_mask)
1045 break;
1046 /* Table full - expand (NB last entry not used....) */
1047 }
1048
1049 /* pid is 'saved use count' + 'size' + entry */
1050 pid = (nxt & ~pid_tbl_mask) + pid_tbl_mask + 1 + next_free_pt;
1051 if ((uint)pid > (uint)pid_max)
1052 pid &= pid_tbl_mask;
1053 next_free_pt = nxt & pid_tbl_mask;
1054
1055 /* XXX For now. The pratical limit is much lower anyway. */
1056 KASSERT(pid <= FUTEX_TID_MASK);
1057
1058 /* Grab table slot */
1059 pt->pt_slot = slot;
1060
1061 KASSERT(pt->pt_pid == 0);
1062 pt->pt_pid = pid;
1063 pid_alloc_cnt++;
1064
1065 return pid;
1066 }
1067
1068 pid_t
1069 proc_alloc_pid(struct proc *p)
1070 {
1071 pid_t pid;
1072
1073 KASSERT((((uintptr_t)p) & PT_F_ALLBITS) == 0);
1074
1075 rw_enter(&pid_table_lock, RW_WRITER);
1076 pid = proc_alloc_pid_slot(p, PT_SET_PROC(p));
1077 if (pid != -1)
1078 p->p_pid = pid;
1079 rw_exit(&pid_table_lock);
1080
1081 return pid;
1082 }
1083
1084 pid_t
1085 proc_alloc_lwpid(struct proc *p, struct lwp *l)
1086 {
1087 struct pid_table *pt;
1088 pid_t pid;
1089
1090 KASSERT((((uintptr_t)l) & PT_F_ALLBITS) == 0);
1091
1092 /*
1093 * If the slot for p->p_pid currently points to the proc,
1094 * then we should usurp this ID for the LWP. This happens
1095 * at least once per process (for the first LWP), and can
1096 * happen again if the first LWP for a process exits and
1097 * before the process creates another.
1098 */
1099 rw_enter(&pid_table_lock, RW_WRITER);
1100 pid = p->p_pid;
1101 pt = &pid_table[pid & pid_tbl_mask];
1102 KASSERT(pt->pt_pid == pid);
1103 if (PT_IS_PROC(pt->pt_slot)) {
1104 KASSERT(PT_GET_PROC(pt->pt_slot) == p);
1105 l->l_lid = pid;
1106 pt->pt_slot = PT_SET_LWP(l);
1107 } else {
1108 /* Need to allocate a new slot. */
1109 pid = proc_alloc_pid_slot(p, PT_SET_LWP(l));
1110 if (pid != -1)
1111 l->l_lid = pid;
1112 }
1113 rw_exit(&pid_table_lock);
1114
1115 return pid;
1116 }
1117
1118 static void __noinline
1119 proc_free_pid_internal(pid_t pid, uintptr_t type __diagused)
1120 {
1121 struct pid_table *pt;
1122
1123 rw_enter(&pid_table_lock, RW_WRITER);
1124 pt = &pid_table[pid & pid_tbl_mask];
1125
1126 KASSERT(PT_GET_TYPE(pt->pt_slot) == type);
1127 KASSERT(pt->pt_pid == pid);
1128
1129 /* save pid use count in slot */
1130 pt->pt_slot = PT_SET_FREE(pid & ~pid_tbl_mask);
1131 pt->pt_pid = 0;
1132
1133 if (pt->pt_pgrp == NULL) {
1134 /* link last freed entry onto ours */
1135 pid &= pid_tbl_mask;
1136 pt = &pid_table[last_free_pt];
1137 pt->pt_slot = PT_SET_FREE(PT_NEXT(pt->pt_slot) | pid);
1138 pt->pt_pid = 0;
1139 last_free_pt = pid;
1140 pid_alloc_cnt--;
1141 }
1142 rw_exit(&pid_table_lock);
1143 }
1144
1145 /*
1146 * Free a process id - called from proc_free (in kern_exit.c)
1147 *
1148 * Called with the proc_lock held.
1149 */
1150 void
1151 proc_free_pid(pid_t pid)
1152 {
1153 KASSERT(mutex_owned(proc_lock));
1154 proc_free_pid_internal(pid, PT_F_PROC);
1155 }
1156
1157 /*
1158 * Free a process id used by an LWP. If this was the process's
1159 * first LWP, we convert the slot to point to the process; the
1160 * entry will get cleaned up later when the process finishes exiting.
1161 *
1162 * If not, then it's the same as proc_free_pid().
1163 */
1164 void
1165 proc_free_lwpid(struct proc *p, pid_t pid)
1166 {
1167
1168 KASSERT(mutex_owned(p->p_lock));
1169
1170 if (__predict_true(p->p_pid == pid)) {
1171 struct pid_table *pt;
1172
1173 rw_enter(&pid_table_lock, RW_WRITER);
1174 pt = &pid_table[pid & pid_tbl_mask];
1175
1176 KASSERT(pt->pt_pid == pid);
1177 KASSERT(PT_IS_LWP(pt->pt_slot));
1178 KASSERT(PT_GET_LWP(pt->pt_slot)->l_proc == p);
1179
1180 pt->pt_slot = PT_SET_PROC(p);
1181
1182 rw_exit(&pid_table_lock);
1183 return;
1184 }
1185 proc_free_pid_internal(pid, PT_F_LWP);
1186 }
1187
1188 void
1189 proc_free_mem(struct proc *p)
1190 {
1191
1192 kdtrace_proc_dtor(NULL, p);
1193 pool_cache_put(proc_cache, p);
1194 }
1195
1196 /*
1197 * proc_enterpgrp: move p to a new or existing process group (and session).
1198 *
1199 * If we are creating a new pgrp, the pgid should equal
1200 * the calling process' pid.
1201 * If is only valid to enter a process group that is in the session
1202 * of the process.
1203 * Also mksess should only be set if we are creating a process group
1204 *
1205 * Only called from sys_setsid, sys_setpgid and posix_spawn/spawn_return.
1206 */
1207 int
1208 proc_enterpgrp(struct proc *curp, pid_t pid, pid_t pgid, bool mksess)
1209 {
1210 struct pgrp *new_pgrp, *pgrp;
1211 struct session *sess;
1212 struct proc *p;
1213 int rval;
1214 pid_t pg_id = NO_PGID;
1215
1216 sess = mksess ? kmem_alloc(sizeof(*sess), KM_SLEEP) : NULL;
1217
1218 /* Allocate data areas we might need before doing any validity checks */
1219 rw_enter(&pid_table_lock, RW_READER);/* Because pid_table might change */
1220 if (pid_table[pgid & pid_tbl_mask].pt_pgrp == 0) {
1221 rw_exit(&pid_table_lock);
1222 new_pgrp = kmem_alloc(sizeof(*new_pgrp), KM_SLEEP);
1223 } else {
1224 rw_exit(&pid_table_lock);
1225 new_pgrp = NULL;
1226 }
1227 mutex_enter(proc_lock);
1228 rw_enter(&pid_table_lock, RW_WRITER);
1229 rval = EPERM; /* most common error (to save typing) */
1230
1231 /* Check pgrp exists or can be created */
1232 pgrp = pid_table[pgid & pid_tbl_mask].pt_pgrp;
1233 if (pgrp != NULL && pgrp->pg_id != pgid)
1234 goto done;
1235
1236 /* Can only set another process under restricted circumstances. */
1237 if (pid != curp->p_pid) {
1238 /* Must exist and be one of our children... */
1239 p = proc_find_pid_table_locked(pid, false);
1240 if (p == NULL || !p_inferior(p, curp)) {
1241 rval = ESRCH;
1242 goto done;
1243 }
1244 /* ... in the same session... */
1245 if (sess != NULL || p->p_session != curp->p_session)
1246 goto done;
1247 /* ... existing pgid must be in same session ... */
1248 if (pgrp != NULL && pgrp->pg_session != p->p_session)
1249 goto done;
1250 /* ... and not done an exec. */
1251 if (p->p_flag & PK_EXEC) {
1252 rval = EACCES;
1253 goto done;
1254 }
1255 } else {
1256 /* ... setsid() cannot re-enter a pgrp */
1257 if (mksess && (curp->p_pgid == curp->p_pid ||
1258 pgrp_find_pid_table_locked(curp->p_pid)))
1259 goto done;
1260 p = curp;
1261 }
1262
1263 /* Changing the process group/session of a session
1264 leader is definitely off limits. */
1265 if (SESS_LEADER(p)) {
1266 if (sess == NULL && p->p_pgrp == pgrp)
1267 /* unless it's a definite noop */
1268 rval = 0;
1269 goto done;
1270 }
1271
1272 /* Can only create a process group with id of process */
1273 if (pgrp == NULL && pgid != pid)
1274 goto done;
1275
1276 /* Can only create a session if creating pgrp */
1277 if (sess != NULL && pgrp != NULL)
1278 goto done;
1279
1280 /* Check we allocated memory for a pgrp... */
1281 if (pgrp == NULL && new_pgrp == NULL)
1282 goto done;
1283
1284 /* Don't attach to 'zombie' pgrp */
1285 if (pgrp != NULL && LIST_EMPTY(&pgrp->pg_members))
1286 goto done;
1287
1288 /* Expect to succeed now */
1289 rval = 0;
1290
1291 if (pgrp == p->p_pgrp)
1292 /* nothing to do */
1293 goto done;
1294
1295 /* Ok all setup, link up required structures */
1296
1297 if (pgrp == NULL) {
1298 pgrp = new_pgrp;
1299 new_pgrp = NULL;
1300 if (sess != NULL) {
1301 sess->s_sid = p->p_pid;
1302 sess->s_leader = p;
1303 sess->s_count = 1;
1304 sess->s_ttyvp = NULL;
1305 sess->s_ttyp = NULL;
1306 sess->s_flags = p->p_session->s_flags & ~S_LOGIN_SET;
1307 memcpy(sess->s_login, p->p_session->s_login,
1308 sizeof(sess->s_login));
1309 p->p_lflag &= ~PL_CONTROLT;
1310 } else {
1311 sess = p->p_pgrp->pg_session;
1312 proc_sesshold(sess);
1313 }
1314 pgrp->pg_session = sess;
1315 sess = NULL;
1316
1317 pgrp->pg_id = pgid;
1318 LIST_INIT(&pgrp->pg_members);
1319 #ifdef DIAGNOSTIC
1320 if (__predict_false(pid_table[pgid & pid_tbl_mask].pt_pgrp))
1321 panic("enterpgrp: pgrp table slot in use");
1322 if (__predict_false(mksess && p != curp))
1323 panic("enterpgrp: mksession and p != curproc");
1324 #endif
1325 pid_table[pgid & pid_tbl_mask].pt_pgrp = pgrp;
1326 pgrp->pg_jobc = 0;
1327 }
1328
1329 /*
1330 * Adjust eligibility of affected pgrps to participate in job control.
1331 * Increment eligibility counts before decrementing, otherwise we
1332 * could reach 0 spuriously during the first call.
1333 */
1334 fixjobc(p, pgrp, 1);
1335 fixjobc(p, p->p_pgrp, 0);
1336
1337 /* Interlock with ttread(). */
1338 mutex_spin_enter(&tty_lock);
1339
1340 /* Move process to requested group. */
1341 LIST_REMOVE(p, p_pglist);
1342 if (LIST_EMPTY(&p->p_pgrp->pg_members))
1343 /* defer delete until we've dumped the lock */
1344 pg_id = p->p_pgrp->pg_id;
1345 p->p_pgrp = pgrp;
1346 LIST_INSERT_HEAD(&pgrp->pg_members, p, p_pglist);
1347
1348 /* Done with the swap; we can release the tty mutex. */
1349 mutex_spin_exit(&tty_lock);
1350
1351 done:
1352 rw_exit(&pid_table_lock);
1353 if (pg_id != NO_PGID) {
1354 /* Releases proc_lock. */
1355 pg_delete(pg_id);
1356 } else {
1357 mutex_exit(proc_lock);
1358 }
1359 if (sess != NULL)
1360 kmem_free(sess, sizeof(*sess));
1361 if (new_pgrp != NULL)
1362 kmem_free(new_pgrp, sizeof(*new_pgrp));
1363 #ifdef DEBUG_PGRP
1364 if (__predict_false(rval))
1365 printf("enterpgrp(%d,%d,%d), curproc %d, rval %d\n",
1366 pid, pgid, mksess, curp->p_pid, rval);
1367 #endif
1368 return rval;
1369 }
1370
1371 /*
1372 * proc_leavepgrp: remove a process from its process group.
1373 * => must be called with the proc_lock held, which will be released;
1374 */
1375 void
1376 proc_leavepgrp(struct proc *p)
1377 {
1378 struct pgrp *pgrp;
1379
1380 KASSERT(mutex_owned(proc_lock));
1381
1382 /* Interlock with ttread() */
1383 mutex_spin_enter(&tty_lock);
1384 pgrp = p->p_pgrp;
1385 LIST_REMOVE(p, p_pglist);
1386 p->p_pgrp = NULL;
1387 mutex_spin_exit(&tty_lock);
1388
1389 if (LIST_EMPTY(&pgrp->pg_members)) {
1390 /* Releases proc_lock. */
1391 pg_delete(pgrp->pg_id);
1392 } else {
1393 mutex_exit(proc_lock);
1394 }
1395 }
1396
1397 /*
1398 * pg_remove: remove a process group from the table.
1399 * => must be called with the proc_lock held;
1400 * => returns process group to free;
1401 */
1402 static struct pgrp *
1403 pg_remove(pid_t pg_id)
1404 {
1405 struct pgrp *pgrp;
1406 struct pid_table *pt;
1407
1408 KASSERT(mutex_owned(proc_lock));
1409 KASSERT(rw_write_held(&pid_table_lock));
1410
1411 pt = &pid_table[pg_id & pid_tbl_mask];
1412 pgrp = pt->pt_pgrp;
1413
1414 KASSERT(pgrp != NULL);
1415 KASSERT(pgrp->pg_id == pg_id);
1416 KASSERT(LIST_EMPTY(&pgrp->pg_members));
1417
1418 pt->pt_pgrp = NULL;
1419
1420 if (!PT_VALID(pt->pt_slot)) {
1421 /* Orphaned pgrp, put slot onto free list. */
1422 KASSERT((PT_NEXT(pt->pt_slot) & pid_tbl_mask) == 0);
1423 pg_id &= pid_tbl_mask;
1424 pt = &pid_table[last_free_pt];
1425 pt->pt_slot = PT_SET_FREE(PT_NEXT(pt->pt_slot) | pg_id);
1426 KASSERT(pt->pt_pid == 0);
1427 last_free_pt = pg_id;
1428 pid_alloc_cnt--;
1429 }
1430 return pgrp;
1431 }
1432
1433 /*
1434 * pg_delete: delete and free a process group.
1435 * => must be called with the proc_lock held, which will be released.
1436 */
1437 static void
1438 pg_delete(pid_t pg_id)
1439 {
1440 struct pgrp *pg;
1441 struct tty *ttyp;
1442 struct session *ss;
1443
1444 KASSERT(mutex_owned(proc_lock));
1445
1446 rw_enter(&pid_table_lock, RW_WRITER);
1447 pg = pid_table[pg_id & pid_tbl_mask].pt_pgrp;
1448 if (pg == NULL || pg->pg_id != pg_id || !LIST_EMPTY(&pg->pg_members)) {
1449 rw_exit(&pid_table_lock);
1450 mutex_exit(proc_lock);
1451 return;
1452 }
1453
1454 ss = pg->pg_session;
1455
1456 /* Remove reference (if any) from tty to this process group */
1457 mutex_spin_enter(&tty_lock);
1458 ttyp = ss->s_ttyp;
1459 if (ttyp != NULL && ttyp->t_pgrp == pg) {
1460 ttyp->t_pgrp = NULL;
1461 KASSERT(ttyp->t_session == ss);
1462 }
1463 mutex_spin_exit(&tty_lock);
1464
1465 /*
1466 * The leading process group in a session is freed by
1467 * proc_sessrele_pid_table_write_locked(), if last
1468 * reference. It will also release the locks.
1469 */
1470 pg = (ss->s_sid != pg->pg_id) ? pg_remove(pg_id) : NULL;
1471 proc_sessrele_pid_table_write_locked(ss);
1472
1473 if (pg != NULL) {
1474 /* Free it, if was not done above. */
1475 kmem_free(pg, sizeof(struct pgrp));
1476 }
1477 }
1478
1479 /*
1480 * Adjust pgrp jobc counters when specified process changes process group.
1481 * We count the number of processes in each process group that "qualify"
1482 * the group for terminal job control (those with a parent in a different
1483 * process group of the same session). If that count reaches zero, the
1484 * process group becomes orphaned. Check both the specified process'
1485 * process group and that of its children.
1486 * entering == 0 => p is leaving specified group.
1487 * entering == 1 => p is entering specified group.
1488 *
1489 * Call with proc_lock held.
1490 */
1491 void
1492 fixjobc(struct proc *p, struct pgrp *pgrp, int entering)
1493 {
1494 struct pgrp *hispgrp;
1495 struct session *mysession = pgrp->pg_session;
1496 struct proc *child;
1497
1498 KASSERT(mutex_owned(proc_lock));
1499
1500 /*
1501 * Check p's parent to see whether p qualifies its own process
1502 * group; if so, adjust count for p's process group.
1503 */
1504 hispgrp = p->p_pptr->p_pgrp;
1505 if (hispgrp != pgrp && hispgrp->pg_session == mysession) {
1506 if (entering) {
1507 pgrp->pg_jobc++;
1508 p->p_lflag &= ~PL_ORPHANPG;
1509 } else {
1510 KASSERT(pgrp->pg_jobc > 0);
1511 if (--pgrp->pg_jobc == 0)
1512 orphanpg(pgrp);
1513 }
1514 }
1515
1516 /*
1517 * Check this process' children to see whether they qualify
1518 * their process groups; if so, adjust counts for children's
1519 * process groups.
1520 */
1521 LIST_FOREACH(child, &p->p_children, p_sibling) {
1522 hispgrp = child->p_pgrp;
1523 if (hispgrp != pgrp && hispgrp->pg_session == mysession &&
1524 !P_ZOMBIE(child)) {
1525 if (entering) {
1526 child->p_lflag &= ~PL_ORPHANPG;
1527 hispgrp->pg_jobc++;
1528 } else {
1529 KASSERT(hispgrp->pg_jobc > 0);
1530 if (--hispgrp->pg_jobc == 0)
1531 orphanpg(hispgrp);
1532 }
1533 }
1534 }
1535 }
1536
1537 /*
1538 * A process group has become orphaned;
1539 * if there are any stopped processes in the group,
1540 * hang-up all process in that group.
1541 *
1542 * Call with proc_lock held.
1543 */
1544 static void
1545 orphanpg(struct pgrp *pg)
1546 {
1547 struct proc *p;
1548
1549 KASSERT(mutex_owned(proc_lock));
1550
1551 LIST_FOREACH(p, &pg->pg_members, p_pglist) {
1552 if (p->p_stat == SSTOP) {
1553 p->p_lflag |= PL_ORPHANPG;
1554 psignal(p, SIGHUP);
1555 psignal(p, SIGCONT);
1556 }
1557 }
1558 }
1559
1560 #ifdef DDB
1561 #include <ddb/db_output.h>
1562 void pidtbl_dump(void);
1563 void
1564 pidtbl_dump(void)
1565 {
1566 struct pid_table *pt;
1567 struct proc *p;
1568 struct pgrp *pgrp;
1569 uintptr_t slot;
1570 int id;
1571
1572 db_printf("pid table %p size %x, next %x, last %x\n",
1573 pid_table, pid_tbl_mask+1,
1574 next_free_pt, last_free_pt);
1575 for (pt = pid_table, id = 0; id <= pid_tbl_mask; id++, pt++) {
1576 slot = pt->pt_slot;
1577 if (!PT_VALID(slot) && !pt->pt_pgrp)
1578 continue;
1579 if (PT_IS_LWP(slot)) {
1580 p = PT_GET_LWP(slot)->l_proc;
1581 } else if (PT_IS_PROC(slot)) {
1582 p = PT_GET_PROC(slot);
1583 } else {
1584 p = NULL;
1585 }
1586 db_printf(" id %x: ", id);
1587 if (p != NULL)
1588 db_printf("slotpid %d proc %p id %d (0x%x) %s\n",
1589 pt->pt_pid, p, p->p_pid, p->p_pid, p->p_comm);
1590 else
1591 db_printf("next %x use %x\n",
1592 PT_NEXT(slot) & pid_tbl_mask,
1593 PT_NEXT(slot) & ~pid_tbl_mask);
1594 if ((pgrp = pt->pt_pgrp)) {
1595 db_printf("\tsession %p, sid %d, count %d, login %s\n",
1596 pgrp->pg_session, pgrp->pg_session->s_sid,
1597 pgrp->pg_session->s_count,
1598 pgrp->pg_session->s_login);
1599 db_printf("\tpgrp %p, pg_id %d, pg_jobc %d, members %p\n",
1600 pgrp, pgrp->pg_id, pgrp->pg_jobc,
1601 LIST_FIRST(&pgrp->pg_members));
1602 LIST_FOREACH(p, &pgrp->pg_members, p_pglist) {
1603 db_printf("\t\tpid %d addr %p pgrp %p %s\n",
1604 p->p_pid, p, p->p_pgrp, p->p_comm);
1605 }
1606 }
1607 }
1608 }
1609 #endif /* DDB */
1610
1611 #ifdef KSTACK_CHECK_MAGIC
1612
1613 #define KSTACK_MAGIC 0xdeadbeaf
1614
1615 /* XXX should be per process basis? */
1616 static int kstackleftmin = KSTACK_SIZE;
1617 static int kstackleftthres = KSTACK_SIZE / 8;
1618
1619 void
1620 kstack_setup_magic(const struct lwp *l)
1621 {
1622 uint32_t *ip;
1623 uint32_t const *end;
1624
1625 KASSERT(l != NULL);
1626 KASSERT(l != &lwp0);
1627
1628 /*
1629 * fill all the stack with magic number
1630 * so that later modification on it can be detected.
1631 */
1632 ip = (uint32_t *)KSTACK_LOWEST_ADDR(l);
1633 end = (uint32_t *)((char *)KSTACK_LOWEST_ADDR(l) + KSTACK_SIZE);
1634 for (; ip < end; ip++) {
1635 *ip = KSTACK_MAGIC;
1636 }
1637 }
1638
1639 void
1640 kstack_check_magic(const struct lwp *l)
1641 {
1642 uint32_t const *ip, *end;
1643 int stackleft;
1644
1645 KASSERT(l != NULL);
1646
1647 /* don't check proc0 */ /*XXX*/
1648 if (l == &lwp0)
1649 return;
1650
1651 #ifdef __MACHINE_STACK_GROWS_UP
1652 /* stack grows upwards (eg. hppa) */
1653 ip = (uint32_t *)((void *)KSTACK_LOWEST_ADDR(l) + KSTACK_SIZE);
1654 end = (uint32_t *)KSTACK_LOWEST_ADDR(l);
1655 for (ip--; ip >= end; ip--)
1656 if (*ip != KSTACK_MAGIC)
1657 break;
1658
1659 stackleft = (void *)KSTACK_LOWEST_ADDR(l) + KSTACK_SIZE - (void *)ip;
1660 #else /* __MACHINE_STACK_GROWS_UP */
1661 /* stack grows downwards (eg. i386) */
1662 ip = (uint32_t *)KSTACK_LOWEST_ADDR(l);
1663 end = (uint32_t *)((char *)KSTACK_LOWEST_ADDR(l) + KSTACK_SIZE);
1664 for (; ip < end; ip++)
1665 if (*ip != KSTACK_MAGIC)
1666 break;
1667
1668 stackleft = ((const char *)ip) - (const char *)KSTACK_LOWEST_ADDR(l);
1669 #endif /* __MACHINE_STACK_GROWS_UP */
1670
1671 if (kstackleftmin > stackleft) {
1672 kstackleftmin = stackleft;
1673 if (stackleft < kstackleftthres)
1674 printf("warning: kernel stack left %d bytes"
1675 "(pid %u:lid %u)\n", stackleft,
1676 (u_int)l->l_proc->p_pid, (u_int)l->l_lid);
1677 }
1678
1679 if (stackleft <= 0) {
1680 panic("magic on the top of kernel stack changed for "
1681 "pid %u, lid %u: maybe kernel stack overflow",
1682 (u_int)l->l_proc->p_pid, (u_int)l->l_lid);
1683 }
1684 }
1685 #endif /* KSTACK_CHECK_MAGIC */
1686
1687 int
1688 proclist_foreach_call(struct proclist *list,
1689 int (*callback)(struct proc *, void *arg), void *arg)
1690 {
1691 struct proc marker;
1692 struct proc *p;
1693 int ret = 0;
1694
1695 marker.p_flag = PK_MARKER;
1696 mutex_enter(proc_lock);
1697 for (p = LIST_FIRST(list); ret == 0 && p != NULL;) {
1698 if (p->p_flag & PK_MARKER) {
1699 p = LIST_NEXT(p, p_list);
1700 continue;
1701 }
1702 LIST_INSERT_AFTER(p, &marker, p_list);
1703 ret = (*callback)(p, arg);
1704 KASSERT(mutex_owned(proc_lock));
1705 p = LIST_NEXT(&marker, p_list);
1706 LIST_REMOVE(&marker, p_list);
1707 }
1708 mutex_exit(proc_lock);
1709
1710 return ret;
1711 }
1712
1713 int
1714 proc_vmspace_getref(struct proc *p, struct vmspace **vm)
1715 {
1716
1717 /* XXXCDC: how should locking work here? */
1718
1719 /* curproc exception is for coredump. */
1720
1721 if ((p != curproc && (p->p_sflag & PS_WEXIT) != 0) ||
1722 (p->p_vmspace->vm_refcnt < 1)) { /* XXX */
1723 return EFAULT;
1724 }
1725
1726 uvmspace_addref(p->p_vmspace);
1727 *vm = p->p_vmspace;
1728
1729 return 0;
1730 }
1731
1732 /*
1733 * Acquire a write lock on the process credential.
1734 */
1735 void
1736 proc_crmod_enter(void)
1737 {
1738 struct lwp *l = curlwp;
1739 struct proc *p = l->l_proc;
1740 kauth_cred_t oc;
1741
1742 /* Reset what needs to be reset in plimit. */
1743 if (p->p_limit->pl_corename != defcorename) {
1744 lim_setcorename(p, defcorename, 0);
1745 }
1746
1747 mutex_enter(p->p_lock);
1748
1749 /* Ensure the LWP cached credentials are up to date. */
1750 if ((oc = l->l_cred) != p->p_cred) {
1751 kauth_cred_hold(p->p_cred);
1752 l->l_cred = p->p_cred;
1753 kauth_cred_free(oc);
1754 }
1755 }
1756
1757 /*
1758 * Set in a new process credential, and drop the write lock. The credential
1759 * must have a reference already. Optionally, free a no-longer required
1760 * credential. The scheduler also needs to inspect p_cred, so we also
1761 * briefly acquire the sched state mutex.
1762 */
1763 void
1764 proc_crmod_leave(kauth_cred_t scred, kauth_cred_t fcred, bool sugid)
1765 {
1766 struct lwp *l = curlwp, *l2;
1767 struct proc *p = l->l_proc;
1768 kauth_cred_t oc;
1769
1770 KASSERT(mutex_owned(p->p_lock));
1771
1772 /* Is there a new credential to set in? */
1773 if (scred != NULL) {
1774 p->p_cred = scred;
1775 LIST_FOREACH(l2, &p->p_lwps, l_sibling) {
1776 if (l2 != l)
1777 l2->l_prflag |= LPR_CRMOD;
1778 }
1779
1780 /* Ensure the LWP cached credentials are up to date. */
1781 if ((oc = l->l_cred) != scred) {
1782 kauth_cred_hold(scred);
1783 l->l_cred = scred;
1784 }
1785 } else
1786 oc = NULL; /* XXXgcc */
1787
1788 if (sugid) {
1789 /*
1790 * Mark process as having changed credentials, stops
1791 * tracing etc.
1792 */
1793 p->p_flag |= PK_SUGID;
1794 }
1795
1796 mutex_exit(p->p_lock);
1797
1798 /* If there is a credential to be released, free it now. */
1799 if (fcred != NULL) {
1800 KASSERT(scred != NULL);
1801 kauth_cred_free(fcred);
1802 if (oc != scred)
1803 kauth_cred_free(oc);
1804 }
1805 }
1806
1807 /*
1808 * proc_specific_key_create --
1809 * Create a key for subsystem proc-specific data.
1810 */
1811 int
1812 proc_specific_key_create(specificdata_key_t *keyp, specificdata_dtor_t dtor)
1813 {
1814
1815 return (specificdata_key_create(proc_specificdata_domain, keyp, dtor));
1816 }
1817
1818 /*
1819 * proc_specific_key_delete --
1820 * Delete a key for subsystem proc-specific data.
1821 */
1822 void
1823 proc_specific_key_delete(specificdata_key_t key)
1824 {
1825
1826 specificdata_key_delete(proc_specificdata_domain, key);
1827 }
1828
1829 /*
1830 * proc_initspecific --
1831 * Initialize a proc's specificdata container.
1832 */
1833 void
1834 proc_initspecific(struct proc *p)
1835 {
1836 int error __diagused;
1837
1838 error = specificdata_init(proc_specificdata_domain, &p->p_specdataref);
1839 KASSERT(error == 0);
1840 }
1841
1842 /*
1843 * proc_finispecific --
1844 * Finalize a proc's specificdata container.
1845 */
1846 void
1847 proc_finispecific(struct proc *p)
1848 {
1849
1850 specificdata_fini(proc_specificdata_domain, &p->p_specdataref);
1851 }
1852
1853 /*
1854 * proc_getspecific --
1855 * Return proc-specific data corresponding to the specified key.
1856 */
1857 void *
1858 proc_getspecific(struct proc *p, specificdata_key_t key)
1859 {
1860
1861 return (specificdata_getspecific(proc_specificdata_domain,
1862 &p->p_specdataref, key));
1863 }
1864
1865 /*
1866 * proc_setspecific --
1867 * Set proc-specific data corresponding to the specified key.
1868 */
1869 void
1870 proc_setspecific(struct proc *p, specificdata_key_t key, void *data)
1871 {
1872
1873 specificdata_setspecific(proc_specificdata_domain,
1874 &p->p_specdataref, key, data);
1875 }
1876
1877 int
1878 proc_uidmatch(kauth_cred_t cred, kauth_cred_t target)
1879 {
1880 int r = 0;
1881
1882 if (kauth_cred_getuid(cred) != kauth_cred_getuid(target) ||
1883 kauth_cred_getuid(cred) != kauth_cred_getsvuid(target)) {
1884 /*
1885 * suid proc of ours or proc not ours
1886 */
1887 r = EPERM;
1888 } else if (kauth_cred_getgid(target) != kauth_cred_getsvgid(target)) {
1889 /*
1890 * sgid proc has sgid back to us temporarily
1891 */
1892 r = EPERM;
1893 } else {
1894 /*
1895 * our rgid must be in target's group list (ie,
1896 * sub-processes started by a sgid process)
1897 */
1898 int ismember = 0;
1899
1900 if (kauth_cred_ismember_gid(cred,
1901 kauth_cred_getgid(target), &ismember) != 0 ||
1902 !ismember)
1903 r = EPERM;
1904 }
1905
1906 return (r);
1907 }
1908
1909 /*
1910 * sysctl stuff
1911 */
1912
1913 #define KERN_PROCSLOP (5 * sizeof(struct kinfo_proc))
1914
1915 static const u_int sysctl_flagmap[] = {
1916 PK_ADVLOCK, P_ADVLOCK,
1917 PK_EXEC, P_EXEC,
1918 PK_NOCLDWAIT, P_NOCLDWAIT,
1919 PK_32, P_32,
1920 PK_CLDSIGIGN, P_CLDSIGIGN,
1921 PK_SUGID, P_SUGID,
1922 0
1923 };
1924
1925 static const u_int sysctl_sflagmap[] = {
1926 PS_NOCLDSTOP, P_NOCLDSTOP,
1927 PS_WEXIT, P_WEXIT,
1928 PS_STOPFORK, P_STOPFORK,
1929 PS_STOPEXEC, P_STOPEXEC,
1930 PS_STOPEXIT, P_STOPEXIT,
1931 0
1932 };
1933
1934 static const u_int sysctl_slflagmap[] = {
1935 PSL_TRACED, P_TRACED,
1936 PSL_CHTRACED, P_CHTRACED,
1937 PSL_SYSCALL, P_SYSCALL,
1938 0
1939 };
1940
1941 static const u_int sysctl_lflagmap[] = {
1942 PL_CONTROLT, P_CONTROLT,
1943 PL_PPWAIT, P_PPWAIT,
1944 0
1945 };
1946
1947 static const u_int sysctl_stflagmap[] = {
1948 PST_PROFIL, P_PROFIL,
1949 0
1950
1951 };
1952
1953 /* used by kern_lwp also */
1954 const u_int sysctl_lwpflagmap[] = {
1955 LW_SINTR, L_SINTR,
1956 LW_SYSTEM, L_SYSTEM,
1957 0
1958 };
1959
1960 /*
1961 * Find the most ``active'' lwp of a process and return it for ps display
1962 * purposes
1963 */
1964 static struct lwp *
1965 proc_active_lwp(struct proc *p)
1966 {
1967 static const int ostat[] = {
1968 0,
1969 2, /* LSIDL */
1970 6, /* LSRUN */
1971 5, /* LSSLEEP */
1972 4, /* LSSTOP */
1973 0, /* LSZOMB */
1974 1, /* LSDEAD */
1975 7, /* LSONPROC */
1976 3 /* LSSUSPENDED */
1977 };
1978
1979 struct lwp *l, *lp = NULL;
1980 LIST_FOREACH(l, &p->p_lwps, l_sibling) {
1981 KASSERT(l->l_stat >= 0 && l->l_stat < __arraycount(ostat));
1982 if (lp == NULL ||
1983 ostat[l->l_stat] > ostat[lp->l_stat] ||
1984 (ostat[l->l_stat] == ostat[lp->l_stat] &&
1985 l->l_cpticks > lp->l_cpticks)) {
1986 lp = l;
1987 continue;
1988 }
1989 }
1990 return lp;
1991 }
1992
1993 static int
1994 sysctl_doeproc(SYSCTLFN_ARGS)
1995 {
1996 union {
1997 struct kinfo_proc kproc;
1998 struct kinfo_proc2 kproc2;
1999 } *kbuf;
2000 struct proc *p, *next, *marker;
2001 char *where, *dp;
2002 int type, op, arg, error;
2003 u_int elem_size, kelem_size, elem_count;
2004 size_t buflen, needed;
2005 bool match, zombie, mmmbrains;
2006 const bool allowaddr = get_expose_address(curproc);
2007
2008 if (namelen == 1 && name[0] == CTL_QUERY)
2009 return (sysctl_query(SYSCTLFN_CALL(rnode)));
2010
2011 dp = where = oldp;
2012 buflen = where != NULL ? *oldlenp : 0;
2013 error = 0;
2014 needed = 0;
2015 type = rnode->sysctl_num;
2016
2017 if (type == KERN_PROC) {
2018 if (namelen == 0)
2019 return EINVAL;
2020 switch (op = name[0]) {
2021 case KERN_PROC_ALL:
2022 if (namelen != 1)
2023 return EINVAL;
2024 arg = 0;
2025 break;
2026 default:
2027 if (namelen != 2)
2028 return EINVAL;
2029 arg = name[1];
2030 break;
2031 }
2032 elem_count = 0; /* Hush little compiler, don't you cry */
2033 kelem_size = elem_size = sizeof(kbuf->kproc);
2034 } else {
2035 if (namelen != 4)
2036 return EINVAL;
2037 op = name[0];
2038 arg = name[1];
2039 elem_size = name[2];
2040 elem_count = name[3];
2041 kelem_size = sizeof(kbuf->kproc2);
2042 }
2043
2044 sysctl_unlock();
2045
2046 kbuf = kmem_zalloc(sizeof(*kbuf), KM_SLEEP);
2047 marker = kmem_alloc(sizeof(*marker), KM_SLEEP);
2048 marker->p_flag = PK_MARKER;
2049
2050 mutex_enter(proc_lock);
2051 /*
2052 * Start with zombies to prevent reporting processes twice, in case they
2053 * are dying and being moved from the list of alive processes to zombies.
2054 */
2055 mmmbrains = true;
2056 for (p = LIST_FIRST(&zombproc);; p = next) {
2057 if (p == NULL) {
2058 if (mmmbrains) {
2059 p = LIST_FIRST(&allproc);
2060 mmmbrains = false;
2061 }
2062 if (p == NULL)
2063 break;
2064 }
2065 next = LIST_NEXT(p, p_list);
2066 if ((p->p_flag & PK_MARKER) != 0)
2067 continue;
2068
2069 /*
2070 * Skip embryonic processes.
2071 */
2072 if (p->p_stat == SIDL)
2073 continue;
2074
2075 mutex_enter(p->p_lock);
2076 error = kauth_authorize_process(l->l_cred,
2077 KAUTH_PROCESS_CANSEE, p,
2078 KAUTH_ARG(KAUTH_REQ_PROCESS_CANSEE_EPROC), NULL, NULL);
2079 if (error != 0) {
2080 mutex_exit(p->p_lock);
2081 continue;
2082 }
2083
2084 /*
2085 * Hande all the operations in one switch on the cost of
2086 * algorithm complexity is on purpose. The win splitting this
2087 * function into several similar copies makes maintenance burden
2088 * burden, code grow and boost is neglible in practical systems.
2089 */
2090 switch (op) {
2091 case KERN_PROC_PID:
2092 match = (p->p_pid == (pid_t)arg);
2093 break;
2094
2095 case KERN_PROC_PGRP:
2096 match = (p->p_pgrp->pg_id == (pid_t)arg);
2097 break;
2098
2099 case KERN_PROC_SESSION:
2100 match = (p->p_session->s_sid == (pid_t)arg);
2101 break;
2102
2103 case KERN_PROC_TTY:
2104 match = true;
2105 if (arg == (int) KERN_PROC_TTY_REVOKE) {
2106 if ((p->p_lflag & PL_CONTROLT) == 0 ||
2107 p->p_session->s_ttyp == NULL ||
2108 p->p_session->s_ttyvp != NULL) {
2109 match = false;
2110 }
2111 } else if ((p->p_lflag & PL_CONTROLT) == 0 ||
2112 p->p_session->s_ttyp == NULL) {
2113 if ((dev_t)arg != KERN_PROC_TTY_NODEV) {
2114 match = false;
2115 }
2116 } else if (p->p_session->s_ttyp->t_dev != (dev_t)arg) {
2117 match = false;
2118 }
2119 break;
2120
2121 case KERN_PROC_UID:
2122 match = (kauth_cred_geteuid(p->p_cred) == (uid_t)arg);
2123 break;
2124
2125 case KERN_PROC_RUID:
2126 match = (kauth_cred_getuid(p->p_cred) == (uid_t)arg);
2127 break;
2128
2129 case KERN_PROC_GID:
2130 match = (kauth_cred_getegid(p->p_cred) == (uid_t)arg);
2131 break;
2132
2133 case KERN_PROC_RGID:
2134 match = (kauth_cred_getgid(p->p_cred) == (uid_t)arg);
2135 break;
2136
2137 case KERN_PROC_ALL:
2138 match = true;
2139 /* allow everything */
2140 break;
2141
2142 default:
2143 error = EINVAL;
2144 mutex_exit(p->p_lock);
2145 goto cleanup;
2146 }
2147 if (!match) {
2148 mutex_exit(p->p_lock);
2149 continue;
2150 }
2151
2152 /*
2153 * Grab a hold on the process.
2154 */
2155 if (mmmbrains) {
2156 zombie = true;
2157 } else {
2158 zombie = !rw_tryenter(&p->p_reflock, RW_READER);
2159 }
2160 if (zombie) {
2161 LIST_INSERT_AFTER(p, marker, p_list);
2162 }
2163
2164 if (buflen >= elem_size &&
2165 (type == KERN_PROC || elem_count > 0)) {
2166 ruspace(p); /* Update process vm resource use */
2167
2168 if (type == KERN_PROC) {
2169 fill_proc(p, &kbuf->kproc.kp_proc, allowaddr);
2170 fill_eproc(p, &kbuf->kproc.kp_eproc, zombie,
2171 allowaddr);
2172 } else {
2173 fill_kproc2(p, &kbuf->kproc2, zombie,
2174 allowaddr);
2175 elem_count--;
2176 }
2177 mutex_exit(p->p_lock);
2178 mutex_exit(proc_lock);
2179 /*
2180 * Copy out elem_size, but not larger than kelem_size
2181 */
2182 error = sysctl_copyout(l, kbuf, dp,
2183 uimin(kelem_size, elem_size));
2184 mutex_enter(proc_lock);
2185 if (error) {
2186 goto bah;
2187 }
2188 dp += elem_size;
2189 buflen -= elem_size;
2190 } else {
2191 mutex_exit(p->p_lock);
2192 }
2193 needed += elem_size;
2194
2195 /*
2196 * Release reference to process.
2197 */
2198 if (zombie) {
2199 next = LIST_NEXT(marker, p_list);
2200 LIST_REMOVE(marker, p_list);
2201 } else {
2202 rw_exit(&p->p_reflock);
2203 next = LIST_NEXT(p, p_list);
2204 }
2205
2206 /*
2207 * Short-circuit break quickly!
2208 */
2209 if (op == KERN_PROC_PID)
2210 break;
2211 }
2212 mutex_exit(proc_lock);
2213
2214 if (where != NULL) {
2215 *oldlenp = dp - where;
2216 if (needed > *oldlenp) {
2217 error = ENOMEM;
2218 goto out;
2219 }
2220 } else {
2221 needed += KERN_PROCSLOP;
2222 *oldlenp = needed;
2223 }
2224 kmem_free(kbuf, sizeof(*kbuf));
2225 kmem_free(marker, sizeof(*marker));
2226 sysctl_relock();
2227 return 0;
2228 bah:
2229 if (zombie)
2230 LIST_REMOVE(marker, p_list);
2231 else
2232 rw_exit(&p->p_reflock);
2233 cleanup:
2234 mutex_exit(proc_lock);
2235 out:
2236 kmem_free(kbuf, sizeof(*kbuf));
2237 kmem_free(marker, sizeof(*marker));
2238 sysctl_relock();
2239 return error;
2240 }
2241
2242 int
2243 copyin_psstrings(struct proc *p, struct ps_strings *arginfo)
2244 {
2245 #if !defined(_RUMPKERNEL)
2246 int retval;
2247
2248 if (p->p_flag & PK_32) {
2249 MODULE_HOOK_CALL(kern_proc32_copyin_hook, (p, arginfo),
2250 enosys(), retval);
2251 return retval;
2252 }
2253 #endif /* !defined(_RUMPKERNEL) */
2254
2255 return copyin_proc(p, (void *)p->p_psstrp, arginfo, sizeof(*arginfo));
2256 }
2257
2258 static int
2259 copy_procargs_sysctl_cb(void *cookie_, const void *src, size_t off, size_t len)
2260 {
2261 void **cookie = cookie_;
2262 struct lwp *l = cookie[0];
2263 char *dst = cookie[1];
2264
2265 return sysctl_copyout(l, src, dst + off, len);
2266 }
2267
2268 /*
2269 * sysctl helper routine for kern.proc_args pseudo-subtree.
2270 */
2271 static int
2272 sysctl_kern_proc_args(SYSCTLFN_ARGS)
2273 {
2274 struct ps_strings pss;
2275 struct proc *p;
2276 pid_t pid;
2277 int type, error;
2278 void *cookie[2];
2279
2280 if (namelen == 1 && name[0] == CTL_QUERY)
2281 return (sysctl_query(SYSCTLFN_CALL(rnode)));
2282
2283 if (newp != NULL || namelen != 2)
2284 return (EINVAL);
2285 pid = name[0];
2286 type = name[1];
2287
2288 switch (type) {
2289 case KERN_PROC_PATHNAME:
2290 sysctl_unlock();
2291 error = fill_pathname(l, pid, oldp, oldlenp);
2292 sysctl_relock();
2293 return error;
2294
2295 case KERN_PROC_CWD:
2296 sysctl_unlock();
2297 error = fill_cwd(l, pid, oldp, oldlenp);
2298 sysctl_relock();
2299 return error;
2300
2301 case KERN_PROC_ARGV:
2302 case KERN_PROC_NARGV:
2303 case KERN_PROC_ENV:
2304 case KERN_PROC_NENV:
2305 /* ok */
2306 break;
2307 default:
2308 return (EINVAL);
2309 }
2310
2311 sysctl_unlock();
2312
2313 /* check pid */
2314 mutex_enter(proc_lock);
2315 if ((p = proc_find(pid)) == NULL) {
2316 error = EINVAL;
2317 goto out_locked;
2318 }
2319 mutex_enter(p->p_lock);
2320
2321 /* Check permission. */
2322 if (type == KERN_PROC_ARGV || type == KERN_PROC_NARGV)
2323 error = kauth_authorize_process(l->l_cred, KAUTH_PROCESS_CANSEE,
2324 p, KAUTH_ARG(KAUTH_REQ_PROCESS_CANSEE_ARGS), NULL, NULL);
2325 else if (type == KERN_PROC_ENV || type == KERN_PROC_NENV)
2326 error = kauth_authorize_process(l->l_cred, KAUTH_PROCESS_CANSEE,
2327 p, KAUTH_ARG(KAUTH_REQ_PROCESS_CANSEE_ENV), NULL, NULL);
2328 else
2329 error = EINVAL; /* XXXGCC */
2330 if (error) {
2331 mutex_exit(p->p_lock);
2332 goto out_locked;
2333 }
2334
2335 if (oldp == NULL) {
2336 if (type == KERN_PROC_NARGV || type == KERN_PROC_NENV)
2337 *oldlenp = sizeof (int);
2338 else
2339 *oldlenp = ARG_MAX; /* XXX XXX XXX */
2340 error = 0;
2341 mutex_exit(p->p_lock);
2342 goto out_locked;
2343 }
2344
2345 /*
2346 * Zombies don't have a stack, so we can't read their psstrings.
2347 * System processes also don't have a user stack.
2348 */
2349 if (P_ZOMBIE(p) || (p->p_flag & PK_SYSTEM) != 0) {
2350 error = EINVAL;
2351 mutex_exit(p->p_lock);
2352 goto out_locked;
2353 }
2354
2355 error = rw_tryenter(&p->p_reflock, RW_READER) ? 0 : EBUSY;
2356 mutex_exit(p->p_lock);
2357 if (error) {
2358 goto out_locked;
2359 }
2360 mutex_exit(proc_lock);
2361
2362 if (type == KERN_PROC_NARGV || type == KERN_PROC_NENV) {
2363 int value;
2364 if ((error = copyin_psstrings(p, &pss)) == 0) {
2365 if (type == KERN_PROC_NARGV)
2366 value = pss.ps_nargvstr;
2367 else
2368 value = pss.ps_nenvstr;
2369 error = sysctl_copyout(l, &value, oldp, sizeof(value));
2370 *oldlenp = sizeof(value);
2371 }
2372 } else {
2373 cookie[0] = l;
2374 cookie[1] = oldp;
2375 error = copy_procargs(p, type, oldlenp,
2376 copy_procargs_sysctl_cb, cookie);
2377 }
2378 rw_exit(&p->p_reflock);
2379 sysctl_relock();
2380 return error;
2381
2382 out_locked:
2383 mutex_exit(proc_lock);
2384 sysctl_relock();
2385 return error;
2386 }
2387
2388 int
2389 copy_procargs(struct proc *p, int oid, size_t *limit,
2390 int (*cb)(void *, const void *, size_t, size_t), void *cookie)
2391 {
2392 struct ps_strings pss;
2393 size_t len, i, loaded, entry_len;
2394 struct uio auio;
2395 struct iovec aiov;
2396 int error, argvlen;
2397 char *arg;
2398 char **argv;
2399 vaddr_t user_argv;
2400 struct vmspace *vmspace;
2401
2402 /*
2403 * Allocate a temporary buffer to hold the argument vector and
2404 * the arguments themselve.
2405 */
2406 arg = kmem_alloc(PAGE_SIZE, KM_SLEEP);
2407 argv = kmem_alloc(PAGE_SIZE, KM_SLEEP);
2408
2409 /*
2410 * Lock the process down in memory.
2411 */
2412 vmspace = p->p_vmspace;
2413 uvmspace_addref(vmspace);
2414
2415 /*
2416 * Read in the ps_strings structure.
2417 */
2418 if ((error = copyin_psstrings(p, &pss)) != 0)
2419 goto done;
2420
2421 /*
2422 * Now read the address of the argument vector.
2423 */
2424 switch (oid) {
2425 case KERN_PROC_ARGV:
2426 user_argv = (uintptr_t)pss.ps_argvstr;
2427 argvlen = pss.ps_nargvstr;
2428 break;
2429 case KERN_PROC_ENV:
2430 user_argv = (uintptr_t)pss.ps_envstr;
2431 argvlen = pss.ps_nenvstr;
2432 break;
2433 default:
2434 error = EINVAL;
2435 goto done;
2436 }
2437
2438 if (argvlen < 0) {
2439 error = EIO;
2440 goto done;
2441 }
2442
2443
2444 /*
2445 * Now copy each string.
2446 */
2447 len = 0; /* bytes written to user buffer */
2448 loaded = 0; /* bytes from argv already processed */
2449 i = 0; /* To make compiler happy */
2450 entry_len = PROC_PTRSZ(p);
2451
2452 for (; argvlen; --argvlen) {
2453 int finished = 0;
2454 vaddr_t base;
2455 size_t xlen;
2456 int j;
2457
2458 if (loaded == 0) {
2459 size_t rem = entry_len * argvlen;
2460 loaded = MIN(rem, PAGE_SIZE);
2461 error = copyin_vmspace(vmspace,
2462 (const void *)user_argv, argv, loaded);
2463 if (error)
2464 break;
2465 user_argv += loaded;
2466 i = 0;
2467 }
2468
2469 #if !defined(_RUMPKERNEL)
2470 if (p->p_flag & PK_32)
2471 MODULE_HOOK_CALL(kern_proc32_base_hook,
2472 (argv, i++), 0, base);
2473 else
2474 #endif /* !defined(_RUMPKERNEL) */
2475 base = (vaddr_t)argv[i++];
2476 loaded -= entry_len;
2477
2478 /*
2479 * The program has messed around with its arguments,
2480 * possibly deleting some, and replacing them with
2481 * NULL's. Treat this as the last argument and not
2482 * a failure.
2483 */
2484 if (base == 0)
2485 break;
2486
2487 while (!finished) {
2488 xlen = PAGE_SIZE - (base & PAGE_MASK);
2489
2490 aiov.iov_base = arg;
2491 aiov.iov_len = PAGE_SIZE;
2492 auio.uio_iov = &aiov;
2493 auio.uio_iovcnt = 1;
2494 auio.uio_offset = base;
2495 auio.uio_resid = xlen;
2496 auio.uio_rw = UIO_READ;
2497 UIO_SETUP_SYSSPACE(&auio);
2498 error = uvm_io(&vmspace->vm_map, &auio, 0);
2499 if (error)
2500 goto done;
2501
2502 /* Look for the end of the string */
2503 for (j = 0; j < xlen; j++) {
2504 if (arg[j] == '\0') {
2505 xlen = j + 1;
2506 finished = 1;
2507 break;
2508 }
2509 }
2510
2511 /* Check for user buffer overflow */
2512 if (len + xlen > *limit) {
2513 finished = 1;
2514 if (len > *limit)
2515 xlen = 0;
2516 else
2517 xlen = *limit - len;
2518 }
2519
2520 /* Copyout the page */
2521 error = (*cb)(cookie, arg, len, xlen);
2522 if (error)
2523 goto done;
2524
2525 len += xlen;
2526 base += xlen;
2527 }
2528 }
2529 *limit = len;
2530
2531 done:
2532 kmem_free(argv, PAGE_SIZE);
2533 kmem_free(arg, PAGE_SIZE);
2534 uvmspace_free(vmspace);
2535 return error;
2536 }
2537
2538 /*
2539 * Fill in a proc structure for the specified process.
2540 */
2541 static void
2542 fill_proc(const struct proc *psrc, struct proc *p, bool allowaddr)
2543 {
2544 COND_SET_VALUE(p->p_list, psrc->p_list, allowaddr);
2545 COND_SET_VALUE(p->p_auxlock, psrc->p_auxlock, allowaddr);
2546 COND_SET_VALUE(p->p_lock, psrc->p_lock, allowaddr);
2547 COND_SET_VALUE(p->p_stmutex, psrc->p_stmutex, allowaddr);
2548 COND_SET_VALUE(p->p_reflock, psrc->p_reflock, allowaddr);
2549 COND_SET_VALUE(p->p_waitcv, psrc->p_waitcv, allowaddr);
2550 COND_SET_VALUE(p->p_lwpcv, psrc->p_lwpcv, allowaddr);
2551 COND_SET_VALUE(p->p_cred, psrc->p_cred, allowaddr);
2552 COND_SET_VALUE(p->p_fd, psrc->p_fd, allowaddr);
2553 COND_SET_VALUE(p->p_cwdi, psrc->p_cwdi, allowaddr);
2554 COND_SET_VALUE(p->p_stats, psrc->p_stats, allowaddr);
2555 COND_SET_VALUE(p->p_limit, psrc->p_limit, allowaddr);
2556 COND_SET_VALUE(p->p_vmspace, psrc->p_vmspace, allowaddr);
2557 COND_SET_VALUE(p->p_sigacts, psrc->p_sigacts, allowaddr);
2558 COND_SET_VALUE(p->p_aio, psrc->p_aio, allowaddr);
2559 p->p_mqueue_cnt = psrc->p_mqueue_cnt;
2560 COND_SET_VALUE(p->p_specdataref, psrc->p_specdataref, allowaddr);
2561 p->p_exitsig = psrc->p_exitsig;
2562 p->p_flag = psrc->p_flag;
2563 p->p_sflag = psrc->p_sflag;
2564 p->p_slflag = psrc->p_slflag;
2565 p->p_lflag = psrc->p_lflag;
2566 p->p_stflag = psrc->p_stflag;
2567 p->p_stat = psrc->p_stat;
2568 p->p_trace_enabled = psrc->p_trace_enabled;
2569 p->p_pid = psrc->p_pid;
2570 COND_SET_VALUE(p->p_pglist, psrc->p_pglist, allowaddr);
2571 COND_SET_VALUE(p->p_pptr, psrc->p_pptr, allowaddr);
2572 COND_SET_VALUE(p->p_sibling, psrc->p_sibling, allowaddr);
2573 COND_SET_VALUE(p->p_children, psrc->p_children, allowaddr);
2574 COND_SET_VALUE(p->p_lwps, psrc->p_lwps, allowaddr);
2575 COND_SET_VALUE(p->p_raslist, psrc->p_raslist, allowaddr);
2576 p->p_nlwps = psrc->p_nlwps;
2577 p->p_nzlwps = psrc->p_nzlwps;
2578 p->p_nrlwps = psrc->p_nrlwps;
2579 p->p_nlwpwait = psrc->p_nlwpwait;
2580 p->p_ndlwps = psrc->p_ndlwps;
2581 p->p_nstopchild = psrc->p_nstopchild;
2582 p->p_waited = psrc->p_waited;
2583 COND_SET_VALUE(p->p_zomblwp, psrc->p_zomblwp, allowaddr);
2584 COND_SET_VALUE(p->p_vforklwp, psrc->p_vforklwp, allowaddr);
2585 COND_SET_VALUE(p->p_sched_info, psrc->p_sched_info, allowaddr);
2586 p->p_estcpu = psrc->p_estcpu;
2587 p->p_estcpu_inherited = psrc->p_estcpu_inherited;
2588 p->p_forktime = psrc->p_forktime;
2589 p->p_pctcpu = psrc->p_pctcpu;
2590 COND_SET_VALUE(p->p_opptr, psrc->p_opptr, allowaddr);
2591 COND_SET_VALUE(p->p_timers, psrc->p_timers, allowaddr);
2592 p->p_rtime = psrc->p_rtime;
2593 p->p_uticks = psrc->p_uticks;
2594 p->p_sticks = psrc->p_sticks;
2595 p->p_iticks = psrc->p_iticks;
2596 p->p_xutime = psrc->p_xutime;
2597 p->p_xstime = psrc->p_xstime;
2598 p->p_traceflag = psrc->p_traceflag;
2599 COND_SET_VALUE(p->p_tracep, psrc->p_tracep, allowaddr);
2600 COND_SET_VALUE(p->p_textvp, psrc->p_textvp, allowaddr);
2601 COND_SET_VALUE(p->p_emul, psrc->p_emul, allowaddr);
2602 COND_SET_VALUE(p->p_emuldata, psrc->p_emuldata, allowaddr);
2603 COND_SET_VALUE(p->p_execsw, psrc->p_execsw, allowaddr);
2604 COND_SET_VALUE(p->p_klist, psrc->p_klist, allowaddr);
2605 COND_SET_VALUE(p->p_sigwaiters, psrc->p_sigwaiters, allowaddr);
2606 COND_SET_VALUE(p->p_sigpend, psrc->p_sigpend, allowaddr);
2607 COND_SET_VALUE(p->p_lwpctl, psrc->p_lwpctl, allowaddr);
2608 p->p_ppid = psrc->p_ppid;
2609 p->p_oppid = psrc->p_oppid;
2610 COND_SET_VALUE(p->p_path, psrc->p_path, allowaddr);
2611 COND_SET_VALUE(p->p_sigctx, psrc->p_sigctx, allowaddr);
2612 p->p_nice = psrc->p_nice;
2613 memcpy(p->p_comm, psrc->p_comm, sizeof(p->p_comm));
2614 COND_SET_VALUE(p->p_pgrp, psrc->p_pgrp, allowaddr);
2615 COND_SET_VALUE(p->p_psstrp, psrc->p_psstrp, allowaddr);
2616 p->p_pax = psrc->p_pax;
2617 p->p_xexit = psrc->p_xexit;
2618 p->p_xsig = psrc->p_xsig;
2619 p->p_acflag = psrc->p_acflag;
2620 COND_SET_VALUE(p->p_md, psrc->p_md, allowaddr);
2621 p->p_stackbase = psrc->p_stackbase;
2622 COND_SET_VALUE(p->p_dtrace, psrc->p_dtrace, allowaddr);
2623 }
2624
2625 /*
2626 * Fill in an eproc structure for the specified process.
2627 */
2628 void
2629 fill_eproc(struct proc *p, struct eproc *ep, bool zombie, bool allowaddr)
2630 {
2631 struct tty *tp;
2632 struct lwp *l;
2633
2634 KASSERT(mutex_owned(proc_lock));
2635 KASSERT(mutex_owned(p->p_lock));
2636
2637 COND_SET_VALUE(ep->e_paddr, p, allowaddr);
2638 COND_SET_VALUE(ep->e_sess, p->p_session, allowaddr);
2639 if (p->p_cred) {
2640 kauth_cred_topcred(p->p_cred, &ep->e_pcred);
2641 kauth_cred_toucred(p->p_cred, &ep->e_ucred);
2642 }
2643 if (p->p_stat != SIDL && !P_ZOMBIE(p) && !zombie) {
2644 struct vmspace *vm = p->p_vmspace;
2645
2646 ep->e_vm.vm_rssize = vm_resident_count(vm);
2647 ep->e_vm.vm_tsize = vm->vm_tsize;
2648 ep->e_vm.vm_dsize = vm->vm_dsize;
2649 ep->e_vm.vm_ssize = vm->vm_ssize;
2650 ep->e_vm.vm_map.size = vm->vm_map.size;
2651
2652 /* Pick the primary (first) LWP */
2653 l = proc_active_lwp(p);
2654 KASSERT(l != NULL);
2655 lwp_lock(l);
2656 if (l->l_wchan)
2657 strncpy(ep->e_wmesg, l->l_wmesg, WMESGLEN);
2658 lwp_unlock(l);
2659 }
2660 ep->e_ppid = p->p_ppid;
2661 if (p->p_pgrp && p->p_session) {
2662 ep->e_pgid = p->p_pgrp->pg_id;
2663 ep->e_jobc = p->p_pgrp->pg_jobc;
2664 ep->e_sid = p->p_session->s_sid;
2665 if ((p->p_lflag & PL_CONTROLT) &&
2666 (tp = p->p_session->s_ttyp)) {
2667 ep->e_tdev = tp->t_dev;
2668 ep->e_tpgid = tp->t_pgrp ? tp->t_pgrp->pg_id : NO_PGID;
2669 COND_SET_VALUE(ep->e_tsess, tp->t_session, allowaddr);
2670 } else
2671 ep->e_tdev = (uint32_t)NODEV;
2672 ep->e_flag = p->p_session->s_ttyvp ? EPROC_CTTY : 0;
2673 if (SESS_LEADER(p))
2674 ep->e_flag |= EPROC_SLEADER;
2675 strncpy(ep->e_login, p->p_session->s_login, MAXLOGNAME);
2676 }
2677 ep->e_xsize = ep->e_xrssize = 0;
2678 ep->e_xccount = ep->e_xswrss = 0;
2679 }
2680
2681 /*
2682 * Fill in a kinfo_proc2 structure for the specified process.
2683 */
2684 void
2685 fill_kproc2(struct proc *p, struct kinfo_proc2 *ki, bool zombie, bool allowaddr)
2686 {
2687 struct tty *tp;
2688 struct lwp *l, *l2;
2689 struct timeval ut, st, rt;
2690 sigset_t ss1, ss2;
2691 struct rusage ru;
2692 struct vmspace *vm;
2693
2694 KASSERT(mutex_owned(proc_lock));
2695 KASSERT(mutex_owned(p->p_lock));
2696
2697 sigemptyset(&ss1);
2698 sigemptyset(&ss2);
2699
2700 COND_SET_VALUE(ki->p_paddr, PTRTOUINT64(p), allowaddr);
2701 COND_SET_VALUE(ki->p_fd, PTRTOUINT64(p->p_fd), allowaddr);
2702 COND_SET_VALUE(ki->p_cwdi, PTRTOUINT64(p->p_cwdi), allowaddr);
2703 COND_SET_VALUE(ki->p_stats, PTRTOUINT64(p->p_stats), allowaddr);
2704 COND_SET_VALUE(ki->p_limit, PTRTOUINT64(p->p_limit), allowaddr);
2705 COND_SET_VALUE(ki->p_vmspace, PTRTOUINT64(p->p_vmspace), allowaddr);
2706 COND_SET_VALUE(ki->p_sigacts, PTRTOUINT64(p->p_sigacts), allowaddr);
2707 COND_SET_VALUE(ki->p_sess, PTRTOUINT64(p->p_session), allowaddr);
2708 ki->p_tsess = 0; /* may be changed if controlling tty below */
2709 COND_SET_VALUE(ki->p_ru, PTRTOUINT64(&p->p_stats->p_ru), allowaddr);
2710 ki->p_eflag = 0;
2711 ki->p_exitsig = p->p_exitsig;
2712 ki->p_flag = L_INMEM; /* Process never swapped out */
2713 ki->p_flag |= sysctl_map_flags(sysctl_flagmap, p->p_flag);
2714 ki->p_flag |= sysctl_map_flags(sysctl_sflagmap, p->p_sflag);
2715 ki->p_flag |= sysctl_map_flags(sysctl_slflagmap, p->p_slflag);
2716 ki->p_flag |= sysctl_map_flags(sysctl_lflagmap, p->p_lflag);
2717 ki->p_flag |= sysctl_map_flags(sysctl_stflagmap, p->p_stflag);
2718 ki->p_pid = p->p_pid;
2719 ki->p_ppid = p->p_ppid;
2720 ki->p_uid = kauth_cred_geteuid(p->p_cred);
2721 ki->p_ruid = kauth_cred_getuid(p->p_cred);
2722 ki->p_gid = kauth_cred_getegid(p->p_cred);
2723 ki->p_rgid = kauth_cred_getgid(p->p_cred);
2724 ki->p_svuid = kauth_cred_getsvuid(p->p_cred);
2725 ki->p_svgid = kauth_cred_getsvgid(p->p_cred);
2726 ki->p_ngroups = kauth_cred_ngroups(p->p_cred);
2727 kauth_cred_getgroups(p->p_cred, ki->p_groups,
2728 uimin(ki->p_ngroups, sizeof(ki->p_groups) / sizeof(ki->p_groups[0])),
2729 UIO_SYSSPACE);
2730
2731 ki->p_uticks = p->p_uticks;
2732 ki->p_sticks = p->p_sticks;
2733 ki->p_iticks = p->p_iticks;
2734 ki->p_tpgid = NO_PGID; /* may be changed if controlling tty below */
2735 COND_SET_VALUE(ki->p_tracep, PTRTOUINT64(p->p_tracep), allowaddr);
2736 ki->p_traceflag = p->p_traceflag;
2737
2738 memcpy(&ki->p_sigignore, &p->p_sigctx.ps_sigignore,sizeof(ki_sigset_t));
2739 memcpy(&ki->p_sigcatch, &p->p_sigctx.ps_sigcatch, sizeof(ki_sigset_t));
2740
2741 ki->p_cpticks = 0;
2742 ki->p_pctcpu = p->p_pctcpu;
2743 ki->p_estcpu = 0;
2744 ki->p_stat = p->p_stat; /* Will likely be overridden by LWP status */
2745 ki->p_realstat = p->p_stat;
2746 ki->p_nice = p->p_nice;
2747 ki->p_xstat = P_WAITSTATUS(p);
2748 ki->p_acflag = p->p_acflag;
2749
2750 strncpy(ki->p_comm, p->p_comm,
2751 uimin(sizeof(ki->p_comm), sizeof(p->p_comm)));
2752 strncpy(ki->p_ename, p->p_emul->e_name, sizeof(ki->p_ename));
2753
2754 ki->p_nlwps = p->p_nlwps;
2755 ki->p_realflag = ki->p_flag;
2756
2757 if (p->p_stat != SIDL && !P_ZOMBIE(p) && !zombie) {
2758 vm = p->p_vmspace;
2759 ki->p_vm_rssize = vm_resident_count(vm);
2760 ki->p_vm_tsize = vm->vm_tsize;
2761 ki->p_vm_dsize = vm->vm_dsize;
2762 ki->p_vm_ssize = vm->vm_ssize;
2763 ki->p_vm_vsize = atop(vm->vm_map.size);
2764 /*
2765 * Since the stack is initially mapped mostly with
2766 * PROT_NONE and grown as needed, adjust the "mapped size"
2767 * to skip the unused stack portion.
2768 */
2769 ki->p_vm_msize =
2770 atop(vm->vm_map.size) - vm->vm_issize + vm->vm_ssize;
2771
2772 /* Pick the primary (first) LWP */
2773 l = proc_active_lwp(p);
2774 KASSERT(l != NULL);
2775 lwp_lock(l);
2776 ki->p_nrlwps = p->p_nrlwps;
2777 ki->p_forw = 0;
2778 ki->p_back = 0;
2779 COND_SET_VALUE(ki->p_addr, PTRTOUINT64(l->l_addr), allowaddr);
2780 ki->p_stat = l->l_stat;
2781 ki->p_flag |= sysctl_map_flags(sysctl_lwpflagmap, l->l_flag);
2782 ki->p_swtime = l->l_swtime;
2783 ki->p_slptime = l->l_slptime;
2784 if (l->l_stat == LSONPROC)
2785 ki->p_schedflags = l->l_cpu->ci_schedstate.spc_flags;
2786 else
2787 ki->p_schedflags = 0;
2788 ki->p_priority = lwp_eprio(l);
2789 ki->p_usrpri = l->l_priority;
2790 if (l->l_wchan)
2791 strncpy(ki->p_wmesg, l->l_wmesg, sizeof(ki->p_wmesg));
2792 COND_SET_VALUE(ki->p_wchan, PTRTOUINT64(l->l_wchan), allowaddr);
2793 ki->p_cpuid = cpu_index(l->l_cpu);
2794 lwp_unlock(l);
2795 LIST_FOREACH(l, &p->p_lwps, l_sibling) {
2796 /* This is hardly correct, but... */
2797 sigplusset(&l->l_sigpend.sp_set, &ss1);
2798 sigplusset(&l->l_sigmask, &ss2);
2799 ki->p_cpticks += l->l_cpticks;
2800 ki->p_pctcpu += l->l_pctcpu;
2801 ki->p_estcpu += l->l_estcpu;
2802 }
2803 }
2804 sigplusset(&p->p_sigpend.sp_set, &ss1);
2805 memcpy(&ki->p_siglist, &ss1, sizeof(ki_sigset_t));
2806 memcpy(&ki->p_sigmask, &ss2, sizeof(ki_sigset_t));
2807
2808 if (p->p_session != NULL) {
2809 ki->p_sid = p->p_session->s_sid;
2810 ki->p__pgid = p->p_pgrp->pg_id;
2811 if (p->p_session->s_ttyvp)
2812 ki->p_eflag |= EPROC_CTTY;
2813 if (SESS_LEADER(p))
2814 ki->p_eflag |= EPROC_SLEADER;
2815 strncpy(ki->p_login, p->p_session->s_login,
2816 uimin(sizeof ki->p_login - 1, sizeof p->p_session->s_login));
2817 ki->p_jobc = p->p_pgrp->pg_jobc;
2818 if ((p->p_lflag & PL_CONTROLT) && (tp = p->p_session->s_ttyp)) {
2819 ki->p_tdev = tp->t_dev;
2820 ki->p_tpgid = tp->t_pgrp ? tp->t_pgrp->pg_id : NO_PGID;
2821 COND_SET_VALUE(ki->p_tsess, PTRTOUINT64(tp->t_session),
2822 allowaddr);
2823 } else {
2824 ki->p_tdev = (int32_t)NODEV;
2825 }
2826 }
2827
2828 if (!P_ZOMBIE(p) && !zombie) {
2829 ki->p_uvalid = 1;
2830 ki->p_ustart_sec = p->p_stats->p_start.tv_sec;
2831 ki->p_ustart_usec = p->p_stats->p_start.tv_usec;
2832
2833 calcru(p, &ut, &st, NULL, &rt);
2834 ki->p_rtime_sec = rt.tv_sec;
2835 ki->p_rtime_usec = rt.tv_usec;
2836 ki->p_uutime_sec = ut.tv_sec;
2837 ki->p_uutime_usec = ut.tv_usec;
2838 ki->p_ustime_sec = st.tv_sec;
2839 ki->p_ustime_usec = st.tv_usec;
2840
2841 memcpy(&ru, &p->p_stats->p_ru, sizeof(ru));
2842 ki->p_uru_nvcsw = 0;
2843 ki->p_uru_nivcsw = 0;
2844 LIST_FOREACH(l2, &p->p_lwps, l_sibling) {
2845 ki->p_uru_nvcsw += (l2->l_ncsw - l2->l_nivcsw);
2846 ki->p_uru_nivcsw += l2->l_nivcsw;
2847 ruadd(&ru, &l2->l_ru);
2848 }
2849 ki->p_uru_maxrss = ru.ru_maxrss;
2850 ki->p_uru_ixrss = ru.ru_ixrss;
2851 ki->p_uru_idrss = ru.ru_idrss;
2852 ki->p_uru_isrss = ru.ru_isrss;
2853 ki->p_uru_minflt = ru.ru_minflt;
2854 ki->p_uru_majflt = ru.ru_majflt;
2855 ki->p_uru_nswap = ru.ru_nswap;
2856 ki->p_uru_inblock = ru.ru_inblock;
2857 ki->p_uru_oublock = ru.ru_oublock;
2858 ki->p_uru_msgsnd = ru.ru_msgsnd;
2859 ki->p_uru_msgrcv = ru.ru_msgrcv;
2860 ki->p_uru_nsignals = ru.ru_nsignals;
2861
2862 timeradd(&p->p_stats->p_cru.ru_utime,
2863 &p->p_stats->p_cru.ru_stime, &ut);
2864 ki->p_uctime_sec = ut.tv_sec;
2865 ki->p_uctime_usec = ut.tv_usec;
2866 }
2867 }
2868
2869
2870 int
2871 proc_find_locked(struct lwp *l, struct proc **p, pid_t pid)
2872 {
2873 int error;
2874
2875 mutex_enter(proc_lock);
2876 if (pid == -1)
2877 *p = l->l_proc;
2878 else
2879 *p = proc_find(pid);
2880
2881 if (*p == NULL) {
2882 if (pid != -1)
2883 mutex_exit(proc_lock);
2884 return ESRCH;
2885 }
2886 if (pid != -1)
2887 mutex_enter((*p)->p_lock);
2888 mutex_exit(proc_lock);
2889
2890 error = kauth_authorize_process(l->l_cred,
2891 KAUTH_PROCESS_CANSEE, *p,
2892 KAUTH_ARG(KAUTH_REQ_PROCESS_CANSEE_ENTRY), NULL, NULL);
2893 if (error) {
2894 if (pid != -1)
2895 mutex_exit((*p)->p_lock);
2896 }
2897 return error;
2898 }
2899
2900 static int
2901 fill_pathname(struct lwp *l, pid_t pid, void *oldp, size_t *oldlenp)
2902 {
2903 int error;
2904 struct proc *p;
2905
2906 if ((error = proc_find_locked(l, &p, pid)) != 0)
2907 return error;
2908
2909 if (p->p_path == NULL) {
2910 if (pid != -1)
2911 mutex_exit(p->p_lock);
2912 return ENOENT;
2913 }
2914
2915 size_t len = strlen(p->p_path) + 1;
2916 if (oldp != NULL) {
2917 size_t copylen = uimin(len, *oldlenp);
2918 error = sysctl_copyout(l, p->p_path, oldp, copylen);
2919 if (error == 0 && *oldlenp < len)
2920 error = ENOSPC;
2921 }
2922 *oldlenp = len;
2923 if (pid != -1)
2924 mutex_exit(p->p_lock);
2925 return error;
2926 }
2927
2928 static int
2929 fill_cwd(struct lwp *l, pid_t pid, void *oldp, size_t *oldlenp)
2930 {
2931 int error;
2932 struct proc *p;
2933 char *path;
2934 char *bp, *bend;
2935 struct cwdinfo *cwdi;
2936 struct vnode *vp;
2937 size_t len, lenused;
2938
2939 if ((error = proc_find_locked(l, &p, pid)) != 0)
2940 return error;
2941
2942 len = MAXPATHLEN * 4;
2943
2944 path = kmem_alloc(len, KM_SLEEP);
2945
2946 bp = &path[len];
2947 bend = bp;
2948 *(--bp) = '\0';
2949
2950 cwdi = p->p_cwdi;
2951 rw_enter(&cwdi->cwdi_lock, RW_READER);
2952 vp = cwdi->cwdi_cdir;
2953 error = getcwd_common(vp, NULL, &bp, path, len/2, 0, l);
2954 rw_exit(&cwdi->cwdi_lock);
2955
2956 if (error)
2957 goto out;
2958
2959 lenused = bend - bp;
2960
2961 if (oldp != NULL) {
2962 size_t copylen = uimin(lenused, *oldlenp);
2963 error = sysctl_copyout(l, bp, oldp, copylen);
2964 if (error == 0 && *oldlenp < lenused)
2965 error = ENOSPC;
2966 }
2967 *oldlenp = lenused;
2968 out:
2969 if (pid != -1)
2970 mutex_exit(p->p_lock);
2971 kmem_free(path, len);
2972 return error;
2973 }
2974
2975 int
2976 proc_getauxv(struct proc *p, void **buf, size_t *len)
2977 {
2978 struct ps_strings pss;
2979 int error;
2980 void *uauxv, *kauxv;
2981 size_t size;
2982
2983 if ((error = copyin_psstrings(p, &pss)) != 0)
2984 return error;
2985 if (pss.ps_envstr == NULL)
2986 return EIO;
2987
2988 size = p->p_execsw->es_arglen;
2989 if (size == 0)
2990 return EIO;
2991
2992 size_t ptrsz = PROC_PTRSZ(p);
2993 uauxv = (void *)((char *)pss.ps_envstr + (pss.ps_nenvstr + 1) * ptrsz);
2994
2995 kauxv = kmem_alloc(size, KM_SLEEP);
2996
2997 error = copyin_proc(p, uauxv, kauxv, size);
2998 if (error) {
2999 kmem_free(kauxv, size);
3000 return error;
3001 }
3002
3003 *buf = kauxv;
3004 *len = size;
3005
3006 return 0;
3007 }
3008
3009
3010 static int
3011 sysctl_security_expose_address(SYSCTLFN_ARGS)
3012 {
3013 int expose_address, error;
3014 struct sysctlnode node;
3015
3016 node = *rnode;
3017 node.sysctl_data = &expose_address;
3018 expose_address = *(int *)rnode->sysctl_data;
3019 error = sysctl_lookup(SYSCTLFN_CALL(&node));
3020 if (error || newp == NULL)
3021 return error;
3022
3023 if (kauth_authorize_system(l->l_cred, KAUTH_SYSTEM_KERNADDR,
3024 0, NULL, NULL, NULL))
3025 return EPERM;
3026
3027 switch (expose_address) {
3028 case 0:
3029 case 1:
3030 case 2:
3031 break;
3032 default:
3033 return EINVAL;
3034 }
3035
3036 *(int *)rnode->sysctl_data = expose_address;
3037
3038 return 0;
3039 }
3040
3041 bool
3042 get_expose_address(struct proc *p)
3043 {
3044 /* allow only if sysctl variable is set or privileged */
3045 return kauth_authorize_process(kauth_cred_get(), KAUTH_PROCESS_CANSEE,
3046 p, KAUTH_ARG(KAUTH_REQ_PROCESS_CANSEE_KPTR), NULL, NULL) == 0;
3047 }
3048