xref: /xnu-8792.81.2/bsd/kern/kern_resource.c (revision 19c3b8c28c31cb8130e034cfb5df6bf9ba342d90)
1 /*
2  * Copyright (c) 2000-2020 Apple Inc. All rights reserved.
3  *
4  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5  *
6  * This file contains Original Code and/or Modifications of Original Code
7  * as defined in and that are subject to the Apple Public Source License
8  * Version 2.0 (the 'License'). You may not use this file except in
9  * compliance with the License. The rights granted to you under the License
10  * may not be used to create, or enable the creation or redistribution of,
11  * unlawful or unlicensed copies of an Apple operating system, or to
12  * circumvent, violate, or enable the circumvention or violation of, any
13  * terms of an Apple operating system software license agreement.
14  *
15  * Please obtain a copy of the License at
16  * http://www.opensource.apple.com/apsl/ and read it before using this file.
17  *
18  * The Original Code and all software distributed under the License are
19  * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23  * Please see the License for the specific language governing rights and
24  * limitations under the License.
25  *
26  * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27  */
28 /* Copyright (c) 1995, 1997 Apple Computer, Inc. All Rights Reserved */
29 /*-
30  * Copyright (c) 1982, 1986, 1991, 1993
31  *	The Regents of the University of California.  All rights reserved.
32  * (c) UNIX System Laboratories, Inc.
33  * All or some portions of this file are derived from material licensed
34  * to the University of California by American Telephone and Telegraph
35  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
36  * the permission of UNIX System Laboratories, Inc.
37  *
38  * Redistribution and use in source and binary forms, with or without
39  * modification, are permitted provided that the following conditions
40  * are met:
41  * 1. Redistributions of source code must retain the above copyright
42  *    notice, this list of conditions and the following disclaimer.
43  * 2. Redistributions in binary form must reproduce the above copyright
44  *    notice, this list of conditions and the following disclaimer in the
45  *    documentation and/or other materials provided with the distribution.
46  * 3. All advertising materials mentioning features or use of this software
47  *    must display the following acknowledgement:
48  *	This product includes software developed by the University of
49  *	California, Berkeley and its contributors.
50  * 4. Neither the name of the University nor the names of its contributors
51  *    may be used to endorse or promote products derived from this software
52  *    without specific prior written permission.
53  *
54  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
55  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
58  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
59  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
60  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
62  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
63  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
64  * SUCH DAMAGE.
65  *
66  *	@(#)kern_resource.c	8.5 (Berkeley) 1/21/94
67  */
68 /*
69  * NOTICE: This file was modified by SPARTA, Inc. in 2005 to introduce
70  * support for mandatory and extensible security protections.  This notice
71  * is included in support of clause 2.2 (b) of the Apple Public License,
72  * Version 2.0.
73  */
74 
75 #include <sys/param.h>
76 #include <sys/systm.h>
77 #include <sys/sysctl.h>
78 #include <sys/kernel.h>
79 #include <sys/file_internal.h>
80 #include <sys/resourcevar.h>
81 #include <sys/malloc.h>
82 #include <sys/proc_internal.h>
83 #include <sys/kauth.h>
84 #include <sys/mount_internal.h>
85 #include <sys/sysproto.h>
86 
87 #include <security/audit/audit.h>
88 
89 #include <machine/vmparam.h>
90 
91 #include <mach/mach_types.h>
92 #include <mach/time_value.h>
93 #include <mach/task.h>
94 #include <mach/task_info.h>
95 #include <mach/vm_map.h>
96 #include <mach/mach_vm.h>
97 #include <mach/thread_act.h>  /* for thread_policy_set( ) */
98 #include <kern/thread.h>
99 #include <kern/policy_internal.h>
100 
101 #include <kern/task.h>
102 #include <kern/clock.h>         /* for absolutetime_to_microtime() */
103 #include <netinet/in.h>         /* for TRAFFIC_MGT_SO_* */
104 #if CONFIG_FREEZE
105 #include <sys/kern_memorystatus_freeze.h> /* for memorystatus_freeze_mark_ui_transition */
106 #endif /* CONFIG_FREEZE */
107 #include <sys/socketvar.h>      /* for struct socket */
108 #if NECP
109 #include <net/necp.h>
110 #endif /* NECP */
111 
112 #include <vm/vm_map.h>
113 
114 #include <kern/assert.h>
115 #include <sys/resource.h>
116 #include <sys/priv.h>
117 #include <IOKit/IOBSD.h>
118 
119 #if CONFIG_MACF
120 #include <security/mac_framework.h>
121 #endif
122 
123 static void proc_limitblock(proc_t p);
124 static void proc_limitunblock(proc_t p);
125 static void proc_limitupdate(proc_t p, bool unblock,
126     void (^update)(struct plimit *plim));
127 
128 static int donice(struct proc *curp, struct proc *chgp, int n);
129 static int dosetrlimit(struct proc *p, u_int which, struct rlimit *limp);
130 static void do_background_socket(struct proc *p, thread_t thread);
131 static int do_background_thread(thread_t thread, int priority);
132 static int do_background_proc(struct proc *curp, struct proc *targetp, int priority);
133 static int set_gpudeny_proc(struct proc *curp, struct proc *targetp, int priority);
134 static int proc_set_darwin_role(proc_t curp, proc_t targetp, int priority);
135 static int proc_get_darwin_role(proc_t curp, proc_t targetp, int *priority);
136 static int get_background_proc(struct proc *curp, struct proc *targetp, int *priority);
137 
138 int fill_task_rusage(task_t task, rusage_info_current *ri);
139 void fill_task_billed_usage(task_t task, rusage_info_current *ri);
140 int fill_task_io_rusage(task_t task, rusage_info_current *ri);
141 int fill_task_qos_rusage(task_t task, rusage_info_current *ri);
142 uint64_t get_task_logical_writes(task_t task, bool external);
143 
144 rlim_t maxdmap = MAXDSIZ;       /* XXX */
145 rlim_t maxsmap = MAXSSIZ - PAGE_MAX_SIZE;       /* XXX */
146 
147 /* For plimit reference count */
148 os_refgrp_decl(, rlimit_refgrp, "plimit_refcnt", NULL);
149 
150 static KALLOC_TYPE_DEFINE(plimit_zone, struct plimit, KT_DEFAULT);
151 
152 /*
153  * Limits on the number of open files per process, and the number
154  * of child processes per process.
155  *
156  * Note: would be in kern/subr_param.c in FreeBSD.
157  */
158 __private_extern__ int maxfilesperproc = OPEN_MAX;              /* per-proc open files limit */
159 
160 SYSCTL_INT(_kern, KERN_MAXPROCPERUID, maxprocperuid, CTLFLAG_RW | CTLFLAG_LOCKED,
161     &maxprocperuid, 0, "Maximum processes allowed per userid" );
162 
163 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW | CTLFLAG_LOCKED,
164     &maxfilesperproc, 0, "Maximum files allowed open per process" );
165 
166 /* Args and fn for proc_iteration callback used in setpriority */
167 struct puser_nice_args {
168 	proc_t curp;
169 	int     prio;
170 	id_t    who;
171 	int *   foundp;
172 	int *   errorp;
173 };
174 static int puser_donice_callback(proc_t p, void * arg);
175 
176 
177 /* Args and fn for proc_iteration callback used in setpriority */
178 struct ppgrp_nice_args {
179 	proc_t curp;
180 	int     prio;
181 	int *   foundp;
182 	int *   errorp;
183 };
184 static int ppgrp_donice_callback(proc_t p, void * arg);
185 
186 /*
187  * Resource controls and accounting.
188  */
189 int
getpriority(struct proc * curp,struct getpriority_args * uap,int32_t * retval)190 getpriority(struct proc *curp, struct getpriority_args *uap, int32_t *retval)
191 {
192 	struct proc *p;
193 	int low = PRIO_MAX + 1;
194 	kauth_cred_t my_cred;
195 	int refheld = 0;
196 	int error = 0;
197 
198 	/* would also test (uap->who < 0), but id_t is unsigned */
199 	if (uap->who > 0x7fffffff) {
200 		return EINVAL;
201 	}
202 
203 	switch (uap->which) {
204 	case PRIO_PROCESS:
205 		if (uap->who == 0) {
206 			p = curp;
207 			low = p->p_nice;
208 		} else {
209 			p = proc_find(uap->who);
210 			if (p == 0) {
211 				break;
212 			}
213 			low = p->p_nice;
214 			proc_rele(p);
215 		}
216 		break;
217 
218 	case PRIO_PGRP: {
219 		struct pgrp *pg = PGRP_NULL;
220 
221 		if (uap->who == 0) {
222 			/* returns the pgrp to ref */
223 			pg = proc_pgrp(curp, NULL);
224 		} else if ((pg = pgrp_find(uap->who)) == PGRP_NULL) {
225 			break;
226 		}
227 		/* No need for iteration as it is a simple scan */
228 		pgrp_lock(pg);
229 		PGMEMBERS_FOREACH(pg, p) {
230 			if (p->p_nice < low) {
231 				low = p->p_nice;
232 			}
233 		}
234 		pgrp_unlock(pg);
235 		pgrp_rele(pg);
236 		break;
237 	}
238 
239 	case PRIO_USER:
240 		if (uap->who == 0) {
241 			uap->who = kauth_cred_getuid(kauth_cred_get());
242 		}
243 
244 		proc_list_lock();
245 
246 		for (p = allproc.lh_first; p != 0; p = p->p_list.le_next) {
247 			my_cred = kauth_cred_proc_ref(p);
248 			if (kauth_cred_getuid(my_cred) == uap->who &&
249 			    p->p_nice < low) {
250 				low = p->p_nice;
251 			}
252 			kauth_cred_unref(&my_cred);
253 		}
254 
255 		proc_list_unlock();
256 
257 		break;
258 
259 	case PRIO_DARWIN_THREAD:
260 		/* we currently only support the current thread */
261 		if (uap->who != 0) {
262 			return EINVAL;
263 		}
264 
265 		low = proc_get_thread_policy(current_thread(), TASK_POLICY_INTERNAL, TASK_POLICY_DARWIN_BG);
266 
267 		break;
268 
269 	case PRIO_DARWIN_PROCESS:
270 		if (uap->who == 0) {
271 			p = curp;
272 		} else {
273 			p = proc_find(uap->who);
274 			if (p == PROC_NULL) {
275 				break;
276 			}
277 			refheld = 1;
278 		}
279 
280 		error = get_background_proc(curp, p, &low);
281 
282 		if (refheld) {
283 			proc_rele(p);
284 		}
285 		if (error) {
286 			return error;
287 		}
288 		break;
289 
290 	case PRIO_DARWIN_ROLE:
291 		if (uap->who == 0) {
292 			p = curp;
293 		} else {
294 			p = proc_find(uap->who);
295 			if (p == PROC_NULL) {
296 				break;
297 			}
298 			refheld = 1;
299 		}
300 
301 		error = proc_get_darwin_role(curp, p, &low);
302 
303 		if (refheld) {
304 			proc_rele(p);
305 		}
306 		if (error) {
307 			return error;
308 		}
309 		break;
310 
311 	default:
312 		return EINVAL;
313 	}
314 	if (low == PRIO_MAX + 1) {
315 		return ESRCH;
316 	}
317 	*retval = low;
318 	return 0;
319 }
320 
321 /* call back function used for proc iteration in PRIO_USER */
322 static int
puser_donice_callback(proc_t p,void * arg)323 puser_donice_callback(proc_t p, void * arg)
324 {
325 	int error, n;
326 	struct puser_nice_args * pun = (struct puser_nice_args *)arg;
327 	kauth_cred_t my_cred;
328 
329 	my_cred = kauth_cred_proc_ref(p);
330 	if (kauth_cred_getuid(my_cred) == pun->who) {
331 		error = donice(pun->curp, p, pun->prio);
332 		if (pun->errorp != NULL) {
333 			*pun->errorp = error;
334 		}
335 		if (pun->foundp != NULL) {
336 			n = *pun->foundp;
337 			*pun->foundp = n + 1;
338 		}
339 	}
340 	kauth_cred_unref(&my_cred);
341 
342 	return PROC_RETURNED;
343 }
344 
345 /* call back function used for proc iteration in PRIO_PGRP */
346 static int
ppgrp_donice_callback(proc_t p,void * arg)347 ppgrp_donice_callback(proc_t p, void * arg)
348 {
349 	int error;
350 	struct ppgrp_nice_args * pun = (struct ppgrp_nice_args *)arg;
351 	int n;
352 
353 	error = donice(pun->curp, p, pun->prio);
354 	if (pun->errorp != NULL) {
355 		*pun->errorp = error;
356 	}
357 	if (pun->foundp != NULL) {
358 		n = *pun->foundp;
359 		*pun->foundp = n + 1;
360 	}
361 
362 	return PROC_RETURNED;
363 }
364 
365 /*
366  * Returns:	0			Success
367  *		EINVAL
368  *		ESRCH
369  *	donice:EPERM
370  *	donice:EACCES
371  */
372 /* ARGSUSED */
373 int
setpriority(struct proc * curp,struct setpriority_args * uap,int32_t * retval)374 setpriority(struct proc *curp, struct setpriority_args *uap, int32_t *retval)
375 {
376 	struct proc *p;
377 	int found = 0, error = 0;
378 	int refheld = 0;
379 
380 	AUDIT_ARG(cmd, uap->which);
381 	AUDIT_ARG(owner, uap->who, 0);
382 	AUDIT_ARG(value32, uap->prio);
383 
384 	/* would also test (uap->who < 0), but id_t is unsigned */
385 	if (uap->who > 0x7fffffff) {
386 		return EINVAL;
387 	}
388 
389 	switch (uap->which) {
390 	case PRIO_PROCESS:
391 		if (uap->who == 0) {
392 			p = curp;
393 		} else {
394 			p = proc_find(uap->who);
395 			if (p == 0) {
396 				break;
397 			}
398 			refheld = 1;
399 		}
400 		error = donice(curp, p, uap->prio);
401 		found++;
402 		if (refheld != 0) {
403 			proc_rele(p);
404 		}
405 		break;
406 
407 	case PRIO_PGRP: {
408 		struct pgrp *pg = PGRP_NULL;
409 		struct ppgrp_nice_args ppgrp;
410 
411 		if (uap->who == 0) {
412 			pg = proc_pgrp(curp, NULL);
413 		} else if ((pg = pgrp_find(uap->who)) == PGRP_NULL) {
414 			break;
415 		}
416 
417 		ppgrp.curp = curp;
418 		ppgrp.prio = uap->prio;
419 		ppgrp.foundp = &found;
420 		ppgrp.errorp = &error;
421 
422 		pgrp_iterate(pg, ppgrp_donice_callback, (void *)&ppgrp, NULL);
423 		pgrp_rele(pg);
424 
425 		break;
426 	}
427 
428 	case PRIO_USER: {
429 		struct puser_nice_args punice;
430 
431 		if (uap->who == 0) {
432 			uap->who = kauth_cred_getuid(kauth_cred_get());
433 		}
434 
435 		punice.curp = curp;
436 		punice.prio = uap->prio;
437 		punice.who = uap->who;
438 		punice.foundp = &found;
439 		error = 0;
440 		punice.errorp = &error;
441 		proc_iterate(PROC_ALLPROCLIST, puser_donice_callback, (void *)&punice, NULL, NULL);
442 
443 		break;
444 	}
445 
446 	case PRIO_DARWIN_THREAD: {
447 		/* we currently only support the current thread */
448 		if (uap->who != 0) {
449 			return EINVAL;
450 		}
451 
452 		error = do_background_thread(current_thread(), uap->prio);
453 		found++;
454 		break;
455 	}
456 
457 	case PRIO_DARWIN_PROCESS: {
458 		if (uap->who == 0) {
459 			p = curp;
460 		} else {
461 			p = proc_find(uap->who);
462 			if (p == 0) {
463 				break;
464 			}
465 			refheld = 1;
466 		}
467 
468 		error = do_background_proc(curp, p, uap->prio);
469 
470 		found++;
471 		if (refheld != 0) {
472 			proc_rele(p);
473 		}
474 		break;
475 	}
476 
477 	case PRIO_DARWIN_GPU: {
478 		if (uap->who == 0) {
479 			return EINVAL;
480 		}
481 
482 		p = proc_find(uap->who);
483 		if (p == PROC_NULL) {
484 			break;
485 		}
486 
487 		error = set_gpudeny_proc(curp, p, uap->prio);
488 
489 		found++;
490 		proc_rele(p);
491 		break;
492 	}
493 
494 	case PRIO_DARWIN_ROLE: {
495 		if (uap->who == 0) {
496 			p = curp;
497 		} else {
498 			p = proc_find(uap->who);
499 			if (p == PROC_NULL) {
500 				break;
501 			}
502 			refheld = 1;
503 		}
504 
505 		error = proc_set_darwin_role(curp, p, uap->prio);
506 
507 		found++;
508 		if (refheld != 0) {
509 			proc_rele(p);
510 		}
511 		break;
512 	}
513 
514 	default:
515 		return EINVAL;
516 	}
517 	if (found == 0) {
518 		return ESRCH;
519 	}
520 	if (error == EIDRM) {
521 		*retval = -2;
522 		error = 0;
523 	}
524 	return error;
525 }
526 
527 
528 /*
529  * Returns:	0			Success
530  *		EPERM
531  *		EACCES
532  *	mac_check_proc_sched:???
533  */
534 static int
donice(struct proc * curp,struct proc * chgp,int n)535 donice(struct proc *curp, struct proc *chgp, int n)
536 {
537 	int error = 0;
538 	kauth_cred_t ucred;
539 	kauth_cred_t my_cred;
540 
541 	ucred = kauth_cred_proc_ref(curp);
542 	my_cred = kauth_cred_proc_ref(chgp);
543 
544 	if (suser(ucred, NULL) && kauth_cred_getruid(ucred) &&
545 	    kauth_cred_getuid(ucred) != kauth_cred_getuid(my_cred) &&
546 	    kauth_cred_getruid(ucred) != kauth_cred_getuid(my_cred)) {
547 		error = EPERM;
548 		goto out;
549 	}
550 	if (n > PRIO_MAX) {
551 		n = PRIO_MAX;
552 	}
553 	if (n < PRIO_MIN) {
554 		n = PRIO_MIN;
555 	}
556 	if (n < chgp->p_nice && suser(ucred, &curp->p_acflag)) {
557 		error = EACCES;
558 		goto out;
559 	}
560 #if CONFIG_MACF
561 	error = mac_proc_check_sched(curp, chgp);
562 	if (error) {
563 		goto out;
564 	}
565 #endif
566 	proc_lock(chgp);
567 	chgp->p_nice = (char)n;
568 	proc_unlock(chgp);
569 	(void)resetpriority(chgp);
570 out:
571 	kauth_cred_unref(&ucred);
572 	kauth_cred_unref(&my_cred);
573 	return error;
574 }
575 
576 static int
set_gpudeny_proc(struct proc * curp,struct proc * targetp,int priority)577 set_gpudeny_proc(struct proc *curp, struct proc *targetp, int priority)
578 {
579 	int error = 0;
580 	kauth_cred_t ucred;
581 	kauth_cred_t target_cred;
582 
583 	ucred = kauth_cred_get();
584 	target_cred = kauth_cred_proc_ref(targetp);
585 
586 	/* TODO: Entitlement instead of uid check */
587 
588 	if (!kauth_cred_issuser(ucred) && kauth_cred_getruid(ucred) &&
589 	    kauth_cred_getuid(ucred) != kauth_cred_getuid(target_cred) &&
590 	    kauth_cred_getruid(ucred) != kauth_cred_getuid(target_cred)) {
591 		error = EPERM;
592 		goto out;
593 	}
594 
595 	if (curp == targetp) {
596 		error = EPERM;
597 		goto out;
598 	}
599 
600 #if CONFIG_MACF
601 	error = mac_proc_check_sched(curp, targetp);
602 	if (error) {
603 		goto out;
604 	}
605 #endif
606 
607 	switch (priority) {
608 	case PRIO_DARWIN_GPU_DENY:
609 		task_set_gpu_denied(proc_task(targetp), TRUE);
610 		break;
611 	case PRIO_DARWIN_GPU_ALLOW:
612 		task_set_gpu_denied(proc_task(targetp), FALSE);
613 		break;
614 	default:
615 		error = EINVAL;
616 		goto out;
617 	}
618 
619 out:
620 	kauth_cred_unref(&target_cred);
621 	return error;
622 }
623 
624 static int
proc_set_darwin_role(proc_t curp,proc_t targetp,int priority)625 proc_set_darwin_role(proc_t curp, proc_t targetp, int priority)
626 {
627 	int error = 0;
628 	uint32_t flagsp = 0;
629 
630 	kauth_cred_t ucred, target_cred;
631 
632 	ucred = kauth_cred_get();
633 	target_cred = kauth_cred_proc_ref(targetp);
634 
635 	if (!kauth_cred_issuser(ucred) && kauth_cred_getruid(ucred) &&
636 	    kauth_cred_getuid(ucred) != kauth_cred_getuid(target_cred) &&
637 	    kauth_cred_getruid(ucred) != kauth_cred_getuid(target_cred)) {
638 		if (priv_check_cred(ucred, PRIV_SETPRIORITY_DARWIN_ROLE, 0) != 0) {
639 			error = EPERM;
640 			goto out;
641 		}
642 	}
643 
644 	if (curp != targetp) {
645 #if CONFIG_MACF
646 		if ((error = mac_proc_check_sched(curp, targetp))) {
647 			goto out;
648 		}
649 #endif
650 	}
651 
652 	proc_get_darwinbgstate(proc_task(targetp), &flagsp);
653 	if ((flagsp & PROC_FLAG_APPLICATION) != PROC_FLAG_APPLICATION) {
654 		error = ENOTSUP;
655 		goto out;
656 	}
657 
658 	task_role_t role = TASK_UNSPECIFIED;
659 
660 	if ((error = proc_darwin_role_to_task_role(priority, &role))) {
661 		goto out;
662 	}
663 
664 	proc_set_task_policy(proc_task(targetp), TASK_POLICY_ATTRIBUTE,
665 	    TASK_POLICY_ROLE, role);
666 
667 #if CONFIG_FREEZE
668 	if (priority == PRIO_DARWIN_ROLE_UI_FOCAL || priority == PRIO_DARWIN_ROLE_UI || priority == PRIO_DARWIN_ROLE_UI_NON_FOCAL) {
669 		memorystatus_freezer_mark_ui_transition(targetp);
670 	}
671 #endif /* CONFIG_FREEZE */
672 
673 out:
674 	kauth_cred_unref(&target_cred);
675 	return error;
676 }
677 
678 static int
proc_get_darwin_role(proc_t curp,proc_t targetp,int * priority)679 proc_get_darwin_role(proc_t curp, proc_t targetp, int *priority)
680 {
681 	int error = 0;
682 	int role = 0;
683 
684 	kauth_cred_t ucred, target_cred;
685 
686 	ucred = kauth_cred_get();
687 	target_cred = kauth_cred_proc_ref(targetp);
688 
689 	if (!kauth_cred_issuser(ucred) && kauth_cred_getruid(ucred) &&
690 	    kauth_cred_getuid(ucred) != kauth_cred_getuid(target_cred) &&
691 	    kauth_cred_getruid(ucred) != kauth_cred_getuid(target_cred)) {
692 		error = EPERM;
693 		goto out;
694 	}
695 
696 	if (curp != targetp) {
697 #if CONFIG_MACF
698 		if ((error = mac_proc_check_sched(curp, targetp))) {
699 			goto out;
700 		}
701 #endif
702 	}
703 
704 	role = proc_get_task_policy(proc_task(targetp), TASK_POLICY_ATTRIBUTE, TASK_POLICY_ROLE);
705 
706 	*priority = proc_task_role_to_darwin_role(role);
707 
708 out:
709 	kauth_cred_unref(&target_cred);
710 	return error;
711 }
712 
713 
714 static int
get_background_proc(struct proc * curp,struct proc * targetp,int * priority)715 get_background_proc(struct proc *curp, struct proc *targetp, int *priority)
716 {
717 	int external = 0;
718 	int error = 0;
719 	kauth_cred_t ucred, target_cred;
720 
721 	ucred = kauth_cred_get();
722 	target_cred = kauth_cred_proc_ref(targetp);
723 
724 	if (!kauth_cred_issuser(ucred) && kauth_cred_getruid(ucred) &&
725 	    kauth_cred_getuid(ucred) != kauth_cred_getuid(target_cred) &&
726 	    kauth_cred_getruid(ucred) != kauth_cred_getuid(target_cred)) {
727 		error = EPERM;
728 		goto out;
729 	}
730 
731 	external = (curp == targetp) ? TASK_POLICY_INTERNAL : TASK_POLICY_EXTERNAL;
732 
733 	*priority = proc_get_task_policy(current_task(), external, TASK_POLICY_DARWIN_BG);
734 
735 out:
736 	kauth_cred_unref(&target_cred);
737 	return error;
738 }
739 
740 static int
do_background_proc(struct proc * curp,struct proc * targetp,int priority)741 do_background_proc(struct proc *curp, struct proc *targetp, int priority)
742 {
743 #if !CONFIG_MACF
744 #pragma unused(curp)
745 #endif
746 	int error = 0;
747 	kauth_cred_t ucred;
748 	kauth_cred_t target_cred;
749 	int external;
750 	int enable;
751 
752 	ucred = kauth_cred_get();
753 	target_cred = kauth_cred_proc_ref(targetp);
754 
755 	if (!kauth_cred_issuser(ucred) && kauth_cred_getruid(ucred) &&
756 	    kauth_cred_getuid(ucred) != kauth_cred_getuid(target_cred) &&
757 	    kauth_cred_getruid(ucred) != kauth_cred_getuid(target_cred)) {
758 		error = EPERM;
759 		goto out;
760 	}
761 
762 #if CONFIG_MACF
763 	error = mac_proc_check_sched(curp, targetp);
764 	if (error) {
765 		goto out;
766 	}
767 #endif
768 
769 	external = (curp == targetp) ? TASK_POLICY_INTERNAL : TASK_POLICY_EXTERNAL;
770 
771 	switch (priority) {
772 	case PRIO_DARWIN_BG:
773 		enable = TASK_POLICY_ENABLE;
774 		break;
775 	case PRIO_DARWIN_NONUI:
776 		/* ignored for compatibility */
777 		goto out;
778 	default:
779 		/* TODO: EINVAL if priority != 0 */
780 		enable = TASK_POLICY_DISABLE;
781 		break;
782 	}
783 
784 	proc_set_task_policy(proc_task(targetp), external, TASK_POLICY_DARWIN_BG, enable);
785 
786 out:
787 	kauth_cred_unref(&target_cred);
788 	return error;
789 }
790 
791 static void
do_background_socket(struct proc * p,thread_t thread)792 do_background_socket(struct proc *p, thread_t thread)
793 {
794 #if SOCKETS
795 	struct fileproc *fp;
796 	int              background = false;
797 #if NECP
798 	int              update_necp = false;
799 #endif /* NECP */
800 
801 	if (thread != THREAD_NULL &&
802 	    get_threadtask(thread) != proc_task(p)) {
803 		return;
804 	}
805 
806 	proc_fdlock(p);
807 
808 	if (thread != THREAD_NULL) {
809 		background = proc_get_effective_thread_policy(thread, TASK_POLICY_ALL_SOCKETS_BG);
810 	} else {
811 		background = proc_get_effective_task_policy(proc_task(p), TASK_POLICY_ALL_SOCKETS_BG);
812 	}
813 
814 	if (background) {
815 		/*
816 		 * For PRIO_DARWIN_PROCESS (thread is NULL), simply mark
817 		 * the sockets with the background flag.  There's nothing
818 		 * to do here for the PRIO_DARWIN_THREAD case.
819 		 */
820 		if (thread == THREAD_NULL) {
821 			fdt_foreach(fp, p) {
822 				if (FILEGLOB_DTYPE(fp->fp_glob) == DTYPE_SOCKET) {
823 					struct socket *sockp = (struct socket *)fp_get_data(fp);
824 					socket_set_traffic_mgt_flags(sockp, TRAFFIC_MGT_SO_BACKGROUND);
825 					sockp->so_background_thread = NULL;
826 				}
827 #if NECP
828 				else if (FILEGLOB_DTYPE(fp->fp_glob) == DTYPE_NETPOLICY) {
829 					if (necp_set_client_as_background(p, fp, background)) {
830 						update_necp = true;
831 					}
832 				}
833 #endif /* NECP */
834 			}
835 		}
836 	} else {
837 		/* disable networking IO throttle.
838 		 * NOTE - It is a known limitation of the current design that we
839 		 * could potentially clear TRAFFIC_MGT_SO_BACKGROUND bit for
840 		 * sockets created by other threads within this process.
841 		 */
842 		fdt_foreach(fp, p) {
843 			struct socket *sockp;
844 
845 			if (FILEGLOB_DTYPE(fp->fp_glob) == DTYPE_SOCKET) {
846 				sockp = (struct socket *)fp_get_data(fp);
847 				/* skip if only clearing this thread's sockets */
848 				if ((thread) && (sockp->so_background_thread != thread)) {
849 					continue;
850 				}
851 				socket_clear_traffic_mgt_flags(sockp, TRAFFIC_MGT_SO_BACKGROUND);
852 				sockp->so_background_thread = NULL;
853 			}
854 #if NECP
855 			else if (FILEGLOB_DTYPE(fp->fp_glob) == DTYPE_NETPOLICY) {
856 				if (necp_set_client_as_background(p, fp, background)) {
857 					update_necp = true;
858 				}
859 			}
860 #endif /* NECP */
861 		}
862 	}
863 
864 	proc_fdunlock(p);
865 
866 #if NECP
867 	if (update_necp) {
868 		necp_update_all_clients();
869 	}
870 #endif /* NECP */
871 #else
872 #pragma unused(p, thread)
873 #endif
874 }
875 
876 
877 /*
878  * do_background_thread
879  *
880  * Requires: thread reference
881  *
882  * Returns:     0                       Success
883  *              EPERM                   Tried to background while in vfork
884  * XXX - todo - does this need a MACF hook?
885  */
886 static int
do_background_thread(thread_t thread,int priority)887 do_background_thread(thread_t thread, int priority)
888 {
889 	int enable, external;
890 	int rv = 0;
891 
892 	/* Backgrounding is unsupported for workq threads */
893 	if (thread_is_static_param(thread)) {
894 		return EPERM;
895 	}
896 
897 	/* Not allowed to combine QoS and DARWIN_BG, doing so strips the QoS */
898 	if (thread_has_qos_policy(thread)) {
899 		thread_remove_qos_policy(thread);
900 		rv = EIDRM;
901 	}
902 
903 	/* TODO: Fail if someone passes something besides 0 or PRIO_DARWIN_BG */
904 	enable   = (priority == PRIO_DARWIN_BG) ? TASK_POLICY_ENABLE   : TASK_POLICY_DISABLE;
905 	external = (current_thread() == thread) ? TASK_POLICY_INTERNAL : TASK_POLICY_EXTERNAL;
906 
907 	proc_set_thread_policy(thread, external, TASK_POLICY_DARWIN_BG, enable);
908 
909 	return rv;
910 }
911 
912 
913 /*
914  * Returns:	0			Success
915  *	copyin:EFAULT
916  *	dosetrlimit:
917  */
918 /* ARGSUSED */
919 int
setrlimit(struct proc * p,struct setrlimit_args * uap,__unused int32_t * retval)920 setrlimit(struct proc *p, struct setrlimit_args *uap, __unused int32_t *retval)
921 {
922 	struct rlimit alim;
923 	int error;
924 
925 	if ((error = copyin(uap->rlp, (caddr_t)&alim,
926 	    sizeof(struct rlimit)))) {
927 		return error;
928 	}
929 
930 	return dosetrlimit(p, uap->which, &alim);
931 }
932 
933 /*
934  * Returns:	0			Success
935  *		EINVAL
936  *	suser:EPERM
937  *
938  * Notes:	EINVAL is returned both for invalid arguments, and in the
939  *		case that the current usage (e.g. RLIMIT_STACK) is already
940  *		in excess of the requested limit.
941  */
942 static int
dosetrlimit(struct proc * p,u_int which,struct rlimit * newrlim)943 dosetrlimit(struct proc *p, u_int which, struct rlimit *newrlim)
944 {
945 	struct rlimit        rlim, stack_rlim = {.rlim_cur = 0, .rlim_max = 0};
946 	int                  error;
947 	kern_return_t        kr;
948 
949 	/* Mask out POSIX flag, saved above */
950 	which &= ~_RLIMIT_POSIX_FLAG;
951 
952 	/* Unknown resource */
953 	if (which >= RLIM_NLIMITS) {
954 		return EINVAL;
955 	}
956 
957 	proc_lock(p);
958 
959 	/* Only one thread is able to change the current process's rlimit values */
960 	proc_limitblock(p);
961 
962 	/*
963 	 * Take a snapshot of the current rlimit values and read this throughout
964 	 * this routine. This minimizes the critical sections and allow other
965 	 * processes in the system to access the plimit while we are in the
966 	 * middle of this setrlimit call.
967 	 */
968 	rlim = smr_serialized_load(&p->p_limit)->pl_rlimit[which];
969 
970 	proc_unlock(p);
971 
972 	error = 0;
973 	/* Sanity check: new soft limit cannot exceed new hard limit */
974 	if (newrlim->rlim_cur > newrlim->rlim_max) {
975 		error = EINVAL;
976 	}
977 	/*
978 	 * Sanity check: only super-user may raise the hard limit.
979 	 * newrlim->rlim_cur > rlim.rlim_max implies that the call
980 	 * is increasing the hard limit as well.
981 	 */
982 	else if (newrlim->rlim_cur > rlim.rlim_max || newrlim->rlim_max > rlim.rlim_max) {
983 		/* suser() returns 0 if the calling thread is super user. */
984 		error = suser(kauth_cred_get(), &p->p_acflag);
985 	}
986 
987 	if (error) {
988 		/* Invalid setrlimit request: EINVAL or EPERM */
989 		goto out;
990 	}
991 
992 	/* We have the reader lock of the process's plimit so it's safe to read the rlimit values */
993 	switch (which) {
994 	case RLIMIT_CPU:
995 		if (newrlim->rlim_cur == RLIM_INFINITY) {
996 			task_vtimer_clear(proc_task(p), TASK_VTIMER_RLIM);
997 			timerclear(&p->p_rlim_cpu);
998 		} else {
999 			task_absolutetime_info_data_t   tinfo;
1000 			mach_msg_type_number_t          count;
1001 			struct timeval                  ttv, tv;
1002 			clock_sec_t                     tv_sec;
1003 			clock_usec_t                    tv_usec;
1004 
1005 			count = TASK_ABSOLUTETIME_INFO_COUNT;
1006 			task_info(proc_task(p), TASK_ABSOLUTETIME_INFO, (task_info_t)&tinfo, &count);
1007 			absolutetime_to_microtime(tinfo.total_user + tinfo.total_system, &tv_sec, &tv_usec);
1008 			ttv.tv_sec = tv_sec;
1009 			ttv.tv_usec = tv_usec;
1010 
1011 			tv.tv_sec = (newrlim->rlim_cur > __INT_MAX__ ? __INT_MAX__ : (__darwin_time_t)newrlim->rlim_cur);
1012 			tv.tv_usec = 0;
1013 			timersub(&tv, &ttv, &p->p_rlim_cpu);
1014 
1015 			timerclear(&tv);
1016 			if (timercmp(&p->p_rlim_cpu, &tv, >)) {
1017 				task_vtimer_set(proc_task(p), TASK_VTIMER_RLIM);
1018 			} else {
1019 				task_vtimer_clear(proc_task(p), TASK_VTIMER_RLIM);
1020 
1021 				timerclear(&p->p_rlim_cpu);
1022 
1023 				psignal(p, SIGXCPU);
1024 			}
1025 		}
1026 		break;
1027 
1028 	case RLIMIT_DATA:
1029 #if 00
1030 		if (newrlim->rlim_cur > maxdmap) {
1031 			newrlim->rlim_cur = maxdmap;
1032 		}
1033 		if (newrlim->rlim_max > maxdmap) {
1034 			newrlim->rlim_max = maxdmap;
1035 		}
1036 #endif
1037 
1038 		/* Over to Mach VM to validate the new data limit */
1039 		if (vm_map_set_data_limit(current_map(), newrlim->rlim_cur) != KERN_SUCCESS) {
1040 			/* The limit specified cannot be lowered because current usage is already higher than the limit. */
1041 			error =  EINVAL;
1042 			goto out;
1043 		}
1044 		break;
1045 
1046 	case RLIMIT_STACK:
1047 		if (p->p_lflag & P_LCUSTOM_STACK) {
1048 			/* Process has a custom stack set - rlimit cannot be used to change it */
1049 			error = EINVAL;
1050 			goto out;
1051 		}
1052 
1053 		/*
1054 		 * Note: the real stack size limit is enforced by maxsmap, not a process's RLIMIT_STACK.
1055 		 *
1056 		 * The kernel uses maxsmap to control the actual stack size limit. While we allow
1057 		 * processes to set RLIMIT_STACK to RLIM_INFINITY (UNIX 03), accessing memory
1058 		 * beyond the maxsmap will still trigger an exception.
1059 		 *
1060 		 * stack_rlim is used to store the user-defined RLIMIT_STACK values while we adjust
1061 		 * the stack size using kernel limit (i.e. maxsmap).
1062 		 */
1063 		if (newrlim->rlim_cur > maxsmap ||
1064 		    newrlim->rlim_max > maxsmap) {
1065 			if (newrlim->rlim_cur > maxsmap) {
1066 				stack_rlim.rlim_cur = newrlim->rlim_cur;
1067 				newrlim->rlim_cur = maxsmap;
1068 			}
1069 			if (newrlim->rlim_max > maxsmap) {
1070 				stack_rlim.rlim_max = newrlim->rlim_max;
1071 				newrlim->rlim_max = maxsmap;
1072 			}
1073 		}
1074 
1075 		/*
1076 		 * Stack is allocated to the max at exec time with only
1077 		 * "rlim_cur" bytes accessible.  If stack limit is going
1078 		 * up make more accessible, if going down make inaccessible.
1079 		 */
1080 		if (newrlim->rlim_cur > rlim.rlim_cur) {
1081 			mach_vm_offset_t addr;
1082 			mach_vm_size_t size;
1083 
1084 			/* grow stack */
1085 			size = newrlim->rlim_cur;
1086 			if (round_page_overflow(size, &size)) {
1087 				error = EINVAL;
1088 				goto out;
1089 			}
1090 			size -= round_page_64(rlim.rlim_cur);
1091 
1092 			addr = (mach_vm_offset_t)(p->user_stack - round_page_64(newrlim->rlim_cur));
1093 			kr = mach_vm_protect(current_map(), addr, size, FALSE, VM_PROT_DEFAULT);
1094 			if (kr != KERN_SUCCESS) {
1095 				error = EINVAL;
1096 				goto out;
1097 			}
1098 		} else if (newrlim->rlim_cur < rlim.rlim_cur) {
1099 			mach_vm_offset_t addr;
1100 			mach_vm_size_t size;
1101 			uint64_t cur_sp;
1102 
1103 			/* shrink stack */
1104 
1105 			/*
1106 			 * First check if new stack limit would agree
1107 			 * with current stack usage.
1108 			 * Get the current thread's stack pointer...
1109 			 */
1110 			cur_sp = thread_adjuserstack(current_thread(), 0);
1111 			if (cur_sp <= p->user_stack &&
1112 			    cur_sp > (p->user_stack - round_page_64(rlim.rlim_cur))) {
1113 				/* stack pointer is in main stack */
1114 				if (cur_sp <= (p->user_stack - round_page_64(newrlim->rlim_cur))) {
1115 					/*
1116 					 * New limit would cause current usage to be invalid:
1117 					 * reject new limit.
1118 					 */
1119 					error =  EINVAL;
1120 					goto out;
1121 				}
1122 			} else {
1123 				/* not on the main stack: reject */
1124 				error =  EINVAL;
1125 				goto out;
1126 			}
1127 
1128 			size = round_page_64(rlim.rlim_cur);
1129 			size -= round_page_64(rlim.rlim_cur);
1130 
1131 			addr = (mach_vm_offset_t)(p->user_stack - round_page_64(rlim.rlim_cur));
1132 
1133 			kr = mach_vm_protect(current_map(), addr, size, FALSE, VM_PROT_NONE);
1134 			if (kr != KERN_SUCCESS) {
1135 				error =  EINVAL;
1136 				goto out;
1137 			}
1138 		} else {
1139 			/* no change ... */
1140 		}
1141 
1142 		/*
1143 		 * We've adjusted the process's stack region. If the user-defined limit is greater
1144 		 * than maxsmap, we need to reflect this change in rlimit interface.
1145 		 */
1146 		if (stack_rlim.rlim_cur != 0) {
1147 			newrlim->rlim_cur = stack_rlim.rlim_cur;
1148 		}
1149 		if (stack_rlim.rlim_max != 0) {
1150 			newrlim->rlim_max = stack_rlim.rlim_max;
1151 		}
1152 		break;
1153 
1154 	case RLIMIT_NOFILE:
1155 		/*
1156 		 * Nothing to be done here as we already performed the sanity checks before entering the switch code block.
1157 		 * The real NOFILE limits enforced by the kernel is capped at MIN(RLIMIT_NOFILE, maxfilesperproc)
1158 		 */
1159 		break;
1160 
1161 	case RLIMIT_AS:
1162 		/* Over to Mach VM to validate the new address space limit */
1163 		if (vm_map_set_size_limit(current_map(), newrlim->rlim_cur) != KERN_SUCCESS) {
1164 			/* The limit specified cannot be lowered because current usage is already higher than the limit. */
1165 			error =  EINVAL;
1166 			goto out;
1167 		}
1168 		break;
1169 
1170 	case RLIMIT_NPROC:
1171 		/*
1172 		 * Only root can set to the maxproc limits, as it is
1173 		 * systemwide resource; all others are limited to
1174 		 * maxprocperuid (presumably less than maxproc).
1175 		 */
1176 		if (kauth_cred_issuser(kauth_cred_get())) {
1177 			if (newrlim->rlim_cur > (rlim_t)maxproc) {
1178 				newrlim->rlim_cur = maxproc;
1179 			}
1180 			if (newrlim->rlim_max > (rlim_t)maxproc) {
1181 				newrlim->rlim_max = maxproc;
1182 			}
1183 		} else {
1184 			if (newrlim->rlim_cur > (rlim_t)maxprocperuid) {
1185 				newrlim->rlim_cur = maxprocperuid;
1186 			}
1187 			if (newrlim->rlim_max > (rlim_t)maxprocperuid) {
1188 				newrlim->rlim_max = maxprocperuid;
1189 			}
1190 		}
1191 		break;
1192 
1193 	case RLIMIT_MEMLOCK:
1194 		/*
1195 		 * Tell the Mach VM layer about the new limit value.
1196 		 */
1197 		newrlim->rlim_cur = (vm_size_t)newrlim->rlim_cur;
1198 		vm_map_set_user_wire_limit(current_map(), (vm_size_t)newrlim->rlim_cur);
1199 		break;
1200 	} /* switch... */
1201 
1202 	/* Everything checks out and we are now ready to update the rlimit */
1203 	error = 0;
1204 
1205 out:
1206 
1207 	if (error == 0) {
1208 		/*
1209 		 * COW the current plimit if it's shared, otherwise update it in place.
1210 		 * Finally unblock other threads wishing to change plimit.
1211 		 */
1212 		proc_limitupdate(p, true, ^(struct plimit *plim) {
1213 			plim->pl_rlimit[which] = *newrlim;
1214 		});
1215 	} else {
1216 		/*
1217 		 * This setrlimit has failed, just leave the plimit as is and unblock other
1218 		 * threads wishing to change plimit.
1219 		 */
1220 		proc_lock(p);
1221 		proc_limitunblock(p);
1222 		proc_unlock(p);
1223 	}
1224 
1225 	return error;
1226 }
1227 
1228 /* ARGSUSED */
1229 int
getrlimit(struct proc * p,struct getrlimit_args * uap,__unused int32_t * retval)1230 getrlimit(struct proc *p, struct getrlimit_args *uap, __unused int32_t *retval)
1231 {
1232 	struct rlimit lim = {};
1233 
1234 	/*
1235 	 * Take out flag now in case we need to use it to trigger variant
1236 	 * behaviour later.
1237 	 */
1238 	uap->which &= ~_RLIMIT_POSIX_FLAG;
1239 
1240 	if (uap->which >= RLIM_NLIMITS) {
1241 		return EINVAL;
1242 	}
1243 	lim = proc_limitget(p, uap->which);
1244 	return copyout((caddr_t)&lim,
1245 	           uap->rlp, sizeof(struct rlimit));
1246 }
1247 
1248 /*
1249  * Transform the running time and tick information in proc p into user,
1250  * system, and interrupt time usage.
1251  */
1252 /* No lock on proc is held for this.. */
1253 void
calcru(struct proc * p,struct timeval * up,struct timeval * sp,struct timeval * ip)1254 calcru(struct proc *p, struct timeval *up, struct timeval *sp, struct timeval *ip)
1255 {
1256 	task_t                  task;
1257 
1258 	timerclear(up);
1259 	timerclear(sp);
1260 	if (ip != NULL) {
1261 		timerclear(ip);
1262 	}
1263 
1264 	task = proc_task(p);
1265 	if (task) {
1266 		mach_task_basic_info_data_t tinfo;
1267 		task_thread_times_info_data_t ttimesinfo;
1268 		task_events_info_data_t teventsinfo;
1269 		mach_msg_type_number_t task_info_count, task_ttimes_count;
1270 		mach_msg_type_number_t task_events_count;
1271 		struct timeval ut, st;
1272 
1273 		task_info_count = MACH_TASK_BASIC_INFO_COUNT;
1274 		task_info(task, MACH_TASK_BASIC_INFO,
1275 		    (task_info_t)&tinfo, &task_info_count);
1276 		ut.tv_sec = tinfo.user_time.seconds;
1277 		ut.tv_usec = tinfo.user_time.microseconds;
1278 		st.tv_sec = tinfo.system_time.seconds;
1279 		st.tv_usec = tinfo.system_time.microseconds;
1280 		timeradd(&ut, up, up);
1281 		timeradd(&st, sp, sp);
1282 
1283 		task_ttimes_count = TASK_THREAD_TIMES_INFO_COUNT;
1284 		task_info(task, TASK_THREAD_TIMES_INFO,
1285 		    (task_info_t)&ttimesinfo, &task_ttimes_count);
1286 
1287 		ut.tv_sec = ttimesinfo.user_time.seconds;
1288 		ut.tv_usec = ttimesinfo.user_time.microseconds;
1289 		st.tv_sec = ttimesinfo.system_time.seconds;
1290 		st.tv_usec = ttimesinfo.system_time.microseconds;
1291 		timeradd(&ut, up, up);
1292 		timeradd(&st, sp, sp);
1293 
1294 		task_events_count = TASK_EVENTS_INFO_COUNT;
1295 		task_info(task, TASK_EVENTS_INFO,
1296 		    (task_info_t)&teventsinfo, &task_events_count);
1297 
1298 		/*
1299 		 * No need to lock "p":  this does not need to be
1300 		 * completely consistent, right ?
1301 		 */
1302 		p->p_stats->p_ru.ru_minflt = (teventsinfo.faults -
1303 		    teventsinfo.pageins);
1304 		p->p_stats->p_ru.ru_majflt = teventsinfo.pageins;
1305 		p->p_stats->p_ru.ru_nivcsw = (teventsinfo.csw -
1306 		    p->p_stats->p_ru.ru_nvcsw);
1307 		if (p->p_stats->p_ru.ru_nivcsw < 0) {
1308 			p->p_stats->p_ru.ru_nivcsw = 0;
1309 		}
1310 
1311 		p->p_stats->p_ru.ru_maxrss = (long)tinfo.resident_size_max;
1312 	}
1313 }
1314 
1315 __private_extern__ void munge_user64_rusage(struct rusage *a_rusage_p, struct user64_rusage *a_user_rusage_p);
1316 __private_extern__ void munge_user32_rusage(struct rusage *a_rusage_p, struct user32_rusage *a_user_rusage_p);
1317 
1318 /* ARGSUSED */
1319 int
getrusage(struct proc * p,struct getrusage_args * uap,__unused int32_t * retval)1320 getrusage(struct proc *p, struct getrusage_args *uap, __unused int32_t *retval)
1321 {
1322 	struct rusage *rup, rubuf;
1323 	struct user64_rusage rubuf64 = {};
1324 	struct user32_rusage rubuf32 = {};
1325 	size_t retsize = sizeof(rubuf);                 /* default: 32 bits */
1326 	caddr_t retbuf = (caddr_t)&rubuf;               /* default: 32 bits */
1327 	struct timeval utime;
1328 	struct timeval stime;
1329 
1330 
1331 	switch (uap->who) {
1332 	case RUSAGE_SELF:
1333 		calcru(p, &utime, &stime, NULL);
1334 		proc_lock(p);
1335 		rup = &p->p_stats->p_ru;
1336 		rup->ru_utime = utime;
1337 		rup->ru_stime = stime;
1338 
1339 		rubuf = *rup;
1340 		proc_unlock(p);
1341 
1342 		break;
1343 
1344 	case RUSAGE_CHILDREN:
1345 		proc_lock(p);
1346 		rup = &p->p_stats->p_cru;
1347 		rubuf = *rup;
1348 		proc_unlock(p);
1349 		break;
1350 
1351 	default:
1352 		return EINVAL;
1353 	}
1354 	if (IS_64BIT_PROCESS(p)) {
1355 		retsize = sizeof(rubuf64);
1356 		retbuf = (caddr_t)&rubuf64;
1357 		munge_user64_rusage(&rubuf, &rubuf64);
1358 	} else {
1359 		retsize = sizeof(rubuf32);
1360 		retbuf = (caddr_t)&rubuf32;
1361 		munge_user32_rusage(&rubuf, &rubuf32);
1362 	}
1363 
1364 	return copyout(retbuf, uap->rusage, retsize);
1365 }
1366 
1367 void
ruadd(struct rusage * ru,struct rusage * ru2)1368 ruadd(struct rusage *ru, struct rusage *ru2)
1369 {
1370 	long *ip, *ip2;
1371 	long i;
1372 
1373 	timeradd(&ru->ru_utime, &ru2->ru_utime, &ru->ru_utime);
1374 	timeradd(&ru->ru_stime, &ru2->ru_stime, &ru->ru_stime);
1375 	if (ru->ru_maxrss < ru2->ru_maxrss) {
1376 		ru->ru_maxrss = ru2->ru_maxrss;
1377 	}
1378 	ip = &ru->ru_first; ip2 = &ru2->ru_first;
1379 	for (i = &ru->ru_last - &ru->ru_first; i >= 0; i--) {
1380 		*ip++ += *ip2++;
1381 	}
1382 }
1383 
1384 /*
1385  * Add the rusage stats of child in parent.
1386  *
1387  * It adds rusage statistics of child process and statistics of all its
1388  * children to its parent.
1389  *
1390  * Note: proc lock of parent should be held while calling this function.
1391  */
1392 void
update_rusage_info_child(struct rusage_info_child * ri,rusage_info_current * ri_current)1393 update_rusage_info_child(struct rusage_info_child *ri, rusage_info_current *ri_current)
1394 {
1395 	ri->ri_child_user_time += (ri_current->ri_user_time +
1396 	    ri_current->ri_child_user_time);
1397 	ri->ri_child_system_time += (ri_current->ri_system_time +
1398 	    ri_current->ri_child_system_time);
1399 	ri->ri_child_pkg_idle_wkups += (ri_current->ri_pkg_idle_wkups +
1400 	    ri_current->ri_child_pkg_idle_wkups);
1401 	ri->ri_child_interrupt_wkups += (ri_current->ri_interrupt_wkups +
1402 	    ri_current->ri_child_interrupt_wkups);
1403 	ri->ri_child_pageins += (ri_current->ri_pageins +
1404 	    ri_current->ri_child_pageins);
1405 	ri->ri_child_elapsed_abstime += ((ri_current->ri_proc_exit_abstime -
1406 	    ri_current->ri_proc_start_abstime) + ri_current->ri_child_elapsed_abstime);
1407 }
1408 
1409 static void
proc_limit_free(void * plimit)1410 proc_limit_free(void *plimit)
1411 {
1412 	zfree(plimit_zone, plimit);
1413 }
1414 
1415 static void
proc_limit_release(struct plimit * plimit)1416 proc_limit_release(struct plimit *plimit)
1417 {
1418 	if (os_ref_release(&plimit->pl_refcnt) == 0) {
1419 		smr_global_retire(plimit, sizeof(*plimit), proc_limit_free);
1420 	}
1421 }
1422 
1423 /*
1424  * Reading soft limit from specified resource.
1425  */
1426 rlim_t
proc_limitgetcur(proc_t p,int which)1427 proc_limitgetcur(proc_t p, int which)
1428 {
1429 	rlim_t rlim_cur;
1430 
1431 	assert(p);
1432 	assert(which < RLIM_NLIMITS);
1433 
1434 	smr_global_enter();
1435 	rlim_cur = smr_entered_load(&p->p_limit)->pl_rlimit[which].rlim_cur;
1436 	smr_global_leave();
1437 
1438 	return rlim_cur;
1439 }
1440 
1441 /*
1442  * Handle commonly asked limit that needs to be clamped with maxfilesperproc.
1443  */
1444 int
proc_limitgetcur_nofile(struct proc * p)1445 proc_limitgetcur_nofile(struct proc *p)
1446 {
1447 	rlim_t lim = proc_limitgetcur(p, RLIMIT_NOFILE);
1448 
1449 	return (int)MIN(lim, maxfilesperproc);
1450 }
1451 
1452 /*
1453  * Writing soft limit to specified resource. This is an internal function
1454  * used only by proc_exit to update RLIMIT_FSIZE in
1455  * place without invoking setrlimit.
1456  */
1457 void
proc_limitsetcur_fsize(proc_t p,rlim_t value)1458 proc_limitsetcur_fsize(proc_t p, rlim_t value)
1459 {
1460 	proc_limitupdate(p, false, ^(struct plimit *plimit) {
1461 		plimit->pl_rlimit[RLIMIT_FSIZE].rlim_cur = value;
1462 	});
1463 }
1464 
1465 struct rlimit
proc_limitget(proc_t p,int which)1466 proc_limitget(proc_t p, int which)
1467 {
1468 	struct rlimit lim;
1469 
1470 	assert(which < RLIM_NLIMITS);
1471 
1472 	smr_global_enter();
1473 	lim = smr_entered_load(&p->p_limit)->pl_rlimit[which];
1474 	smr_global_leave();
1475 
1476 	return lim;
1477 }
1478 
1479 void
proc_limitfork(proc_t parent,proc_t child)1480 proc_limitfork(proc_t parent, proc_t child)
1481 {
1482 	struct plimit *plim;
1483 
1484 	smr_global_enter();
1485 	plim = smr_entered_load(&parent->p_limit);
1486 	os_ref_retain(&plim->pl_refcnt);
1487 	smr_global_leave();
1488 
1489 	smr_init_store(&child->p_limit, plim);
1490 }
1491 
1492 void
proc_limitdrop(proc_t p)1493 proc_limitdrop(proc_t p)
1494 {
1495 	struct plimit *plimit = NULL;
1496 
1497 	proc_lock(p);
1498 	plimit = smr_serialized_load(&p->p_limit);
1499 	smr_clear_store(&p->p_limit);
1500 	proc_unlock(p);
1501 
1502 	proc_limit_release(plimit);
1503 }
1504 
1505 /*
1506  * proc_limitblock/unblock are used to serialize access to plimit
1507  * from concurrent threads within the same process.
1508  * Callers must be holding the proc lock to enter, return with
1509  * the proc lock locked
1510  */
1511 static void
proc_limitblock(proc_t p)1512 proc_limitblock(proc_t p)
1513 {
1514 	lck_mtx_assert(&p->p_mlock, LCK_MTX_ASSERT_OWNED);
1515 
1516 	while (p->p_lflag & P_LLIMCHANGE) {
1517 		p->p_lflag |= P_LLIMWAIT;
1518 		msleep(&p->p_limit, &p->p_mlock, 0, "proc_limitblock", NULL);
1519 	}
1520 	p->p_lflag |= P_LLIMCHANGE;
1521 }
1522 
1523 /*
1524  * Callers must be holding the proc lock to enter, return with
1525  * the proc lock locked
1526  */
1527 static void
proc_limitunblock(proc_t p)1528 proc_limitunblock(proc_t p)
1529 {
1530 	lck_mtx_assert(&p->p_mlock, LCK_MTX_ASSERT_OWNED);
1531 
1532 	p->p_lflag &= ~P_LLIMCHANGE;
1533 	if (p->p_lflag & P_LLIMWAIT) {
1534 		p->p_lflag &= ~P_LLIMWAIT;
1535 		wakeup(&p->p_limit);
1536 	}
1537 }
1538 
1539 /*
1540  * Perform an rlimit update (as defined by the arbitrary `update` function).
1541  *
1542  * Because plimits are accessed without holding any locks,
1543  * with only a hazard reference, the struct plimit is always
1544  * copied, updated, and replaced, to implement a const value type.
1545  */
1546 static void
1547 proc_limitupdate(proc_t p, bool unblock, void (^update)(struct plimit *))
1548 {
1549 	struct plimit  *cur_plim;
1550 	struct plimit  *copy_plim;
1551 
1552 	copy_plim = zalloc_flags(plimit_zone, Z_WAITOK | Z_ZERO | Z_NOFAIL);
1553 
1554 	proc_lock(p);
1555 
1556 	cur_plim = smr_serialized_load(&p->p_limit);
1557 
1558 	os_ref_init_count(&copy_plim->pl_refcnt, &rlimit_refgrp, 1);
1559 	bcopy(cur_plim->pl_rlimit, copy_plim->pl_rlimit,
1560 	    sizeof(struct rlimit) * RLIM_NLIMITS);
1561 
1562 	update(copy_plim);
1563 
1564 	smr_serialized_store(&p->p_limit, copy_plim);
1565 
1566 	if (unblock) {
1567 		proc_limitunblock(p);
1568 	}
1569 	proc_unlock(p);
1570 
1571 	proc_limit_release(cur_plim);
1572 }
1573 
1574 static int
1575 iopolicysys_disk(struct proc *p, int cmd, int scope, int policy, struct _iopol_param_t *iop_param);
1576 static int
1577 iopolicysys_vfs_hfs_case_sensitivity(struct proc *p, int cmd, int scope, int policy, struct _iopol_param_t *iop_param);
1578 static int
1579 iopolicysys_vfs_atime_updates(struct proc *p, int cmd, int scope, int policy, struct _iopol_param_t *iop_param);
1580 static int
1581 iopolicysys_vfs_materialize_dataless_files(struct proc *p, int cmd, int scope, int policy, struct _iopol_param_t *iop_param);
1582 static int
1583 iopolicysys_vfs_statfs_no_data_volume(struct proc *p, int cmd, int scope, int policy, struct _iopol_param_t *iop_param);
1584 static int
1585 iopolicysys_vfs_trigger_resolve(struct proc *p, int cmd, int scope, int policy, struct _iopol_param_t *iop_param);
1586 static int
1587 iopolicysys_vfs_ignore_content_protection(struct proc *p, int cmd, int scope, int policy, struct _iopol_param_t *iop_param);
1588 static int
1589 iopolicysys_vfs_ignore_node_permissions(struct proc *p, int cmd, int scope, int policy, struct _iopol_param_t *ipo_param);
1590 static int
1591 iopolicysys_vfs_skip_mtime_update(struct proc *p, int cmd, int scope, int policy, struct _iopol_param_t *iop_param);
1592 static int
1593 iopolicysys_vfs_allow_lowspace_writes(struct proc *p, int cmd, int scope, int policy, struct _iopol_param_t *iop_param);
1594 static int
1595 iopolicysys_vfs_disallow_rw_for_o_evtonly(struct proc *p, int cmd, int scope, int policy, struct _iopol_param_t *iop_param);
1596 static int iopolicysys_vfs_altlink(struct proc *p, int cmd, int scope, int policy, struct _iopol_param_t *iop_param);
1597 
1598 /*
1599  * iopolicysys
1600  *
1601  * Description:	System call MUX for use in manipulating I/O policy attributes of the current process or thread
1602  *
1603  * Parameters:	cmd				Policy command
1604  *		arg				Pointer to policy arguments
1605  *
1606  * Returns:	0				Success
1607  *		EINVAL				Invalid command or invalid policy arguments
1608  *
1609  */
1610 int
iopolicysys(struct proc * p,struct iopolicysys_args * uap,int32_t * retval)1611 iopolicysys(struct proc *p, struct iopolicysys_args *uap, int32_t *retval)
1612 {
1613 	int     error = 0;
1614 	struct _iopol_param_t iop_param;
1615 
1616 	if ((error = copyin(uap->arg, &iop_param, sizeof(iop_param))) != 0) {
1617 		goto out;
1618 	}
1619 
1620 	switch (iop_param.iop_iotype) {
1621 	case IOPOL_TYPE_DISK:
1622 		error = iopolicysys_disk(p, uap->cmd, iop_param.iop_scope, iop_param.iop_policy, &iop_param);
1623 		if (error == EIDRM) {
1624 			*retval = -2;
1625 			error = 0;
1626 		}
1627 		if (error) {
1628 			goto out;
1629 		}
1630 		break;
1631 	case IOPOL_TYPE_VFS_HFS_CASE_SENSITIVITY:
1632 		error = iopolicysys_vfs_hfs_case_sensitivity(p, uap->cmd, iop_param.iop_scope, iop_param.iop_policy, &iop_param);
1633 		if (error) {
1634 			goto out;
1635 		}
1636 		break;
1637 	case IOPOL_TYPE_VFS_ATIME_UPDATES:
1638 		error = iopolicysys_vfs_atime_updates(p, uap->cmd, iop_param.iop_scope, iop_param.iop_policy, &iop_param);
1639 		if (error) {
1640 			goto out;
1641 		}
1642 		break;
1643 	case IOPOL_TYPE_VFS_MATERIALIZE_DATALESS_FILES:
1644 		error = iopolicysys_vfs_materialize_dataless_files(p, uap->cmd, iop_param.iop_scope, iop_param.iop_policy, &iop_param);
1645 		if (error) {
1646 			goto out;
1647 		}
1648 		break;
1649 	case IOPOL_TYPE_VFS_STATFS_NO_DATA_VOLUME:
1650 		error = iopolicysys_vfs_statfs_no_data_volume(p, uap->cmd, iop_param.iop_scope, iop_param.iop_policy, &iop_param);
1651 		if (error) {
1652 			goto out;
1653 		}
1654 		break;
1655 	case IOPOL_TYPE_VFS_TRIGGER_RESOLVE:
1656 		error = iopolicysys_vfs_trigger_resolve(p, uap->cmd, iop_param.iop_scope, iop_param.iop_policy, &iop_param);
1657 		if (error) {
1658 			goto out;
1659 		}
1660 		break;
1661 	case IOPOL_TYPE_VFS_IGNORE_CONTENT_PROTECTION:
1662 		error = iopolicysys_vfs_ignore_content_protection(p, uap->cmd, iop_param.iop_scope, iop_param.iop_policy, &iop_param);
1663 		if (error) {
1664 			goto out;
1665 		}
1666 		break;
1667 	case IOPOL_TYPE_VFS_IGNORE_PERMISSIONS:
1668 		error = iopolicysys_vfs_ignore_node_permissions(p, uap->cmd, iop_param.iop_scope, iop_param.iop_policy, &iop_param);
1669 		if (error) {
1670 			goto out;
1671 		}
1672 		break;
1673 	case IOPOL_TYPE_VFS_SKIP_MTIME_UPDATE:
1674 		error = iopolicysys_vfs_skip_mtime_update(p, uap->cmd, iop_param.iop_scope, iop_param.iop_policy, &iop_param);
1675 		if (error) {
1676 			goto out;
1677 		}
1678 		break;
1679 	case IOPOL_TYPE_VFS_ALLOW_LOW_SPACE_WRITES:
1680 		error = iopolicysys_vfs_allow_lowspace_writes(p, uap->cmd, iop_param.iop_scope, iop_param.iop_policy, &iop_param);
1681 		if (error) {
1682 			goto out;
1683 		}
1684 		break;
1685 	case IOPOL_TYPE_VFS_DISALLOW_RW_FOR_O_EVTONLY:
1686 		error = iopolicysys_vfs_disallow_rw_for_o_evtonly(p, uap->cmd, iop_param.iop_scope, iop_param.iop_policy, &iop_param);
1687 		if (error) {
1688 			goto out;
1689 		}
1690 		break;
1691 	case IOPOL_TYPE_VFS_ALTLINK:
1692 		error = iopolicysys_vfs_altlink(p, uap->cmd, iop_param.iop_scope, iop_param.iop_policy, &iop_param);
1693 		if (error) {
1694 			goto out;
1695 		}
1696 		break;
1697 
1698 	default:
1699 		error = EINVAL;
1700 		goto out;
1701 	}
1702 
1703 	/* Individual iotype handlers are expected to update iop_param, if requested with a GET command */
1704 	if (uap->cmd == IOPOL_CMD_GET) {
1705 		error = copyout((caddr_t)&iop_param, uap->arg, sizeof(iop_param));
1706 		if (error) {
1707 			goto out;
1708 		}
1709 	}
1710 
1711 out:
1712 	return error;
1713 }
1714 
1715 static int
iopolicysys_disk(struct proc * p __unused,int cmd,int scope,int policy,struct _iopol_param_t * iop_param)1716 iopolicysys_disk(struct proc *p __unused, int cmd, int scope, int policy, struct _iopol_param_t *iop_param)
1717 {
1718 	int                     error = 0;
1719 	thread_t        thread;
1720 	int                     policy_flavor;
1721 
1722 	/* Validate scope */
1723 	switch (scope) {
1724 	case IOPOL_SCOPE_PROCESS:
1725 		thread = THREAD_NULL;
1726 		policy_flavor = TASK_POLICY_IOPOL;
1727 		break;
1728 
1729 	case IOPOL_SCOPE_THREAD:
1730 		thread = current_thread();
1731 		policy_flavor = TASK_POLICY_IOPOL;
1732 
1733 		/* Not allowed to combine QoS and (non-PASSIVE) IO policy, doing so strips the QoS */
1734 		if (cmd == IOPOL_CMD_SET && thread_has_qos_policy(thread)) {
1735 			switch (policy) {
1736 			case IOPOL_DEFAULT:
1737 			case IOPOL_PASSIVE:
1738 				break;
1739 			case IOPOL_UTILITY:
1740 			case IOPOL_THROTTLE:
1741 			case IOPOL_IMPORTANT:
1742 			case IOPOL_STANDARD:
1743 				if (!thread_is_static_param(thread)) {
1744 					thread_remove_qos_policy(thread);
1745 					/*
1746 					 * This is not an error case, this is to return a marker to user-space that
1747 					 * we stripped the thread of its QoS class.
1748 					 */
1749 					error = EIDRM;
1750 					break;
1751 				}
1752 				OS_FALLTHROUGH;
1753 			default:
1754 				error = EINVAL;
1755 				goto out;
1756 			}
1757 		}
1758 		break;
1759 
1760 	case IOPOL_SCOPE_DARWIN_BG:
1761 #if !defined(XNU_TARGET_OS_OSX)
1762 		/* We don't want this on platforms outside of macOS as BG is always IOPOL_THROTTLE */
1763 		error = ENOTSUP;
1764 		goto out;
1765 #else /* !defined(XNU_TARGET_OS_OSX) */
1766 		thread = THREAD_NULL;
1767 		policy_flavor = TASK_POLICY_DARWIN_BG_IOPOL;
1768 		break;
1769 #endif /* !defined(XNU_TARGET_OS_OSX) */
1770 
1771 	default:
1772 		error = EINVAL;
1773 		goto out;
1774 	}
1775 
1776 	/* Validate policy */
1777 	if (cmd == IOPOL_CMD_SET) {
1778 		switch (policy) {
1779 		case IOPOL_DEFAULT:
1780 			if (scope == IOPOL_SCOPE_DARWIN_BG) {
1781 				/* the current default BG throttle level is UTILITY */
1782 				policy = IOPOL_UTILITY;
1783 			} else {
1784 				policy = IOPOL_IMPORTANT;
1785 			}
1786 			break;
1787 		case IOPOL_UTILITY:
1788 		/* fall-through */
1789 		case IOPOL_THROTTLE:
1790 			/* These levels are OK */
1791 			break;
1792 		case IOPOL_IMPORTANT:
1793 		/* fall-through */
1794 		case IOPOL_STANDARD:
1795 		/* fall-through */
1796 		case IOPOL_PASSIVE:
1797 			if (scope == IOPOL_SCOPE_DARWIN_BG) {
1798 				/* These levels are invalid for BG */
1799 				error = EINVAL;
1800 				goto out;
1801 			} else {
1802 				/* OK for other scopes */
1803 			}
1804 			break;
1805 		default:
1806 			error = EINVAL;
1807 			goto out;
1808 		}
1809 	}
1810 
1811 	/* Perform command */
1812 	switch (cmd) {
1813 	case IOPOL_CMD_SET:
1814 		if (thread != THREAD_NULL) {
1815 			proc_set_thread_policy(thread, TASK_POLICY_INTERNAL, policy_flavor, policy);
1816 		} else {
1817 			proc_set_task_policy(current_task(), TASK_POLICY_INTERNAL, policy_flavor, policy);
1818 		}
1819 		break;
1820 	case IOPOL_CMD_GET:
1821 		if (thread != THREAD_NULL) {
1822 			policy = proc_get_thread_policy(thread, TASK_POLICY_INTERNAL, policy_flavor);
1823 		} else {
1824 			policy = proc_get_task_policy(current_task(), TASK_POLICY_INTERNAL, policy_flavor);
1825 		}
1826 		iop_param->iop_policy = policy;
1827 		break;
1828 	default:
1829 		error = EINVAL;         /* unknown command */
1830 		break;
1831 	}
1832 
1833 out:
1834 	return error;
1835 }
1836 
1837 static int
iopolicysys_vfs_hfs_case_sensitivity(struct proc * p,int cmd,int scope,int policy,struct _iopol_param_t * iop_param)1838 iopolicysys_vfs_hfs_case_sensitivity(struct proc *p, int cmd, int scope, int policy, struct _iopol_param_t *iop_param)
1839 {
1840 	int                     error = 0;
1841 
1842 	/* Validate scope */
1843 	switch (scope) {
1844 	case IOPOL_SCOPE_PROCESS:
1845 		/* Only process OK */
1846 		break;
1847 	default:
1848 		error = EINVAL;
1849 		goto out;
1850 	}
1851 
1852 	/* Validate policy */
1853 	if (cmd == IOPOL_CMD_SET) {
1854 		switch (policy) {
1855 		case IOPOL_VFS_HFS_CASE_SENSITIVITY_DEFAULT:
1856 		/* fall-through */
1857 		case IOPOL_VFS_HFS_CASE_SENSITIVITY_FORCE_CASE_SENSITIVE:
1858 			/* These policies are OK */
1859 			break;
1860 		default:
1861 			error = EINVAL;
1862 			goto out;
1863 		}
1864 	}
1865 
1866 	/* Perform command */
1867 	switch (cmd) {
1868 	case IOPOL_CMD_SET:
1869 		if (0 == kauth_cred_issuser(kauth_cred_get())) {
1870 			/* If it's a non-root process, it needs to have the entitlement to set the policy */
1871 			boolean_t entitled = FALSE;
1872 			entitled = IOCurrentTaskHasEntitlement("com.apple.private.iopol.case_sensitivity");
1873 			if (!entitled) {
1874 				error = EPERM;
1875 				goto out;
1876 			}
1877 		}
1878 
1879 		switch (policy) {
1880 		case IOPOL_VFS_HFS_CASE_SENSITIVITY_DEFAULT:
1881 			OSBitAndAtomic16(~((uint32_t)P_VFS_IOPOLICY_FORCE_HFS_CASE_SENSITIVITY), &p->p_vfs_iopolicy);
1882 			break;
1883 		case IOPOL_VFS_HFS_CASE_SENSITIVITY_FORCE_CASE_SENSITIVE:
1884 			OSBitOrAtomic16((uint32_t)P_VFS_IOPOLICY_FORCE_HFS_CASE_SENSITIVITY, &p->p_vfs_iopolicy);
1885 			break;
1886 		default:
1887 			error = EINVAL;
1888 			goto out;
1889 		}
1890 
1891 		break;
1892 	case IOPOL_CMD_GET:
1893 		iop_param->iop_policy = (p->p_vfs_iopolicy & P_VFS_IOPOLICY_FORCE_HFS_CASE_SENSITIVITY)
1894 		    ? IOPOL_VFS_HFS_CASE_SENSITIVITY_FORCE_CASE_SENSITIVE
1895 		    : IOPOL_VFS_HFS_CASE_SENSITIVITY_DEFAULT;
1896 		break;
1897 	default:
1898 		error = EINVAL;         /* unknown command */
1899 		break;
1900 	}
1901 
1902 out:
1903 	return error;
1904 }
1905 
1906 static inline int
get_thread_atime_policy(struct uthread * ut)1907 get_thread_atime_policy(struct uthread *ut)
1908 {
1909 	return (ut->uu_flag & UT_ATIME_UPDATE) ? IOPOL_ATIME_UPDATES_OFF : IOPOL_ATIME_UPDATES_DEFAULT;
1910 }
1911 
1912 static inline void
set_thread_atime_policy(struct uthread * ut,int policy)1913 set_thread_atime_policy(struct uthread *ut, int policy)
1914 {
1915 	if (policy == IOPOL_ATIME_UPDATES_OFF) {
1916 		ut->uu_flag |= UT_ATIME_UPDATE;
1917 	} else {
1918 		ut->uu_flag &= ~UT_ATIME_UPDATE;
1919 	}
1920 }
1921 
1922 static inline void
set_task_atime_policy(struct proc * p,int policy)1923 set_task_atime_policy(struct proc *p, int policy)
1924 {
1925 	if (policy == IOPOL_ATIME_UPDATES_OFF) {
1926 		OSBitOrAtomic16((uint16_t)P_VFS_IOPOLICY_ATIME_UPDATES, &p->p_vfs_iopolicy);
1927 	} else {
1928 		OSBitAndAtomic16(~((uint16_t)P_VFS_IOPOLICY_ATIME_UPDATES), &p->p_vfs_iopolicy);
1929 	}
1930 }
1931 
1932 static inline int
get_task_atime_policy(struct proc * p)1933 get_task_atime_policy(struct proc *p)
1934 {
1935 	return (p->p_vfs_iopolicy & P_VFS_IOPOLICY_ATIME_UPDATES) ? IOPOL_ATIME_UPDATES_OFF : IOPOL_ATIME_UPDATES_DEFAULT;
1936 }
1937 
1938 static int
iopolicysys_vfs_atime_updates(struct proc * p __unused,int cmd,int scope,int policy,struct _iopol_param_t * iop_param)1939 iopolicysys_vfs_atime_updates(struct proc *p __unused, int cmd, int scope, int policy, struct _iopol_param_t *iop_param)
1940 {
1941 	int                     error = 0;
1942 	thread_t                thread;
1943 
1944 	/* Validate scope */
1945 	switch (scope) {
1946 	case IOPOL_SCOPE_THREAD:
1947 		thread = current_thread();
1948 		break;
1949 	case IOPOL_SCOPE_PROCESS:
1950 		thread = THREAD_NULL;
1951 		break;
1952 	default:
1953 		error = EINVAL;
1954 		goto out;
1955 	}
1956 
1957 	/* Validate policy */
1958 	if (cmd == IOPOL_CMD_SET) {
1959 		switch (policy) {
1960 		case IOPOL_ATIME_UPDATES_DEFAULT:
1961 		case IOPOL_ATIME_UPDATES_OFF:
1962 			break;
1963 		default:
1964 			error = EINVAL;
1965 			goto out;
1966 		}
1967 	}
1968 
1969 	/* Perform command */
1970 	switch (cmd) {
1971 	case IOPOL_CMD_SET:
1972 		if (thread != THREAD_NULL) {
1973 			set_thread_atime_policy(get_bsdthread_info(thread), policy);
1974 		} else {
1975 			set_task_atime_policy(p, policy);
1976 		}
1977 		break;
1978 	case IOPOL_CMD_GET:
1979 		if (thread != THREAD_NULL) {
1980 			policy = get_thread_atime_policy(get_bsdthread_info(thread));
1981 		} else {
1982 			policy = get_task_atime_policy(p);
1983 		}
1984 		iop_param->iop_policy = policy;
1985 		break;
1986 	default:
1987 		error = EINVAL;         /* unknown command */
1988 		break;
1989 	}
1990 
1991 out:
1992 	return error;
1993 }
1994 
1995 static inline int
get_thread_materialize_policy(struct uthread * ut)1996 get_thread_materialize_policy(struct uthread *ut)
1997 {
1998 	if (ut->uu_flag & UT_NSPACE_NODATALESSFAULTS) {
1999 		return IOPOL_MATERIALIZE_DATALESS_FILES_OFF;
2000 	} else if (ut->uu_flag & UT_NSPACE_FORCEDATALESSFAULTS) {
2001 		return IOPOL_MATERIALIZE_DATALESS_FILES_ON;
2002 	}
2003 	/* Default thread behavior is "inherit process behavior". */
2004 	return IOPOL_MATERIALIZE_DATALESS_FILES_DEFAULT;
2005 }
2006 
2007 static inline void
set_thread_materialize_policy(struct uthread * ut,int policy)2008 set_thread_materialize_policy(struct uthread *ut, int policy)
2009 {
2010 	if (policy == IOPOL_MATERIALIZE_DATALESS_FILES_OFF) {
2011 		ut->uu_flag &= ~UT_NSPACE_FORCEDATALESSFAULTS;
2012 		ut->uu_flag |= UT_NSPACE_NODATALESSFAULTS;
2013 	} else if (policy == IOPOL_MATERIALIZE_DATALESS_FILES_ON) {
2014 		ut->uu_flag &= ~UT_NSPACE_NODATALESSFAULTS;
2015 		ut->uu_flag |= UT_NSPACE_FORCEDATALESSFAULTS;
2016 	} else {
2017 		ut->uu_flag &= ~(UT_NSPACE_NODATALESSFAULTS | UT_NSPACE_FORCEDATALESSFAULTS);
2018 	}
2019 }
2020 
2021 static inline void
set_proc_materialize_policy(struct proc * p,int policy)2022 set_proc_materialize_policy(struct proc *p, int policy)
2023 {
2024 	if (policy == IOPOL_MATERIALIZE_DATALESS_FILES_DEFAULT) {
2025 		/*
2026 		 * Caller has specified "use the default policy".
2027 		 * The default policy is to NOT materialize dataless
2028 		 * files.
2029 		 */
2030 		policy = IOPOL_MATERIALIZE_DATALESS_FILES_OFF;
2031 	}
2032 	if (policy == IOPOL_MATERIALIZE_DATALESS_FILES_ON) {
2033 		OSBitOrAtomic16((uint16_t)P_VFS_IOPOLICY_MATERIALIZE_DATALESS_FILES, &p->p_vfs_iopolicy);
2034 	} else {
2035 		OSBitAndAtomic16(~((uint16_t)P_VFS_IOPOLICY_MATERIALIZE_DATALESS_FILES), &p->p_vfs_iopolicy);
2036 	}
2037 }
2038 
2039 static int
get_proc_materialize_policy(struct proc * p)2040 get_proc_materialize_policy(struct proc *p)
2041 {
2042 	return (p->p_vfs_iopolicy & P_VFS_IOPOLICY_MATERIALIZE_DATALESS_FILES) ? IOPOL_MATERIALIZE_DATALESS_FILES_ON : IOPOL_MATERIALIZE_DATALESS_FILES_OFF;
2043 }
2044 
2045 static int
iopolicysys_vfs_materialize_dataless_files(struct proc * p __unused,int cmd,int scope,int policy,struct _iopol_param_t * iop_param)2046 iopolicysys_vfs_materialize_dataless_files(struct proc *p __unused, int cmd, int scope, int policy, struct _iopol_param_t *iop_param)
2047 {
2048 	int                     error = 0;
2049 	thread_t                thread;
2050 
2051 	/* Validate scope */
2052 	switch (scope) {
2053 	case IOPOL_SCOPE_THREAD:
2054 		thread = current_thread();
2055 		break;
2056 	case IOPOL_SCOPE_PROCESS:
2057 		thread = THREAD_NULL;
2058 		break;
2059 	default:
2060 		error = EINVAL;
2061 		goto out;
2062 	}
2063 
2064 	/* Validate policy */
2065 	if (cmd == IOPOL_CMD_SET) {
2066 		switch (policy) {
2067 		case IOPOL_MATERIALIZE_DATALESS_FILES_DEFAULT:
2068 		case IOPOL_MATERIALIZE_DATALESS_FILES_OFF:
2069 		case IOPOL_MATERIALIZE_DATALESS_FILES_ON:
2070 			break;
2071 		default:
2072 			error = EINVAL;
2073 			goto out;
2074 		}
2075 	}
2076 
2077 	/* Perform command */
2078 	switch (cmd) {
2079 	case IOPOL_CMD_SET:
2080 		if (thread != THREAD_NULL) {
2081 			set_thread_materialize_policy(get_bsdthread_info(thread), policy);
2082 		} else {
2083 			set_proc_materialize_policy(p, policy);
2084 		}
2085 		break;
2086 	case IOPOL_CMD_GET:
2087 		if (thread != THREAD_NULL) {
2088 			policy = get_thread_materialize_policy(get_bsdthread_info(thread));
2089 		} else {
2090 			policy = get_proc_materialize_policy(p);
2091 		}
2092 		iop_param->iop_policy = policy;
2093 		break;
2094 	default:
2095 		error = EINVAL;         /* unknown command */
2096 		break;
2097 	}
2098 
2099 out:
2100 	return error;
2101 }
2102 
2103 static int
iopolicysys_vfs_statfs_no_data_volume(struct proc * p __unused,int cmd,int scope,int policy,struct _iopol_param_t * iop_param)2104 iopolicysys_vfs_statfs_no_data_volume(struct proc *p __unused, int cmd,
2105     int scope, int policy, struct _iopol_param_t *iop_param)
2106 {
2107 	int error = 0;
2108 
2109 	/* Validate scope */
2110 	switch (scope) {
2111 	case IOPOL_SCOPE_PROCESS:
2112 		/* Only process OK */
2113 		break;
2114 	default:
2115 		error = EINVAL;
2116 		goto out;
2117 	}
2118 
2119 	/* Validate policy */
2120 	if (cmd == IOPOL_CMD_SET) {
2121 		switch (policy) {
2122 		case IOPOL_VFS_STATFS_NO_DATA_VOLUME_DEFAULT:
2123 		/* fall-through */
2124 		case IOPOL_VFS_STATFS_FORCE_NO_DATA_VOLUME:
2125 			/* These policies are OK */
2126 			break;
2127 		default:
2128 			error = EINVAL;
2129 			goto out;
2130 		}
2131 	}
2132 
2133 	/* Perform command */
2134 	switch (cmd) {
2135 	case IOPOL_CMD_SET:
2136 		if (0 == kauth_cred_issuser(kauth_cred_get())) {
2137 			/* If it's a non-root process, it needs to have the entitlement to set the policy */
2138 			boolean_t entitled = FALSE;
2139 			entitled = IOCurrentTaskHasEntitlement("com.apple.private.iopol.case_sensitivity");
2140 			if (!entitled) {
2141 				error = EPERM;
2142 				goto out;
2143 			}
2144 		}
2145 
2146 		switch (policy) {
2147 		case IOPOL_VFS_STATFS_NO_DATA_VOLUME_DEFAULT:
2148 			OSBitAndAtomic16(~((uint32_t)P_VFS_IOPOLICY_STATFS_NO_DATA_VOLUME), &p->p_vfs_iopolicy);
2149 			break;
2150 		case IOPOL_VFS_STATFS_FORCE_NO_DATA_VOLUME:
2151 			OSBitOrAtomic16((uint32_t)P_VFS_IOPOLICY_STATFS_NO_DATA_VOLUME, &p->p_vfs_iopolicy);
2152 			break;
2153 		default:
2154 			error = EINVAL;
2155 			goto out;
2156 		}
2157 
2158 		break;
2159 	case IOPOL_CMD_GET:
2160 		iop_param->iop_policy = (p->p_vfs_iopolicy & P_VFS_IOPOLICY_STATFS_NO_DATA_VOLUME)
2161 		    ? IOPOL_VFS_STATFS_FORCE_NO_DATA_VOLUME
2162 		    : IOPOL_VFS_STATFS_NO_DATA_VOLUME_DEFAULT;
2163 		break;
2164 	default:
2165 		error = EINVAL;         /* unknown command */
2166 		break;
2167 	}
2168 
2169 out:
2170 	return error;
2171 }
2172 
2173 static int
iopolicysys_vfs_trigger_resolve(struct proc * p __unused,int cmd,int scope,int policy,struct _iopol_param_t * iop_param)2174 iopolicysys_vfs_trigger_resolve(struct proc *p __unused, int cmd,
2175     int scope, int policy, struct _iopol_param_t *iop_param)
2176 {
2177 	int error = 0;
2178 
2179 	/* Validate scope */
2180 	switch (scope) {
2181 	case IOPOL_SCOPE_PROCESS:
2182 		/* Only process OK */
2183 		break;
2184 	default:
2185 		error = EINVAL;
2186 		goto out;
2187 	}
2188 
2189 	/* Validate policy */
2190 	if (cmd == IOPOL_CMD_SET) {
2191 		switch (policy) {
2192 		case IOPOL_VFS_TRIGGER_RESOLVE_DEFAULT:
2193 		/* fall-through */
2194 		case IOPOL_VFS_TRIGGER_RESOLVE_OFF:
2195 			/* These policies are OK */
2196 			break;
2197 		default:
2198 			error = EINVAL;
2199 			goto out;
2200 		}
2201 	}
2202 
2203 	/* Perform command */
2204 	switch (cmd) {
2205 	case IOPOL_CMD_SET:
2206 		switch (policy) {
2207 		case IOPOL_VFS_TRIGGER_RESOLVE_DEFAULT:
2208 			OSBitAndAtomic16(~((uint32_t)P_VFS_IOPOLICY_TRIGGER_RESOLVE_DISABLE), &p->p_vfs_iopolicy);
2209 			break;
2210 		case IOPOL_VFS_TRIGGER_RESOLVE_OFF:
2211 			OSBitOrAtomic16((uint32_t)P_VFS_IOPOLICY_TRIGGER_RESOLVE_DISABLE, &p->p_vfs_iopolicy);
2212 			break;
2213 		default:
2214 			error = EINVAL;
2215 			goto out;
2216 		}
2217 
2218 		break;
2219 	case IOPOL_CMD_GET:
2220 		iop_param->iop_policy = (p->p_vfs_iopolicy & P_VFS_IOPOLICY_TRIGGER_RESOLVE_DISABLE)
2221 		    ? IOPOL_VFS_TRIGGER_RESOLVE_OFF
2222 		    : IOPOL_VFS_TRIGGER_RESOLVE_DEFAULT;
2223 		break;
2224 	default:
2225 		error = EINVAL;         /* unknown command */
2226 		break;
2227 	}
2228 
2229 out:
2230 	return error;
2231 }
2232 
2233 static int
iopolicysys_vfs_ignore_content_protection(struct proc * p,int cmd,int scope,int policy,struct _iopol_param_t * iop_param)2234 iopolicysys_vfs_ignore_content_protection(struct proc *p, int cmd, int scope,
2235     int policy, struct _iopol_param_t *iop_param)
2236 {
2237 	int error = 0;
2238 
2239 	/* Validate scope */
2240 	switch (scope) {
2241 	case IOPOL_SCOPE_PROCESS:
2242 		/* Only process OK */
2243 		break;
2244 	default:
2245 		error = EINVAL;
2246 		goto out;
2247 	}
2248 
2249 	/* Validate policy */
2250 	if (cmd == IOPOL_CMD_SET) {
2251 		switch (policy) {
2252 		case IOPOL_VFS_CONTENT_PROTECTION_DEFAULT:
2253 			OS_FALLTHROUGH;
2254 		case IOPOL_VFS_CONTENT_PROTECTION_IGNORE:
2255 			/* These policies are OK */
2256 			break;
2257 		default:
2258 			error = EINVAL;
2259 			goto out;
2260 		}
2261 	}
2262 
2263 	/* Perform command */
2264 	switch (cmd) {
2265 	case IOPOL_CMD_SET:
2266 		if (0 == kauth_cred_issuser(kauth_cred_get())) {
2267 			/* If it's a non-root process, it needs to have the entitlement to set the policy */
2268 			boolean_t entitled = FALSE;
2269 			entitled = IOCurrentTaskHasEntitlement("com.apple.private.iopol.case_sensitivity");
2270 			if (!entitled) {
2271 				error = EPERM;
2272 				goto out;
2273 			}
2274 		}
2275 
2276 		switch (policy) {
2277 		case IOPOL_VFS_CONTENT_PROTECTION_DEFAULT:
2278 			os_atomic_andnot(&p->p_vfs_iopolicy, P_VFS_IOPOLICY_IGNORE_CONTENT_PROTECTION, relaxed);
2279 			break;
2280 		case IOPOL_VFS_CONTENT_PROTECTION_IGNORE:
2281 			os_atomic_or(&p->p_vfs_iopolicy, P_VFS_IOPOLICY_IGNORE_CONTENT_PROTECTION, relaxed);
2282 			break;
2283 		default:
2284 			error = EINVAL;
2285 			goto out;
2286 		}
2287 
2288 		break;
2289 	case IOPOL_CMD_GET:
2290 		iop_param->iop_policy = (os_atomic_load(&p->p_vfs_iopolicy, relaxed) & P_VFS_IOPOLICY_IGNORE_CONTENT_PROTECTION)
2291 		    ? IOPOL_VFS_CONTENT_PROTECTION_IGNORE
2292 		    : IOPOL_VFS_CONTENT_PROTECTION_DEFAULT;
2293 		break;
2294 	default:
2295 		error = EINVAL;         /* unknown command */
2296 		break;
2297 	}
2298 
2299 out:
2300 	return error;
2301 }
2302 
2303 #define AUTHORIZED_ACCESS_ENTITLEMENT \
2304 	"com.apple.private.vfs.authorized-access"
2305 int
iopolicysys_vfs_ignore_node_permissions(struct proc * p,int cmd,int scope,int policy,__unused struct _iopol_param_t * iop_param)2306 iopolicysys_vfs_ignore_node_permissions(struct proc *p, int cmd, int scope,
2307     int policy, __unused struct _iopol_param_t *iop_param)
2308 {
2309 	int error = EINVAL;
2310 
2311 	switch (scope) {
2312 	case IOPOL_SCOPE_PROCESS:
2313 		break;
2314 	default:
2315 		goto out;
2316 	}
2317 
2318 	switch (cmd) {
2319 	case IOPOL_CMD_GET:
2320 		policy = os_atomic_load(&p->p_vfs_iopolicy, relaxed) & P_VFS_IOPOLICY_IGNORE_NODE_PERMISSIONS ?
2321 		    IOPOL_VFS_IGNORE_PERMISSIONS_ON : IOPOL_VFS_IGNORE_PERMISSIONS_OFF;
2322 		iop_param->iop_policy = policy;
2323 		goto out_ok;
2324 	case IOPOL_CMD_SET:
2325 		/* SET is handled after the switch */
2326 		break;
2327 	default:
2328 		goto out;
2329 	}
2330 
2331 	if (!IOCurrentTaskHasEntitlement(AUTHORIZED_ACCESS_ENTITLEMENT)) {
2332 		error = EPERM;
2333 		goto out;
2334 	}
2335 
2336 	switch (policy) {
2337 	case IOPOL_VFS_IGNORE_PERMISSIONS_OFF:
2338 		os_atomic_andnot(&p->p_vfs_iopolicy, P_VFS_IOPOLICY_IGNORE_NODE_PERMISSIONS, relaxed);
2339 		break;
2340 	case IOPOL_VFS_IGNORE_PERMISSIONS_ON:
2341 		os_atomic_or(&p->p_vfs_iopolicy, P_VFS_IOPOLICY_IGNORE_NODE_PERMISSIONS, relaxed);
2342 		break;
2343 	default:
2344 		break;
2345 	}
2346 
2347 out_ok:
2348 	error = 0;
2349 out:
2350 	return error;
2351 }
2352 
2353 #define SKIP_MTIME_UPDATE_ENTITLEMENT \
2354 	"com.apple.private.vfs.skip-mtime-updates"
2355 int
iopolicysys_vfs_skip_mtime_update(struct proc * p,int cmd,int scope,int policy,__unused struct _iopol_param_t * iop_param)2356 iopolicysys_vfs_skip_mtime_update(struct proc *p, int cmd, int scope,
2357     int policy, __unused struct _iopol_param_t *iop_param)
2358 {
2359 	int error = EINVAL;
2360 
2361 	switch (scope) {
2362 	case IOPOL_SCOPE_PROCESS:
2363 		break;
2364 	default:
2365 		goto out;
2366 	}
2367 
2368 	switch (cmd) {
2369 	case IOPOL_CMD_GET:
2370 		policy = os_atomic_load(&p->p_vfs_iopolicy, relaxed) & P_VFS_IOPOLICY_SKIP_MTIME_UPDATE ?
2371 		    IOPOL_VFS_SKIP_MTIME_UPDATE_ON : IOPOL_VFS_SKIP_MTIME_UPDATE_OFF;
2372 		iop_param->iop_policy = policy;
2373 		goto out_ok;
2374 	case IOPOL_CMD_SET:
2375 		break;
2376 	default:
2377 		break;
2378 	}
2379 
2380 	if (!IOCurrentTaskHasEntitlement(SKIP_MTIME_UPDATE_ENTITLEMENT)) {
2381 		error = EPERM;
2382 		goto out;
2383 	}
2384 
2385 	switch (policy) {
2386 	case IOPOL_VFS_SKIP_MTIME_UPDATE_OFF:
2387 		os_atomic_andnot(&p->p_vfs_iopolicy, P_VFS_IOPOLICY_SKIP_MTIME_UPDATE, relaxed);
2388 		break;
2389 	case IOPOL_VFS_SKIP_MTIME_UPDATE_ON:
2390 		os_atomic_or(&p->p_vfs_iopolicy, P_VFS_IOPOLICY_SKIP_MTIME_UPDATE, relaxed);
2391 		break;
2392 	default:
2393 		break;
2394 	}
2395 
2396 out_ok:
2397 	error = 0;
2398 out:
2399 	return error;
2400 }
2401 
2402 #define ALLOW_LOW_SPACE_WRITES_ENTITLEMENT \
2403 	"com.apple.private.vfs.allow-low-space-writes"
2404 static int
iopolicysys_vfs_allow_lowspace_writes(struct proc * p,int cmd,int scope,int policy,__unused struct _iopol_param_t * iop_param)2405 iopolicysys_vfs_allow_lowspace_writes(struct proc *p, int cmd, int scope,
2406     int policy, __unused struct _iopol_param_t *iop_param)
2407 {
2408 	int error = EINVAL;
2409 
2410 	switch (scope) {
2411 	case IOPOL_SCOPE_PROCESS:
2412 		break;
2413 	default:
2414 		goto out;
2415 	}
2416 
2417 	switch (cmd) {
2418 	case IOPOL_CMD_GET:
2419 		policy = os_atomic_load(&p->p_vfs_iopolicy, relaxed) & P_VFS_IOPOLICY_ALLOW_LOW_SPACE_WRITES ?
2420 		    IOPOL_VFS_ALLOW_LOW_SPACE_WRITES_ON : IOPOL_VFS_ALLOW_LOW_SPACE_WRITES_OFF;
2421 		iop_param->iop_policy = policy;
2422 		goto out_ok;
2423 	case IOPOL_CMD_SET:
2424 		break;
2425 	default:
2426 		break;
2427 	}
2428 
2429 	if (!IOCurrentTaskHasEntitlement(ALLOW_LOW_SPACE_WRITES_ENTITLEMENT)) {
2430 		error = EPERM;
2431 		goto out;
2432 	}
2433 
2434 	switch (policy) {
2435 	case IOPOL_VFS_ALLOW_LOW_SPACE_WRITES_OFF:
2436 		os_atomic_andnot(&p->p_vfs_iopolicy, P_VFS_IOPOLICY_ALLOW_LOW_SPACE_WRITES, relaxed);
2437 		break;
2438 	case IOPOL_VFS_ALLOW_LOW_SPACE_WRITES_ON:
2439 		os_atomic_or(&p->p_vfs_iopolicy, P_VFS_IOPOLICY_ALLOW_LOW_SPACE_WRITES, relaxed);
2440 		break;
2441 	default:
2442 		break;
2443 	}
2444 
2445 out_ok:
2446 	error = 0;
2447 out:
2448 	return error;
2449 }
2450 
2451 static int
iopolicysys_vfs_disallow_rw_for_o_evtonly(struct proc * p,int cmd,int scope,int policy,__unused struct _iopol_param_t * iop_param)2452 iopolicysys_vfs_disallow_rw_for_o_evtonly(struct proc *p, int cmd, int scope,
2453     int policy, __unused struct _iopol_param_t *iop_param)
2454 {
2455 	int error = EINVAL;
2456 
2457 	switch (scope) {
2458 	case IOPOL_SCOPE_PROCESS:
2459 		break;
2460 	default:
2461 		goto out;
2462 	}
2463 
2464 	switch (cmd) {
2465 	case IOPOL_CMD_GET:
2466 		policy = (os_atomic_load(&p->p_vfs_iopolicy, relaxed) &
2467 		    P_VFS_IOPOLICY_DISALLOW_RW_FOR_O_EVTONLY) ?
2468 		    IOPOL_VFS_DISALLOW_RW_FOR_O_EVTONLY_ON :
2469 		    IOPOL_VFS_DISALLOW_RW_FOR_O_EVTONLY_DEFAULT;
2470 		iop_param->iop_policy = policy;
2471 		goto out_ok;
2472 	case IOPOL_CMD_SET:
2473 		break;
2474 	default:
2475 		goto out;
2476 	}
2477 
2478 	/* Once set, we don't allow the process to clear it. */
2479 	switch (policy) {
2480 	case IOPOL_VFS_DISALLOW_RW_FOR_O_EVTONLY_ON:
2481 		os_atomic_or(&p->p_vfs_iopolicy,
2482 		    P_VFS_IOPOLICY_DISALLOW_RW_FOR_O_EVTONLY, relaxed);
2483 		break;
2484 	default:
2485 		goto out;
2486 	}
2487 
2488 out_ok:
2489 	error = 0;
2490 out:
2491 	return error;
2492 }
2493 
2494 static int
iopolicysys_vfs_altlink(struct proc * p,int cmd,int scope,int policy,struct _iopol_param_t * iop_param)2495 iopolicysys_vfs_altlink(struct proc *p, int cmd, int scope, int policy,
2496     struct _iopol_param_t *iop_param)
2497 {
2498 	if (scope != IOPOL_SCOPE_PROCESS) {
2499 		return EINVAL;
2500 	}
2501 
2502 	if (cmd == IOPOL_CMD_GET) {
2503 		policy = (os_atomic_load(&p->p_vfs_iopolicy, relaxed) & P_VFS_IOPOLICY_ALTLINK) ?
2504 		    IOPOL_VFS_ALTLINK_ENABLED : IOPOL_VFS_ALTLINK_DISABLED;
2505 		iop_param->iop_policy = policy;
2506 		return 0;
2507 	}
2508 
2509 	/* Once set, we don't allow the process to clear it. */
2510 	if (policy == IOPOL_VFS_ALTLINK_ENABLED) {
2511 		os_atomic_or(&p->p_vfs_iopolicy, P_VFS_IOPOLICY_ALTLINK, relaxed);
2512 		return 0;
2513 	}
2514 
2515 	return EINVAL;
2516 }
2517 
2518 void
proc_apply_task_networkbg(int pid,thread_t thread)2519 proc_apply_task_networkbg(int pid, thread_t thread)
2520 {
2521 	proc_t p = proc_find(pid);
2522 
2523 	if (p != PROC_NULL) {
2524 		do_background_socket(p, thread);
2525 		proc_rele(p);
2526 	}
2527 }
2528 
2529 void
gather_rusage_info(proc_t p,rusage_info_current * ru,int flavor)2530 gather_rusage_info(proc_t p, rusage_info_current *ru, int flavor)
2531 {
2532 	struct rusage_info_child *ri_child;
2533 
2534 	assert(p->p_stats != NULL);
2535 	memset(ru, 0, sizeof(*ru));
2536 	switch (flavor) {
2537 	case RUSAGE_INFO_V6:
2538 		/* Any P-specific resource counters are captured in fill_task_rusage. */
2539 		OS_FALLTHROUGH;
2540 
2541 	case RUSAGE_INFO_V5:
2542 #if __has_feature(ptrauth_calls)
2543 		if (vm_shared_region_is_reslide(proc_task(p))) {
2544 			ru->ri_flags |= RU_PROC_RUNS_RESLIDE;
2545 		}
2546 #endif /* __has_feature(ptrauth_calls) */
2547 		OS_FALLTHROUGH;
2548 
2549 	case RUSAGE_INFO_V4:
2550 		ru->ri_logical_writes = get_task_logical_writes(proc_task(p), false);
2551 		ru->ri_lifetime_max_phys_footprint = get_task_phys_footprint_lifetime_max(proc_task(p));
2552 #if CONFIG_LEDGER_INTERVAL_MAX
2553 		ru->ri_interval_max_phys_footprint = get_task_phys_footprint_interval_max(proc_task(p), FALSE);
2554 #endif
2555 		OS_FALLTHROUGH;
2556 
2557 	case RUSAGE_INFO_V3:
2558 		fill_task_qos_rusage(proc_task(p), ru);
2559 		fill_task_billed_usage(proc_task(p), ru);
2560 		OS_FALLTHROUGH;
2561 
2562 	case RUSAGE_INFO_V2:
2563 		fill_task_io_rusage(proc_task(p), ru);
2564 		OS_FALLTHROUGH;
2565 
2566 	case RUSAGE_INFO_V1:
2567 		/*
2568 		 * p->p_stats->ri_child statistics are protected under proc lock.
2569 		 */
2570 		proc_lock(p);
2571 
2572 		ri_child = &(p->p_stats->ri_child);
2573 		ru->ri_child_user_time = ri_child->ri_child_user_time;
2574 		ru->ri_child_system_time = ri_child->ri_child_system_time;
2575 		ru->ri_child_pkg_idle_wkups = ri_child->ri_child_pkg_idle_wkups;
2576 		ru->ri_child_interrupt_wkups = ri_child->ri_child_interrupt_wkups;
2577 		ru->ri_child_pageins = ri_child->ri_child_pageins;
2578 		ru->ri_child_elapsed_abstime = ri_child->ri_child_elapsed_abstime;
2579 
2580 		proc_unlock(p);
2581 		OS_FALLTHROUGH;
2582 
2583 	case RUSAGE_INFO_V0:
2584 		proc_getexecutableuuid(p, (unsigned char *)&ru->ri_uuid, sizeof(ru->ri_uuid));
2585 		fill_task_rusage(proc_task(p), ru);
2586 		ru->ri_proc_start_abstime = p->p_stats->ps_start;
2587 	}
2588 }
2589 
2590 int
proc_get_rusage(proc_t p,int flavor,user_addr_t buffer,__unused int is_zombie)2591 proc_get_rusage(proc_t p, int flavor, user_addr_t buffer, __unused int is_zombie)
2592 {
2593 	rusage_info_current ri_current = {};
2594 
2595 	size_t size = 0;
2596 
2597 	switch (flavor) {
2598 	case RUSAGE_INFO_V0:
2599 		size = sizeof(struct rusage_info_v0);
2600 		break;
2601 
2602 	case RUSAGE_INFO_V1:
2603 		size = sizeof(struct rusage_info_v1);
2604 		break;
2605 
2606 	case RUSAGE_INFO_V2:
2607 		size = sizeof(struct rusage_info_v2);
2608 		break;
2609 
2610 	case RUSAGE_INFO_V3:
2611 		size = sizeof(struct rusage_info_v3);
2612 		break;
2613 
2614 	case RUSAGE_INFO_V4:
2615 		size = sizeof(struct rusage_info_v4);
2616 		break;
2617 
2618 	case RUSAGE_INFO_V5:
2619 		size = sizeof(struct rusage_info_v5);
2620 		break;
2621 
2622 	case RUSAGE_INFO_V6:
2623 		size = sizeof(struct rusage_info_v6);
2624 		break;
2625 	default:
2626 		return EINVAL;
2627 	}
2628 
2629 	if (size == 0) {
2630 		return EINVAL;
2631 	}
2632 
2633 	/*
2634 	 * If task is still alive, collect info from the live task itself.
2635 	 * Otherwise, look to the cached info in the zombie proc.
2636 	 */
2637 	if (p->p_ru) {
2638 		return copyout(&p->p_ru->ri, buffer, size);
2639 	} else {
2640 		gather_rusage_info(p, &ri_current, flavor);
2641 		ri_current.ri_proc_exit_abstime = 0;
2642 		return copyout(&ri_current, buffer, size);
2643 	}
2644 }
2645 
2646 static int
mach_to_bsd_rv(int mach_rv)2647 mach_to_bsd_rv(int mach_rv)
2648 {
2649 	int bsd_rv = 0;
2650 
2651 	switch (mach_rv) {
2652 	case KERN_SUCCESS:
2653 		bsd_rv = 0;
2654 		break;
2655 	case KERN_INVALID_ARGUMENT:
2656 		bsd_rv = EINVAL;
2657 		break;
2658 	default:
2659 		panic("unknown error %#x", mach_rv);
2660 	}
2661 
2662 	return bsd_rv;
2663 }
2664 
2665 /*
2666  * Resource limit controls
2667  *
2668  * uap->flavor available flavors:
2669  *
2670  *     RLIMIT_WAKEUPS_MONITOR
2671  *     RLIMIT_CPU_USAGE_MONITOR
2672  *     RLIMIT_THREAD_CPULIMITS
2673  *     RLIMIT_FOOTPRINT_INTERVAL
2674  */
2675 int
proc_rlimit_control(__unused struct proc * p,struct proc_rlimit_control_args * uap,__unused int32_t * retval)2676 proc_rlimit_control(__unused struct proc *p, struct proc_rlimit_control_args *uap, __unused int32_t *retval)
2677 {
2678 	proc_t  targetp;
2679 	int     error = 0;
2680 	struct  proc_rlimit_control_wakeupmon wakeupmon_args;
2681 	uint32_t cpumon_flags;
2682 	uint32_t cpulimits_flags;
2683 	kauth_cred_t my_cred, target_cred;
2684 #if CONFIG_LEDGER_INTERVAL_MAX
2685 	uint32_t footprint_interval_flags;
2686 	uint64_t interval_max_footprint;
2687 #endif /* CONFIG_LEDGER_INTERVAL_MAX */
2688 
2689 	/* -1 implicitly means our own process (perhaps even the current thread for per-thread attributes) */
2690 	if (uap->pid == -1) {
2691 		targetp = proc_self();
2692 	} else {
2693 		targetp = proc_find(uap->pid);
2694 	}
2695 
2696 	/* proc_self() can return NULL for an exiting process */
2697 	if (targetp == PROC_NULL) {
2698 		return ESRCH;
2699 	}
2700 
2701 	my_cred = kauth_cred_get();
2702 	target_cred = kauth_cred_proc_ref(targetp);
2703 
2704 	if (!kauth_cred_issuser(my_cred) && kauth_cred_getruid(my_cred) &&
2705 	    kauth_cred_getuid(my_cred) != kauth_cred_getuid(target_cred) &&
2706 	    kauth_cred_getruid(my_cred) != kauth_cred_getuid(target_cred)) {
2707 		proc_rele(targetp);
2708 		kauth_cred_unref(&target_cred);
2709 		return EACCES;
2710 	}
2711 
2712 	switch (uap->flavor) {
2713 	case RLIMIT_WAKEUPS_MONITOR:
2714 		if ((error = copyin(uap->arg, &wakeupmon_args, sizeof(wakeupmon_args))) != 0) {
2715 			break;
2716 		}
2717 		if ((error = mach_to_bsd_rv(task_wakeups_monitor_ctl(proc_task(targetp), &wakeupmon_args.wm_flags,
2718 		    &wakeupmon_args.wm_rate))) != 0) {
2719 			break;
2720 		}
2721 		error = copyout(&wakeupmon_args, uap->arg, sizeof(wakeupmon_args));
2722 		break;
2723 	case RLIMIT_CPU_USAGE_MONITOR:
2724 		cpumon_flags = (uint32_t)uap->arg; // XXX temporarily stashing flags in argp (12592127)
2725 		error = mach_to_bsd_rv(task_cpu_usage_monitor_ctl(proc_task(targetp), &cpumon_flags));
2726 		break;
2727 	case RLIMIT_THREAD_CPULIMITS:
2728 		cpulimits_flags = (uint32_t)uap->arg; // only need a limited set of bits, pass in void * argument
2729 
2730 		if (uap->pid != -1) {
2731 			error = EINVAL;
2732 			break;
2733 		}
2734 
2735 		uint8_t percent = 0;
2736 		uint32_t ms_refill = 0;
2737 		uint64_t ns_refill;
2738 
2739 		percent = (uint8_t)(cpulimits_flags & 0xffU);                                   /* low 8 bits for percent */
2740 		ms_refill = (cpulimits_flags >> 8) & 0xffffff;          /* next 24 bits represent ms refill value */
2741 		if (percent >= 100) {
2742 			error = EINVAL;
2743 			break;
2744 		}
2745 
2746 		ns_refill = ((uint64_t)ms_refill) * NSEC_PER_MSEC;
2747 
2748 		error = mach_to_bsd_rv(thread_set_cpulimit(THREAD_CPULIMIT_BLOCK, percent, ns_refill));
2749 		break;
2750 
2751 #if CONFIG_LEDGER_INTERVAL_MAX
2752 	case RLIMIT_FOOTPRINT_INTERVAL:
2753 		footprint_interval_flags = (uint32_t)uap->arg; // XXX temporarily stashing flags in argp (12592127)
2754 		/*
2755 		 * There is currently only one option for this flavor.
2756 		 */
2757 		if ((footprint_interval_flags & FOOTPRINT_INTERVAL_RESET) == 0) {
2758 			error = EINVAL;
2759 			break;
2760 		}
2761 		interval_max_footprint = get_task_phys_footprint_interval_max(proc_task(targetp), TRUE);
2762 		break;
2763 #endif /* CONFIG_LEDGER_INTERVAL_MAX */
2764 	default:
2765 		error = EINVAL;
2766 		break;
2767 	}
2768 
2769 	proc_rele(targetp);
2770 	kauth_cred_unref(&target_cred);
2771 
2772 	/*
2773 	 * Return value from this function becomes errno to userland caller.
2774 	 */
2775 	return error;
2776 }
2777 
2778 /*
2779  * Return the current amount of CPU consumed by this thread (in either user or kernel mode)
2780  */
2781 int
thread_selfusage(struct proc * p __unused,struct thread_selfusage_args * uap __unused,uint64_t * retval)2782 thread_selfusage(struct proc *p __unused, struct thread_selfusage_args *uap __unused, uint64_t *retval)
2783 {
2784 	uint64_t runtime;
2785 
2786 	runtime = thread_get_runtime_self();
2787 	*retval = runtime;
2788 
2789 	return 0;
2790 }
2791