xref: /xnu-10002.1.13/bsd/kern/kern_exec.c (revision 1031c584a5e37aff177559b9f69dbd3c8c3fd30a)
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 NeXT Computer, Inc. All Rights Reserved */
29 /*
30  * Mach Operating System
31  * Copyright (c) 1987 Carnegie-Mellon University
32  * All rights reserved.  The CMU software License Agreement specifies
33  * the terms and conditions for use and redistribution.
34  */
35 
36 /*-
37  * Copyright (c) 1982, 1986, 1991, 1993
38  *	The Regents of the University of California.  All rights reserved.
39  * (c) UNIX System Laboratories, Inc.
40  * All or some portions of this file are derived from material licensed
41  * to the University of California by American Telephone and Telegraph
42  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
43  * the permission of UNIX System Laboratories, Inc.
44  *
45  * Redistribution and use in source and binary forms, with or without
46  * modification, are permitted provided that the following conditions
47  * are met:
48  * 1. Redistributions of source code must retain the above copyright
49  *    notice, this list of conditions and the following disclaimer.
50  * 2. Redistributions in binary form must reproduce the above copyright
51  *    notice, this list of conditions and the following disclaimer in the
52  *    documentation and/or other materials provided with the distribution.
53  * 3. All advertising materials mentioning features or use of this software
54  *    must display the following acknowledgement:
55  *	This product includes software developed by the University of
56  *	California, Berkeley and its contributors.
57  * 4. Neither the name of the University nor the names of its contributors
58  *    may be used to endorse or promote products derived from this software
59  *    without specific prior written permission.
60  *
61  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
62  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
63  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
64  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
65  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
66  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
67  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
68  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
69  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
70  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
71  * SUCH DAMAGE.
72  *
73  *	from: @(#)kern_exec.c	8.1 (Berkeley) 6/10/93
74  */
75 /*
76  * NOTICE: This file was modified by SPARTA, Inc. in 2005 to introduce
77  * support for mandatory and extensible security protections.  This notice
78  * is included in support of clause 2.2 (b) of the Apple Public License,
79  * Version 2.0.
80  */
81 #include <machine/reg.h>
82 #include <machine/cpu_capabilities.h>
83 
84 #include <sys/cdefs.h>
85 #include <sys/param.h>
86 #include <sys/systm.h>
87 #include <sys/filedesc.h>
88 #include <sys/kernel.h>
89 #include <sys/proc_internal.h>
90 #include <sys/kauth.h>
91 #include <sys/user.h>
92 #include <sys/socketvar.h>
93 #include <sys/malloc.h>
94 #include <sys/namei.h>
95 #include <sys/mount_internal.h>
96 #include <sys/vnode_internal.h>
97 #include <sys/file_internal.h>
98 #include <sys/stat.h>
99 #include <sys/uio_internal.h>
100 #include <sys/acct.h>
101 #include <sys/exec.h>
102 #include <sys/kdebug.h>
103 #include <sys/signal.h>
104 #include <sys/aio_kern.h>
105 #include <sys/sysproto.h>
106 #include <sys/sysctl.h>
107 #include <sys/persona.h>
108 #include <sys/reason.h>
109 #if SYSV_SHM
110 #include <sys/shm_internal.h>           /* shmexec() */
111 #endif
112 #include <sys/ubc_internal.h>           /* ubc_map() */
113 #include <sys/spawn.h>
114 #include <sys/spawn_internal.h>
115 #include <sys/process_policy.h>
116 #include <sys/codesign.h>
117 #include <sys/random.h>
118 #include <crypto/sha1.h>
119 
120 #include <libkern/libkern.h>
121 #include <libkern/crypto/sha2.h>
122 #include <security/audit/audit.h>
123 
124 #include <ipc/ipc_types.h>
125 
126 #include <mach/mach_param.h>
127 #include <mach/mach_types.h>
128 #include <mach/port.h>
129 #include <mach/task.h>
130 #include <mach/task_access.h>
131 #include <mach/thread_act.h>
132 #include <mach/vm_map.h>
133 #include <mach/mach_vm.h>
134 #include <mach/vm_param.h>
135 #include <mach_debug/mach_debug_types.h>
136 
137 #include <kern/sched_prim.h> /* thread_wakeup() */
138 #include <kern/affinity.h>
139 #include <kern/assert.h>
140 #include <kern/task.h>
141 #include <kern/thread.h>
142 #include <kern/coalition.h>
143 #include <kern/policy_internal.h>
144 #include <kern/kalloc.h>
145 #include <kern/zalloc.h> /* zone_userspace_reboot_checks() */
146 
147 #include <os/log.h>
148 
149 #if CONFIG_MACF
150 #include <security/mac_framework.h>
151 #include <security/mac_mach_internal.h>
152 #endif
153 
154 #if CONFIG_AUDIT
155 #include <bsm/audit_kevents.h>
156 #endif
157 
158 #if CONFIG_ARCADE
159 #include <kern/arcade.h>
160 #endif
161 
162 #include <vm/vm_map.h>
163 #include <vm/vm_kern.h>
164 #include <vm/vm_protos.h>
165 #include <vm/vm_kern.h>
166 #include <vm/vm_fault.h>
167 #include <vm/vm_pageout.h>
168 #include <vm/pmap.h>
169 #include <vm/vm_reclaim_internal.h>
170 
171 #include <kdp/kdp_dyld.h>
172 
173 #include <machine/machine_routines.h>
174 #include <machine/pal_routines.h>
175 
176 #include <pexpert/pexpert.h>
177 
178 #if CONFIG_MEMORYSTATUS
179 #include <sys/kern_memorystatus.h>
180 #endif
181 
182 #include <IOKit/IOBSD.h>
183 
184 #include "kern_exec_internal.h"
185 
186 extern boolean_t vm_darkwake_mode;
187 
188 /* enable crash reports on various exec failures */
189 static TUNABLE(bool, bootarg_execfailurereports, "execfailurecrashes", false);
190 
191 #if XNU_TARGET_OS_OSX
192 #if __has_feature(ptrauth_calls)
193 static TUNABLE(bool, bootarg_arm64e_preview_abi, "-arm64e_preview_abi", false);
194 #endif /* __has_feature(ptrauth_calls) */
195 
196 #if DEBUG || DEVELOPMENT
197 static TUNABLE(bool, unentitled_ios_sim_launch, "unentitled_ios_sim_launch", false);
198 #endif /* DEBUG || DEVELOPMENT */
199 #endif /* XNU_TARGET_OS_OSX */
200 
201 #if CONFIG_DTRACE
202 /* Do not include dtrace.h, it redefines kmem_[alloc/free] */
203 extern void dtrace_proc_exec(proc_t);
204 extern void (*dtrace_proc_waitfor_exec_ptr)(proc_t);
205 
206 /*
207  * Since dtrace_proc_waitfor_exec_ptr can be added/removed in dtrace_subr.c,
208  * we will store its value before actually calling it.
209  */
210 static void (*dtrace_proc_waitfor_hook)(proc_t) = NULL;
211 
212 #include <sys/dtrace_ptss.h>
213 #endif
214 
215 #if __has_feature(ptrauth_calls)
216 static TUNABLE_DEV_WRITEABLE(int, vm_shared_region_per_team_id,
217     "vm_shared_region_per_team_id", 1);
218 static TUNABLE_DEV_WRITEABLE(int, vm_shared_region_by_entitlement,
219     "vm_shared_region_by_entitlement", 1);
220 
221 /* Upon userland request, reslide the shared cache. */
222 static TUNABLE_DEV_WRITEABLE(int, vm_shared_region_reslide_aslr,
223     "vm_shared_region_reslide_aslr",
224 #if CONFIG_RESLIDE_SHARED_CACHE
225     1
226 #else
227     0
228 #endif /* CONFIG_RESLIDE_SHARED_CACHE */
229     );
230 
231 /*
232  * Flag to control what processes should get shared cache randomize resliding
233  * after a fault in the shared cache region:
234  *
235  * 0 - all processes get a new randomized slide
236  * 1 - only platform processes get a new randomized slide
237  */
238 TUNABLE_DEV_WRITEABLE(int, vm_shared_region_reslide_restrict,
239     "vm_shared_region_reslide_restrict", 1);
240 
241 #if DEVELOPMENT || DEBUG
242 SYSCTL_INT(_vm, OID_AUTO, vm_shared_region_per_team_id,
243     CTLFLAG_RW, &vm_shared_region_per_team_id, 0, "");
244 SYSCTL_INT(_vm, OID_AUTO, vm_shared_region_by_entitlement,
245     CTLFLAG_RW, &vm_shared_region_by_entitlement, 0, "");
246 SYSCTL_INT(_vm, OID_AUTO, vm_shared_region_reslide_restrict,
247     CTLFLAG_RW, &vm_shared_region_reslide_restrict, 0, "");
248 SYSCTL_INT(_vm, OID_AUTO, vm_shared_region_reslide_aslr,
249     CTLFLAG_RW, &vm_shared_region_reslide_aslr, 0, "");
250 #endif
251 #endif /* __has_feature(ptrauth_calls) */
252 
253 #if DEVELOPMENT || DEBUG
254 static TUNABLE(bool, enable_dext_coredumps_on_panic, "dext_panic_coredump", true);
255 #else
256 static TUNABLE(bool, enable_dext_coredumps_on_panic, "dext_panic_coredump", false);
257 #endif
258 extern kern_return_t kern_register_userspace_coredump(task_t task, const char * name);
259 #define USERSPACE_COREDUMP_PANIC_ENTITLEMENT "com.apple.private.enable-coredump-on-panic"
260 #define USERSPACE_COREDUMP_PANIC_SEED_ENTITLEMENT \
261 	"com.apple.private.enable-coredump-on-panic-seed-privacy-approved"
262 
263 extern void proc_apply_task_networkbg_internal(proc_t, thread_t);
264 extern void task_set_did_exec_flag(task_t task);
265 extern void task_clear_exec_copy_flag(task_t task);
266 proc_t proc_exec_switch_task(proc_t old_proc, proc_t new_proc, task_t old_task,
267     task_t new_task, thread_t new_thread, void **inherit);
268 boolean_t task_is_active(task_t);
269 boolean_t thread_is_active(thread_t thread);
270 void thread_copy_resource_info(thread_t dst_thread, thread_t src_thread);
271 void *ipc_importance_exec_switch_task(task_t old_task, task_t new_task);
272 extern void ipc_importance_release(void *elem);
273 extern boolean_t task_has_watchports(task_t task);
274 extern void task_set_no_smt(task_t task);
275 #if defined(HAS_APPLE_PAC)
276 char *task_get_vm_shared_region_id_and_jop_pid(task_t task, uint64_t *jop_pid);
277 #endif
278 task_t convert_port_to_task(ipc_port_t port);
279 
280 
281 /*
282  * Mach things for which prototypes are unavailable from Mach headers
283  */
284 #define IPC_OBJECT_COPYIN_FLAGS_ALLOW_IMMOVABLE_SEND 0x1
285 void            ipc_task_enable(
286 	task_t          task);
287 void            ipc_task_reset(
288 	task_t          task);
289 void            ipc_thread_reset(
290 	thread_t        thread);
291 kern_return_t ipc_object_copyin(
292 	ipc_space_t             space,
293 	mach_port_name_t        name,
294 	mach_msg_type_name_t    msgt_name,
295 	ipc_object_t            *objectp,
296 	mach_port_context_t     context,
297 	mach_msg_guard_flags_t  *guard_flags,
298 	uint32_t                kmsg_flags);
299 void ipc_port_release_send(ipc_port_t);
300 
301 #if DEVELOPMENT || DEBUG
302 void task_importance_update_owner_info(task_t);
303 #endif
304 
305 extern struct savearea *get_user_regs(thread_t);
306 
307 __attribute__((noinline)) int __EXEC_WAITING_ON_TASKGATED_CODE_SIGNATURE_UPCALL__(mach_port_t task_access_port, int32_t new_pid);
308 
309 #include <kern/thread.h>
310 #include <kern/task.h>
311 #include <kern/ast.h>
312 #include <kern/mach_loader.h>
313 #include <kern/mach_fat.h>
314 #include <mach-o/fat.h>
315 #include <mach-o/loader.h>
316 #include <machine/vmparam.h>
317 #include <sys/imgact.h>
318 
319 #include <sys/sdt.h>
320 
321 
322 /*
323  * EAI_ITERLIMIT	The maximum number of times to iterate an image
324  *			activator in exec_activate_image() before treating
325  *			it as malformed/corrupt.
326  */
327 #define EAI_ITERLIMIT           3
328 
329 /*
330  * For #! interpreter parsing
331  */
332 #define IS_WHITESPACE(ch) ((ch == ' ') || (ch == '\t'))
333 #define IS_EOL(ch) ((ch == '#') || (ch == '\n'))
334 
335 extern vm_map_t bsd_pageable_map;
336 extern const struct fileops vnops;
337 extern int nextpidversion;
338 
339 
340 #define USER_ADDR_ALIGN(addr, val) \
341 	( ( (user_addr_t)(addr) + (val) - 1) \
342 	        & ~((val) - 1) )
343 
344 /*
345  * For subsystem root support
346  */
347 #define SPAWN_SUBSYSTEM_ROOT_ENTITLEMENT "com.apple.private.spawn-subsystem-root"
348 
349 /*
350  * Allow setting p_crash_behavior to trigger panic on crash
351  */
352 #define SPAWN_SET_PANIC_CRASH_BEHAVIOR "com.apple.private.spawn-panic-crash-behavior"
353 
354 /* Platform Code Exec Logging */
355 static int platform_exec_logging = 0;
356 
357 SYSCTL_DECL(_security_mac);
358 
359 SYSCTL_INT(_security_mac, OID_AUTO, platform_exec_logging, CTLFLAG_RW, &platform_exec_logging, 0,
360     "log cdhashes for all platform binary executions");
361 
362 static os_log_t peLog = OS_LOG_DEFAULT;
363 
364 struct exec_port_actions {
365 	uint32_t portwatch_count;
366 	uint32_t registered_count;
367 	ipc_port_t *portwatch_array;
368 	ipc_port_t *registered_array;
369 };
370 
371 struct image_params;    /* Forward */
372 static int exec_activate_image(struct image_params *imgp);
373 static int exec_copyout_strings(struct image_params *imgp, user_addr_t *stackp);
374 static int load_return_to_errno(load_return_t lrtn);
375 static int execargs_alloc(struct image_params *imgp);
376 static int execargs_free(struct image_params *imgp);
377 static int exec_check_permissions(struct image_params *imgp);
378 static int exec_extract_strings(struct image_params *imgp);
379 static int exec_add_apple_strings(struct image_params *imgp, const load_result_t *load_result);
380 static int exec_handle_sugid(struct image_params *imgp);
381 static int sugid_scripts = 0;
382 SYSCTL_INT(_kern, OID_AUTO, sugid_scripts, CTLFLAG_RW | CTLFLAG_LOCKED, &sugid_scripts, 0, "");
383 static kern_return_t create_unix_stack(vm_map_t map, load_result_t* load_result, proc_t p);
384 static int copyoutptr(user_addr_t ua, user_addr_t ptr, int ptr_size);
385 static void exec_resettextvp(proc_t, struct image_params *);
386 static int process_signature(proc_t, struct image_params *);
387 static void exec_prefault_data(proc_t, struct image_params *, load_result_t *);
388 static errno_t exec_handle_port_actions(struct image_params *imgp,
389     struct exec_port_actions *port_actions);
390 static errno_t exec_handle_spawnattr_policy(proc_t p, thread_t thread, int psa_apptype, uint64_t psa_qos_clamp,
391     task_role_t psa_darwin_role, struct exec_port_actions *port_actions);
392 static void exec_port_actions_destroy(struct exec_port_actions *port_actions);
393 
394 /*
395  * exec_add_user_string
396  *
397  * Add the requested string to the string space area.
398  *
399  * Parameters;	struct image_params *		image parameter block
400  *		user_addr_t			string to add to strings area
401  *		int				segment from which string comes
402  *		boolean_t			TRUE if string contributes to NCARGS
403  *
404  * Returns:	0			Success
405  *		!0			Failure errno from copyinstr()
406  *
407  * Implicit returns:
408  *		(imgp->ip_strendp)	updated location of next add, if any
409  *		(imgp->ip_strspace)	updated byte count of space remaining
410  *		(imgp->ip_argspace) updated byte count of space in NCARGS
411  */
412 __attribute__((noinline))
413 static int
exec_add_user_string(struct image_params * imgp,user_addr_t str,int seg,boolean_t is_ncargs)414 exec_add_user_string(struct image_params *imgp, user_addr_t str, int seg, boolean_t is_ncargs)
415 {
416 	int error = 0;
417 
418 	do {
419 		size_t len = 0;
420 		int space;
421 
422 		if (is_ncargs) {
423 			space = imgp->ip_argspace; /* by definition smaller than ip_strspace */
424 		} else {
425 			space = imgp->ip_strspace;
426 		}
427 
428 		if (space <= 0) {
429 			error = E2BIG;
430 			break;
431 		}
432 
433 		if (!UIO_SEG_IS_USER_SPACE(seg)) {
434 			char *kstr = CAST_DOWN(char *, str);     /* SAFE */
435 			error = copystr(kstr, imgp->ip_strendp, space, &len);
436 		} else {
437 			error = copyinstr(str, imgp->ip_strendp, space, &len);
438 		}
439 
440 		imgp->ip_strendp += len;
441 		imgp->ip_strspace -= len;
442 		if (is_ncargs) {
443 			imgp->ip_argspace -= len;
444 		}
445 	} while (error == ENAMETOOLONG);
446 
447 	return error;
448 }
449 
450 /*
451  * dyld is now passed the executable path as a getenv-like variable
452  * in the same fashion as the stack_guard and malloc_entropy keys.
453  */
454 #define EXECUTABLE_KEY "executable_path="
455 
456 /*
457  * exec_save_path
458  *
459  * To support new app package launching for Mac OS X, the dyld needs the
460  * first argument to execve() stored on the user stack.
461  *
462  * Save the executable path name at the bottom of the strings area and set
463  * the argument vector pointer to the location following that to indicate
464  * the start of the argument and environment tuples, setting the remaining
465  * string space count to the size of the string area minus the path length.
466  *
467  * Parameters;	struct image_params *		image parameter block
468  *		char *				path used to invoke program
469  *		int				segment from which path comes
470  *
471  * Returns:	int			0	Success
472  *		EFAULT				Bad address
473  *	copy[in]str:EFAULT			Bad address
474  *	copy[in]str:ENAMETOOLONG		Filename too long
475  *
476  * Implicit returns:
477  *		(imgp->ip_strings)		saved path
478  *		(imgp->ip_strspace)		space remaining in ip_strings
479  *		(imgp->ip_strendp)		start of remaining copy area
480  *		(imgp->ip_argspace)		space remaining of NCARGS
481  *		(imgp->ip_applec)		Initial applev[0]
482  *
483  * Note:	We have to do this before the initial namei() since in the
484  *		path contains symbolic links, namei() will overwrite the
485  *		original path buffer contents.  If the last symbolic link
486  *		resolved was a relative pathname, we would lose the original
487  *		"path", which could be an absolute pathname. This might be
488  *		unacceptable for dyld.
489  */
490 static int
exec_save_path(struct image_params * imgp,user_addr_t path,int seg,const char ** excpath)491 exec_save_path(struct image_params *imgp, user_addr_t path, int seg, const char **excpath)
492 {
493 	int error;
494 	size_t len;
495 	char *kpath;
496 
497 	// imgp->ip_strings can come out of a cache, so we need to obliterate the
498 	// old path.
499 	memset(imgp->ip_strings, '\0', strlen(EXECUTABLE_KEY) + MAXPATHLEN);
500 
501 	len = MIN(MAXPATHLEN, imgp->ip_strspace);
502 
503 	switch (seg) {
504 	case UIO_USERSPACE32:
505 	case UIO_USERSPACE64:   /* Same for copyin()... */
506 		error = copyinstr(path, imgp->ip_strings + strlen(EXECUTABLE_KEY), len, &len);
507 		break;
508 	case UIO_SYSSPACE:
509 		kpath = CAST_DOWN(char *, path); /* SAFE */
510 		error = copystr(kpath, imgp->ip_strings + strlen(EXECUTABLE_KEY), len, &len);
511 		break;
512 	default:
513 		error = EFAULT;
514 		break;
515 	}
516 
517 	if (!error) {
518 		bcopy(EXECUTABLE_KEY, imgp->ip_strings, strlen(EXECUTABLE_KEY));
519 		len += strlen(EXECUTABLE_KEY);
520 
521 		imgp->ip_strendp += len;
522 		imgp->ip_strspace -= len;
523 
524 		if (excpath) {
525 			*excpath = imgp->ip_strings + strlen(EXECUTABLE_KEY);
526 		}
527 	}
528 
529 	return error;
530 }
531 
532 /*
533  * exec_reset_save_path
534  *
535  * If we detect a shell script, we need to reset the string area
536  * state so that the interpreter can be saved onto the stack.
537  *
538  * Parameters;	struct image_params *		image parameter block
539  *
540  * Returns:	int			0	Success
541  *
542  * Implicit returns:
543  *		(imgp->ip_strings)		saved path
544  *		(imgp->ip_strspace)		space remaining in ip_strings
545  *		(imgp->ip_strendp)		start of remaining copy area
546  *		(imgp->ip_argspace)		space remaining of NCARGS
547  *
548  */
549 static int
exec_reset_save_path(struct image_params * imgp)550 exec_reset_save_path(struct image_params *imgp)
551 {
552 	imgp->ip_strendp = imgp->ip_strings;
553 	imgp->ip_argspace = NCARGS;
554 	imgp->ip_strspace = (NCARGS + PAGE_SIZE);
555 
556 	return 0;
557 }
558 
559 /*
560  * exec_shell_imgact
561  *
562  * Image activator for interpreter scripts.  If the image begins with
563  * the characters "#!", then it is an interpreter script.  Verify the
564  * length of the script line indicating the interpreter is not in
565  * excess of the maximum allowed size.  If this is the case, then
566  * break out the arguments, if any, which are separated by white
567  * space, and copy them into the argument save area as if they were
568  * provided on the command line before all other arguments.  The line
569  * ends when we encounter a comment character ('#') or newline.
570  *
571  * Parameters;	struct image_params *	image parameter block
572  *
573  * Returns:	-1			not an interpreter (keep looking)
574  *		-3			Success: interpreter: relookup
575  *		>0			Failure: interpreter: error number
576  *
577  * A return value other than -1 indicates subsequent image activators should
578  * not be given the opportunity to attempt to activate the image.
579  */
580 static int
exec_shell_imgact(struct image_params * imgp)581 exec_shell_imgact(struct image_params *imgp)
582 {
583 	char *vdata = imgp->ip_vdata;
584 	char *ihp;
585 	char *line_startp, *line_endp;
586 	char *interp;
587 
588 	/*
589 	 * Make sure it's a shell script.  If we've already redirected
590 	 * from an interpreted file once, don't do it again.
591 	 */
592 	if (vdata[0] != '#' ||
593 	    vdata[1] != '!' ||
594 	    (imgp->ip_flags & IMGPF_INTERPRET) != 0) {
595 		return -1;
596 	}
597 
598 	if (imgp->ip_origcputype != 0) {
599 		/* Fat header previously matched, don't allow shell script inside */
600 		return -1;
601 	}
602 
603 	imgp->ip_flags |= IMGPF_INTERPRET;
604 	imgp->ip_interp_sugid_fd = -1;
605 	imgp->ip_interp_buffer[0] = '\0';
606 
607 	/* Check to see if SUGID scripts are permitted.  If they aren't then
608 	 * clear the SUGID bits.
609 	 * imgp->ip_vattr is known to be valid.
610 	 */
611 	if (sugid_scripts == 0) {
612 		imgp->ip_origvattr->va_mode &= ~(VSUID | VSGID);
613 	}
614 
615 	/* Try to find the first non-whitespace character */
616 	for (ihp = &vdata[2]; ihp < &vdata[IMG_SHSIZE]; ihp++) {
617 		if (IS_EOL(*ihp)) {
618 			/* Did not find interpreter, "#!\n" */
619 			return ENOEXEC;
620 		} else if (IS_WHITESPACE(*ihp)) {
621 			/* Whitespace, like "#!    /bin/sh\n", keep going. */
622 		} else {
623 			/* Found start of interpreter */
624 			break;
625 		}
626 	}
627 
628 	if (ihp == &vdata[IMG_SHSIZE]) {
629 		/* All whitespace, like "#!           " */
630 		return ENOEXEC;
631 	}
632 
633 	line_startp = ihp;
634 
635 	/* Try to find the end of the interpreter+args string */
636 	for (; ihp < &vdata[IMG_SHSIZE]; ihp++) {
637 		if (IS_EOL(*ihp)) {
638 			/* Got it */
639 			break;
640 		} else {
641 			/* Still part of interpreter or args */
642 		}
643 	}
644 
645 	if (ihp == &vdata[IMG_SHSIZE]) {
646 		/* A long line, like "#! blah blah blah" without end */
647 		return ENOEXEC;
648 	}
649 
650 	/* Backtrack until we find the last non-whitespace */
651 	while (IS_EOL(*ihp) || IS_WHITESPACE(*ihp)) {
652 		ihp--;
653 	}
654 
655 	/* The character after the last non-whitespace is our logical end of line */
656 	line_endp = ihp + 1;
657 
658 	/*
659 	 * Now we have pointers to the usable part of:
660 	 *
661 	 * "#!  /usr/bin/int first    second   third    \n"
662 	 *      ^ line_startp                       ^ line_endp
663 	 */
664 
665 	/* copy the interpreter name */
666 	interp = imgp->ip_interp_buffer;
667 	for (ihp = line_startp; (ihp < line_endp) && !IS_WHITESPACE(*ihp); ihp++) {
668 		*interp++ = *ihp;
669 	}
670 	*interp = '\0';
671 
672 	exec_reset_save_path(imgp);
673 	exec_save_path(imgp, CAST_USER_ADDR_T(imgp->ip_interp_buffer),
674 	    UIO_SYSSPACE, NULL);
675 
676 	/* Copy the entire interpreter + args for later processing into argv[] */
677 	interp = imgp->ip_interp_buffer;
678 	for (ihp = line_startp; (ihp < line_endp); ihp++) {
679 		*interp++ = *ihp;
680 	}
681 	*interp = '\0';
682 
683 #if CONFIG_SETUID
684 	/*
685 	 * If we have an SUID or SGID script, create a file descriptor
686 	 * from the vnode and pass /dev/fd/%d instead of the actual
687 	 * path name so that the script does not get opened twice
688 	 */
689 	if (imgp->ip_origvattr->va_mode & (VSUID | VSGID)) {
690 		proc_t p;
691 		struct fileproc *fp;
692 		int fd;
693 		int error;
694 
695 		p = vfs_context_proc(imgp->ip_vfs_context);
696 		error = falloc(p, &fp, &fd, imgp->ip_vfs_context);
697 		if (error) {
698 			return error;
699 		}
700 
701 		fp->fp_glob->fg_flag = FREAD;
702 		fp->fp_glob->fg_ops = &vnops;
703 		fp_set_data(fp, imgp->ip_vp);
704 
705 		proc_fdlock(p);
706 		procfdtbl_releasefd(p, fd, NULL);
707 		fp_drop(p, fd, fp, 1);
708 		proc_fdunlock(p);
709 		vnode_ref(imgp->ip_vp);
710 
711 		imgp->ip_interp_sugid_fd = fd;
712 	}
713 #endif /* CONFIG_SETUID */
714 
715 	return -3;
716 }
717 
718 
719 
720 /*
721  * exec_fat_imgact
722  *
723  * Image activator for fat 1.0 binaries.  If the binary is fat, then we
724  * need to select an image from it internally, and make that the image
725  * we are going to attempt to execute.  At present, this consists of
726  * reloading the first page for the image with a first page from the
727  * offset location indicated by the fat header.
728  *
729  * Parameters;	struct image_params *	image parameter block
730  *
731  * Returns:	-1			not a fat binary (keep looking)
732  *		-2			Success: encapsulated binary: reread
733  *		>0			Failure: error number
734  *
735  * Important:	This image activator is byte order neutral.
736  *
737  * Note:	A return value other than -1 indicates subsequent image
738  *		activators should not be given the opportunity to attempt
739  *		to activate the image.
740  *
741  *              If we find an encapsulated binary, we make no assertions
742  *		about its  validity; instead, we leave that up to a rescan
743  *		for an activator to claim it, and, if it is claimed by one,
744  *		that activator is responsible for determining validity.
745  */
746 static int
exec_fat_imgact(struct image_params * imgp)747 exec_fat_imgact(struct image_params *imgp)
748 {
749 	proc_t p = vfs_context_proc(imgp->ip_vfs_context);
750 	kauth_cred_t cred = kauth_cred_proc_ref(p);
751 	struct fat_header *fat_header = (struct fat_header *)imgp->ip_vdata;
752 	struct _posix_spawnattr *psa = NULL;
753 	struct fat_arch fat_arch;
754 	int resid, error;
755 	load_return_t lret;
756 
757 	if (imgp->ip_origcputype != 0) {
758 		/* Fat header previously matched, don't allow another fat file inside */
759 		error = -1; /* not claimed */
760 		goto bad;
761 	}
762 
763 	/* Make sure it's a fat binary */
764 	if (OSSwapBigToHostInt32(fat_header->magic) != FAT_MAGIC) {
765 		error = -1; /* not claimed */
766 		goto bad;
767 	}
768 
769 	/* imgp->ip_vdata has PAGE_SIZE, zerofilled if the file is smaller */
770 	lret = fatfile_validate_fatarches((vm_offset_t)fat_header, PAGE_SIZE,
771 	    (off_t)imgp->ip_vattr->va_data_size);
772 	if (lret != LOAD_SUCCESS) {
773 		error = load_return_to_errno(lret);
774 		goto bad;
775 	}
776 
777 	/* If posix_spawn binprefs exist, respect those prefs. */
778 	psa = (struct _posix_spawnattr *) imgp->ip_px_sa;
779 	if (psa != NULL && psa->psa_binprefs[0] != 0) {
780 		uint32_t pr = 0;
781 
782 		/* Check each preference listed against all arches in header */
783 		for (pr = 0; pr < NBINPREFS; pr++) {
784 			cpu_type_t pref = psa->psa_binprefs[pr];
785 			cpu_type_t subpref = psa->psa_subcpuprefs[pr];
786 
787 			if (pref == 0) {
788 				/* No suitable arch in the pref list */
789 				error = EBADARCH;
790 				goto bad;
791 			}
792 
793 			if (pref == CPU_TYPE_ANY) {
794 				/* Fall through to regular grading */
795 				goto regular_grading;
796 			}
797 
798 			lret = fatfile_getbestarch_for_cputype(pref,
799 			    subpref,
800 			    (vm_offset_t)fat_header,
801 			    PAGE_SIZE,
802 			    imgp,
803 			    &fat_arch);
804 			if (lret == LOAD_SUCCESS) {
805 				goto use_arch;
806 			}
807 		}
808 
809 		/* Requested binary preference was not honored */
810 		error = EBADEXEC;
811 		goto bad;
812 	}
813 
814 regular_grading:
815 	/* Look up our preferred architecture in the fat file. */
816 	lret = fatfile_getbestarch((vm_offset_t)fat_header,
817 	    PAGE_SIZE,
818 	    imgp,
819 	    &fat_arch,
820 	    (p->p_flag & P_AFFINITY) != 0);
821 	if (lret != LOAD_SUCCESS) {
822 		error = load_return_to_errno(lret);
823 		goto bad;
824 	}
825 
826 use_arch:
827 	/* Read the Mach-O header out of fat_arch */
828 	error = vn_rdwr(UIO_READ, imgp->ip_vp, imgp->ip_vdata,
829 	    PAGE_SIZE, fat_arch.offset,
830 	    UIO_SYSSPACE, (IO_UNIT | IO_NODELOCKED),
831 	    cred, &resid, p);
832 	if (error) {
833 		goto bad;
834 	}
835 
836 	if (resid) {
837 		memset(imgp->ip_vdata + (PAGE_SIZE - resid), 0x0, resid);
838 	}
839 
840 	/* Success.  Indicate we have identified an encapsulated binary */
841 	error = -2;
842 	imgp->ip_arch_offset = (user_size_t)fat_arch.offset;
843 	imgp->ip_arch_size = (user_size_t)fat_arch.size;
844 	imgp->ip_origcputype = fat_arch.cputype;
845 	imgp->ip_origcpusubtype = fat_arch.cpusubtype;
846 
847 bad:
848 	kauth_cred_unref(&cred);
849 	return error;
850 }
851 
852 static int
activate_exec_state(task_t task,proc_t p,thread_t thread,load_result_t * result)853 activate_exec_state(task_t task, proc_t p, thread_t thread, load_result_t *result)
854 {
855 	int ret;
856 
857 	(void)task_set_dyld_info(task, MACH_VM_MIN_ADDRESS, 0);
858 	task_set_64bit(task, result->is_64bit_addr, result->is_64bit_data);
859 	if (result->is_64bit_addr) {
860 		OSBitOrAtomic(P_LP64, &p->p_flag);
861 		get_bsdthread_info(thread)->uu_flag |= UT_LP64;
862 	} else {
863 		OSBitAndAtomic(~((uint32_t)P_LP64), &p->p_flag);
864 		get_bsdthread_info(thread)->uu_flag &= ~UT_LP64;
865 	}
866 	task_set_mach_header_address(task, result->mach_header);
867 
868 	ret = thread_state_initialize(thread);
869 	if (ret != KERN_SUCCESS) {
870 		return ret;
871 	}
872 
873 	if (result->threadstate) {
874 		uint32_t *ts = result->threadstate;
875 		uint32_t total_size = (uint32_t)result->threadstate_sz;
876 
877 		while (total_size > 0) {
878 			uint32_t flavor = *ts++;
879 			uint32_t size = *ts++;
880 
881 			ret = thread_setstatus(thread, flavor, (thread_state_t)ts, size);
882 			if (ret) {
883 				return ret;
884 			}
885 			ts += size;
886 			total_size -= (size + 2) * sizeof(uint32_t);
887 		}
888 	}
889 
890 	thread_setentrypoint(thread, result->entry_point);
891 
892 	return KERN_SUCCESS;
893 }
894 
895 #if (DEVELOPMENT || DEBUG)
896 extern char panic_on_proc_crash[];
897 extern int use_panic_on_proc_crash;
898 
899 extern char panic_on_proc_exit[];
900 extern int use_panic_on_proc_exit;
901 
902 extern char panic_on_proc_spawn_fail[];
903 extern int use_panic_on_proc_spawn_fail;
904 #endif
905 
906 void
set_proc_name(struct image_params * imgp,proc_t p)907 set_proc_name(struct image_params *imgp, proc_t p)
908 {
909 	int p_name_len = sizeof(p->p_name) - 1;
910 
911 	if (imgp->ip_ndp->ni_cnd.cn_namelen > p_name_len) {
912 		imgp->ip_ndp->ni_cnd.cn_namelen = p_name_len;
913 	}
914 
915 	bcopy((caddr_t)imgp->ip_ndp->ni_cnd.cn_nameptr, (caddr_t)p->p_name,
916 	    (unsigned)imgp->ip_ndp->ni_cnd.cn_namelen);
917 	p->p_name[imgp->ip_ndp->ni_cnd.cn_namelen] = '\0';
918 
919 	if (imgp->ip_ndp->ni_cnd.cn_namelen > MAXCOMLEN) {
920 		imgp->ip_ndp->ni_cnd.cn_namelen = MAXCOMLEN;
921 	}
922 
923 	bcopy((caddr_t)imgp->ip_ndp->ni_cnd.cn_nameptr, (caddr_t)p->p_comm,
924 	    (unsigned)imgp->ip_ndp->ni_cnd.cn_namelen);
925 	p->p_comm[imgp->ip_ndp->ni_cnd.cn_namelen] = '\0';
926 
927 #if DEVELOPMENT || DEBUG
928 	/*
929 	 * This happens during image activation, so the crash behavior flags from
930 	 * posix_spawn will have already been set. So we don't have to worry about
931 	 * this being overridden.
932 	 */
933 	if (use_panic_on_proc_crash && strcmp(p->p_comm, panic_on_proc_crash) == 0) {
934 		printf("will panic on proc crash: %s\n", p->p_comm);
935 		p->p_crash_behavior |= POSIX_SPAWN_PANIC_ON_CRASH;
936 	}
937 
938 	if (use_panic_on_proc_exit && strcmp(p->p_comm, panic_on_proc_exit) == 0) {
939 		printf("will panic on proc exit: %s\n", p->p_comm);
940 		p->p_crash_behavior |= POSIX_SPAWN_PANIC_ON_EXIT;
941 	}
942 
943 	if (use_panic_on_proc_spawn_fail && strcmp(p->p_comm, panic_on_proc_spawn_fail) == 0) {
944 		printf("will panic on proc spawn fail: %s\n", p->p_comm);
945 		p->p_crash_behavior |= POSIX_SPAWN_PANIC_ON_SPAWN_FAIL;
946 	}
947 #endif
948 }
949 
950 #if __has_feature(ptrauth_calls)
951 /**
952  * Returns a team ID string that may be used to assign a shared region.
953  *
954  * Platform binaries do not have team IDs and will return NULL.  Non-platform
955  * binaries without a team ID will be assigned an artificial team ID of ""
956  * (empty string) so that they will not be assigned to the default shared
957  * region.
958  *
959  * @param imgp image parameter block
960  * @return NULL if this is a platform binary, or an appropriate team ID string
961  *         otherwise
962  */
963 static inline const char *
get_teamid_for_shared_region(struct image_params * imgp)964 get_teamid_for_shared_region(struct image_params *imgp)
965 {
966 	assert(imgp->ip_vp != NULL);
967 
968 	const char *ret = csvnode_get_teamid(imgp->ip_vp, imgp->ip_arch_offset);
969 	if (ret) {
970 		return ret;
971 	}
972 
973 	struct cs_blob *blob = csvnode_get_blob(imgp->ip_vp, imgp->ip_arch_offset);
974 	if (csblob_get_platform_binary(blob)) {
975 		return NULL;
976 	} else {
977 		static const char *NO_TEAM_ID = "";
978 		return NO_TEAM_ID;
979 	}
980 }
981 
982 /**
983  * Determines whether ptrauth should be enabled for the provided arm64 CPU subtype.
984  *
985  * @param cpusubtype Mach-O style CPU subtype
986  * @return whether the CPU subtype matches arm64e with the current ptrauth ABI
987  */
988 static inline bool
arm64_cpusubtype_uses_ptrauth(cpu_subtype_t cpusubtype)989 arm64_cpusubtype_uses_ptrauth(cpu_subtype_t cpusubtype)
990 {
991 	return (cpusubtype & ~CPU_SUBTYPE_MASK) == CPU_SUBTYPE_ARM64E &&
992 	       CPU_SUBTYPE_ARM64_PTR_AUTH_VERSION(cpusubtype) == CPU_SUBTYPE_ARM64_PTR_AUTH_CURRENT_VERSION;
993 }
994 
995 #endif /* __has_feature(ptrauth_calls) */
996 
997 /**
998  * Returns whether a type/subtype slice matches the requested
999  * type/subtype.
1000  *
1001  * @param mask Bits to mask from the requested/tested cpu type
1002  * @param req_cpu Requested cpu type
1003  * @param req_subcpu Requested cpu subtype
1004  * @param test_cpu Tested slice cpu type
1005  * @param test_subcpu Tested slice cpu subtype
1006  */
1007 boolean_t
binary_match(cpu_type_t mask,cpu_type_t req_cpu,cpu_subtype_t req_subcpu,cpu_type_t test_cpu,cpu_subtype_t test_subcpu)1008 binary_match(cpu_type_t mask, cpu_type_t req_cpu,
1009     cpu_subtype_t req_subcpu, cpu_type_t test_cpu,
1010     cpu_subtype_t test_subcpu)
1011 {
1012 	if ((test_cpu & ~mask) != (req_cpu & ~mask)) {
1013 		return FALSE;
1014 	}
1015 
1016 	test_subcpu &= ~CPU_SUBTYPE_MASK;
1017 	req_subcpu  &= ~CPU_SUBTYPE_MASK;
1018 
1019 	if (test_subcpu != req_subcpu && req_subcpu != (CPU_SUBTYPE_ANY & ~CPU_SUBTYPE_MASK)) {
1020 		return FALSE;
1021 	}
1022 
1023 	return TRUE;
1024 }
1025 
1026 
1027 #define MIN_IOS_TPRO_SDK_VERSION        0x00100000
1028 #define MIN_OSX_TPRO_SDK_VERSION        0x000D0000
1029 #define MIN_TVOS_TPRO_SDK_VERSION       0x000D0000
1030 #define MIN_WATCHOS_TPRO_SDK_VERSION    0x00090000
1031 #define MIN_DRIVERKIT_TPRO_SDK_VERSION  0x00600000
1032 
1033 static void
exec_setup_tpro(struct image_params * imgp,load_result_t * load_result)1034 exec_setup_tpro(struct image_params *imgp, load_result_t *load_result)
1035 {
1036 	extern boolean_t xprr_tpro_enabled;
1037 	extern boolean_t enable_user_modifiable_perms;
1038 	uint32_t min_sdk_version = 0;
1039 
1040 	/* x86-64 translated code cannot take advantage of TPRO */
1041 	if (imgp->ip_flags & IMGPF_ROSETTA) {
1042 		return;
1043 	}
1044 
1045 	/* Do not enable on 32-bit VA targets */
1046 	if (!(imgp->ip_flags & IMGPF_IS_64BIT_ADDR)) {
1047 		return;
1048 	}
1049 
1050 	switch (load_result->ip_platform) {
1051 	case PLATFORM_IOS:
1052 	case PLATFORM_IOSSIMULATOR:
1053 	case PLATFORM_MACCATALYST:
1054 		min_sdk_version = MIN_IOS_TPRO_SDK_VERSION;
1055 		break;
1056 	case PLATFORM_MACOS:
1057 		min_sdk_version = MIN_OSX_TPRO_SDK_VERSION;
1058 		break;
1059 	case PLATFORM_TVOS:
1060 	case PLATFORM_TVOSSIMULATOR:
1061 		min_sdk_version = MIN_TVOS_TPRO_SDK_VERSION;
1062 		break;
1063 	case PLATFORM_WATCHOS:
1064 	case PLATFORM_WATCHOSSIMULATOR:
1065 		min_sdk_version = MIN_WATCHOS_TPRO_SDK_VERSION;
1066 		break;
1067 	case PLATFORM_DRIVERKIT:
1068 		min_sdk_version = MIN_DRIVERKIT_TPRO_SDK_VERSION;
1069 		break;
1070 	default:
1071 		/* TPRO is on by default for newer platforms */
1072 		break;
1073 	}
1074 
1075 }
1076 
1077 /*
1078  * If the passed in executable's vnode should use the RSR
1079  * shared region, then this should return TRUE, otherwise, return FALSE.
1080  */
1081 static uint32_t rsr_current_version = 0;
1082 boolean_t (*rsr_check_vnode)(void *vnode) = NULL;
1083 
1084 boolean_t
vnode_is_rsr(vnode_t vp)1085 vnode_is_rsr(vnode_t vp)
1086 {
1087 	if (!(vnode_isreg(vp) && vnode_tag(vp) == VT_APFS)) {
1088 		return FALSE;
1089 	}
1090 
1091 	if (rsr_check_vnode != NULL && rsr_check_vnode((void *)vp)) {
1092 		return TRUE;
1093 	}
1094 	return FALSE;
1095 }
1096 
1097 
1098 uint32_t
rsr_get_version(void)1099 rsr_get_version(void)
1100 {
1101 	return os_atomic_load(&rsr_current_version, relaxed);
1102 }
1103 
1104 void
rsr_bump_version(void)1105 rsr_bump_version(void)
1106 {
1107 	os_atomic_inc(&rsr_current_version, relaxed);
1108 }
1109 
1110 #if XNU_TARGET_OS_OSX
1111 static int
1112 rsr_version_sysctl SYSCTL_HANDLER_ARGS
1113 {
1114 #pragma unused(arg1, arg2, oidp)
1115 	int value = rsr_get_version();
1116 	int error = SYSCTL_OUT(req, &value, sizeof(int));
1117 	if (error) {
1118 		return error;
1119 	}
1120 
1121 	if (!req->newptr) {
1122 		return 0;
1123 	}
1124 
1125 	error = SYSCTL_IN(req, &value, sizeof(int));
1126 	if (error) {
1127 		return error;
1128 	}
1129 	if (value != 0) {
1130 		rsr_bump_version();
1131 	}
1132 	return 0;
1133 }
1134 
1135 
1136 SYSCTL_PROC(_vm, OID_AUTO, shared_region_control,
1137     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED | CTLFLAG_MASKED,
1138     0, 0, rsr_version_sysctl, "I", "");
1139 #endif /* XNU_TARGET_OS_OSX */
1140 
1141 /*
1142  * exec_mach_imgact
1143  *
1144  * Image activator for mach-o 1.0 binaries.
1145  *
1146  * Parameters;	struct image_params *	image parameter block
1147  *
1148  * Returns:	-1			not a fat binary (keep looking)
1149  *		-2			Success: encapsulated binary: reread
1150  *		>0			Failure: error number
1151  *		EBADARCH		Mach-o binary, but with an unrecognized
1152  *					architecture
1153  *		ENOMEM			No memory for child process after -
1154  *					can only happen after vfork()
1155  *
1156  * Important:	This image activator is NOT byte order neutral.
1157  *
1158  * Note:	A return value other than -1 indicates subsequent image
1159  *		activators should not be given the opportunity to attempt
1160  *		to activate the image.
1161  */
1162 static int
exec_mach_imgact(struct image_params * imgp)1163 exec_mach_imgact(struct image_params *imgp)
1164 {
1165 	struct mach_header *mach_header = (struct mach_header *)imgp->ip_vdata;
1166 	proc_t                  p = vfs_context_proc(imgp->ip_vfs_context);
1167 	int                     error = 0;
1168 	task_t                  task;
1169 	task_t                  new_task = NULL; /* protected by vfexec */
1170 	thread_t                thread;
1171 	struct uthread          *uthread;
1172 	vm_map_t old_map = VM_MAP_NULL;
1173 	vm_map_t map = VM_MAP_NULL;
1174 	load_return_t           lret;
1175 	load_result_t           load_result = {};
1176 	struct _posix_spawnattr *psa = NULL;
1177 	int                     spawn = (imgp->ip_flags & IMGPF_SPAWN);
1178 	const int               vfexec = 0;
1179 	int                     exec = (imgp->ip_flags & IMGPF_EXEC);
1180 	os_reason_t             exec_failure_reason = OS_REASON_NULL;
1181 	boolean_t               reslide = FALSE;
1182 	char *                  userspace_coredump_name = NULL;
1183 
1184 	/*
1185 	 * make sure it's a Mach-O 1.0 or Mach-O 2.0 binary; the difference
1186 	 * is a reserved field on the end, so for the most part, we can
1187 	 * treat them as if they were identical. Reverse-endian Mach-O
1188 	 * binaries are recognized but not compatible.
1189 	 */
1190 	if ((mach_header->magic == MH_CIGAM) ||
1191 	    (mach_header->magic == MH_CIGAM_64)) {
1192 		error = EBADARCH;
1193 		goto bad;
1194 	}
1195 
1196 	if ((mach_header->magic != MH_MAGIC) &&
1197 	    (mach_header->magic != MH_MAGIC_64)) {
1198 		error = -1;
1199 		goto bad;
1200 	}
1201 
1202 	if (mach_header->filetype != MH_EXECUTE) {
1203 		error = -1;
1204 		goto bad;
1205 	}
1206 
1207 	if (imgp->ip_origcputype != 0) {
1208 		/* Fat header previously had an idea about this thin file */
1209 		if (imgp->ip_origcputype != mach_header->cputype ||
1210 		    imgp->ip_origcpusubtype != mach_header->cpusubtype) {
1211 			error = EBADARCH;
1212 			goto bad;
1213 		}
1214 	} else {
1215 		imgp->ip_origcputype = mach_header->cputype;
1216 		imgp->ip_origcpusubtype = mach_header->cpusubtype;
1217 	}
1218 
1219 	task = current_task();
1220 	thread = current_thread();
1221 	uthread = get_bsdthread_info(thread);
1222 
1223 	if ((mach_header->cputype & CPU_ARCH_ABI64) == CPU_ARCH_ABI64) {
1224 		imgp->ip_flags |= IMGPF_IS_64BIT_ADDR | IMGPF_IS_64BIT_DATA;
1225 	}
1226 
1227 
1228 	/* If posix_spawn binprefs exist, respect those prefs. */
1229 	psa = (struct _posix_spawnattr *) imgp->ip_px_sa;
1230 	if (psa != NULL && psa->psa_binprefs[0] != 0) {
1231 		int pr = 0;
1232 		for (pr = 0; pr < NBINPREFS; pr++) {
1233 			cpu_type_t pref = psa->psa_binprefs[pr];
1234 			cpu_subtype_t subpref = psa->psa_subcpuprefs[pr];
1235 
1236 			if (pref == 0) {
1237 				/* No suitable arch in the pref list */
1238 				error = EBADARCH;
1239 				goto bad;
1240 			}
1241 
1242 			if (pref == CPU_TYPE_ANY) {
1243 				/* Jump to regular grading */
1244 				goto grade;
1245 			}
1246 
1247 			if (binary_match(CPU_ARCH_MASK, pref, subpref,
1248 			    imgp->ip_origcputype, imgp->ip_origcpusubtype)) {
1249 				goto grade;
1250 			}
1251 		}
1252 		error = EBADARCH;
1253 		goto bad;
1254 	}
1255 grade:
1256 	if (!grade_binary(imgp->ip_origcputype, imgp->ip_origcpusubtype & ~CPU_SUBTYPE_MASK,
1257 	    imgp->ip_origcpusubtype & CPU_SUBTYPE_MASK, TRUE)) {
1258 		error = EBADARCH;
1259 		goto bad;
1260 	}
1261 
1262 	if (validate_potential_simulator_binary(imgp->ip_origcputype, imgp,
1263 	    imgp->ip_arch_offset, imgp->ip_arch_size) != LOAD_SUCCESS) {
1264 #if __x86_64__
1265 		const char *excpath;
1266 		error = exec_save_path(imgp, imgp->ip_user_fname, imgp->ip_seg, &excpath);
1267 		os_log_error(OS_LOG_DEFAULT, "Unsupported 32-bit executable: \"%s\"", (error) ? imgp->ip_vp->v_name : excpath);
1268 #endif
1269 		error = EBADARCH;
1270 		goto bad;
1271 	}
1272 
1273 #if defined(HAS_APPLE_PAC)
1274 	assert(mach_header->cputype == CPU_TYPE_ARM64
1275 	    );
1276 
1277 	if ((mach_header->cputype == CPU_TYPE_ARM64 &&
1278 	    arm64_cpusubtype_uses_ptrauth(mach_header->cpusubtype))
1279 	    ) {
1280 		imgp->ip_flags &= ~IMGPF_NOJOP;
1281 	} else {
1282 		imgp->ip_flags |= IMGPF_NOJOP;
1283 	}
1284 #endif
1285 
1286 	/* Copy in arguments/environment from the old process */
1287 	error = exec_extract_strings(imgp);
1288 	if (error) {
1289 		goto bad;
1290 	}
1291 
1292 	AUDIT_ARG(argv, imgp->ip_startargv, imgp->ip_argc,
1293 	    imgp->ip_endargv - imgp->ip_startargv);
1294 	AUDIT_ARG(envv, imgp->ip_endargv, imgp->ip_envc,
1295 	    imgp->ip_endenvv - imgp->ip_endargv);
1296 
1297 
1298 
1299 	/* reset local idea of thread, uthread, task */
1300 	thread = imgp->ip_new_thread;
1301 	uthread = get_bsdthread_info(thread);
1302 	task = new_task = get_threadtask(thread);
1303 
1304 	/*
1305 	 *	Load the Mach-O file.
1306 	 *
1307 	 * NOTE: An error after this point  indicates we have potentially
1308 	 * destroyed or overwritten some process state while attempting an
1309 	 * execve() following a vfork(), which is an unrecoverable condition.
1310 	 * We send the new process an immediate SIGKILL to avoid it executing
1311 	 * any instructions in the mutated address space. For true spawns,
1312 	 * this is not the case, and "too late" is still not too late to
1313 	 * return an error code to the parent process.
1314 	 */
1315 
1316 	/*
1317 	 * Actually load the image file we previously decided to load.
1318 	 */
1319 	lret = load_machfile(imgp, mach_header, thread, &map, &load_result);
1320 	if (lret != LOAD_SUCCESS) {
1321 		error = load_return_to_errno(lret);
1322 
1323 		KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
1324 		    proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_BAD_MACHO, 0, 0);
1325 		if (lret == LOAD_BADMACHO_UPX) {
1326 			set_proc_name(imgp, p);
1327 			exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_UPX);
1328 			exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT;
1329 		} else {
1330 			exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_BAD_MACHO);
1331 
1332 			if (bootarg_execfailurereports) {
1333 				set_proc_name(imgp, p);
1334 				exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT;
1335 			}
1336 		}
1337 
1338 		exec_failure_reason->osr_flags |= OS_REASON_FLAG_CONSISTENT_FAILURE;
1339 
1340 		goto badtoolate;
1341 	}
1342 
1343 	/*
1344 	 * ERROR RECOVERY
1345 	 *
1346 	 * load_machfile() returned the new VM map ("map") but we haven't
1347 	 * committed to it yet.
1348 	 * Any error path between here and the point where we commit to using
1349 	 * the new "map" (with swap_task_map()) should deallocate "map".
1350 	 */
1351 
1352 #ifndef KASAN
1353 	/*
1354 	 * Security: zone sanity checks on fresh boot or initproc re-exec.
1355 	 * launchd by design does not tear down its own service port on USR (rdar://72797967),
1356 	 * which means here is the earliest point we can assert on empty service port label zone,
1357 	 * after load_machfile() above terminates old launchd's IPC space.
1358 	 *
1359 	 * Disable on KASAN builds since zone_size_allocated() accounts for elements
1360 	 * under quarantine.
1361 	 */
1362 	if (task_pid(task) == 1) {
1363 		zone_userspace_reboot_checks();
1364 	}
1365 #endif
1366 
1367 	proc_lock(p);
1368 	p->p_cputype = imgp->ip_origcputype;
1369 	p->p_cpusubtype = imgp->ip_origcpusubtype;
1370 	proc_setplatformdata(p, load_result.ip_platform, load_result.lr_min_sdk, load_result.lr_sdk);
1371 	exec_setup_tpro(imgp, &load_result);
1372 
1373 	vm_map_set_size_limit(map, proc_limitgetcur(p, RLIMIT_AS));
1374 	vm_map_set_data_limit(map, proc_limitgetcur(p, RLIMIT_DATA));
1375 	vm_map_set_user_wire_limit(map, (vm_size_t)proc_limitgetcur(p, RLIMIT_MEMLOCK));
1376 #if XNU_TARGET_OS_OSX
1377 	if (proc_platform(p) == PLATFORM_IOS) {
1378 		assert(vm_map_is_alien(map));
1379 	} else {
1380 		assert(!vm_map_is_alien(map));
1381 	}
1382 #endif /* XNU_TARGET_OS_OSX */
1383 	proc_unlock(p);
1384 
1385 	/*
1386 	 * Set TPRO flags if enabled
1387 	 */
1388 
1389 	/*
1390 	 * Set code-signing flags if this binary is signed, or if parent has
1391 	 * requested them on exec.
1392 	 */
1393 	if (load_result.csflags & CS_VALID) {
1394 		imgp->ip_csflags |= load_result.csflags &
1395 		    (CS_VALID | CS_SIGNED | CS_DEV_CODE | CS_LINKER_SIGNED |
1396 		    CS_HARD | CS_KILL | CS_RESTRICT | CS_ENFORCEMENT | CS_REQUIRE_LV |
1397 		    CS_FORCED_LV | CS_ENTITLEMENTS_VALIDATED | CS_NO_UNTRUSTED_HELPERS | CS_RUNTIME |
1398 		    CS_ENTITLEMENT_FLAGS |
1399 		    CS_EXEC_SET_HARD | CS_EXEC_SET_KILL | CS_EXEC_SET_ENFORCEMENT);
1400 	} else {
1401 		imgp->ip_csflags &= ~CS_VALID;
1402 	}
1403 
1404 	if (proc_getcsflags(p) & CS_EXEC_SET_HARD) {
1405 		imgp->ip_csflags |= CS_HARD;
1406 	}
1407 	if (proc_getcsflags(p) & CS_EXEC_SET_KILL) {
1408 		imgp->ip_csflags |= CS_KILL;
1409 	}
1410 	if (proc_getcsflags(p) & CS_EXEC_SET_ENFORCEMENT) {
1411 		imgp->ip_csflags |= CS_ENFORCEMENT;
1412 	}
1413 	if (proc_getcsflags(p) & CS_EXEC_INHERIT_SIP) {
1414 		if (proc_getcsflags(p) & CS_INSTALLER) {
1415 			imgp->ip_csflags |= CS_INSTALLER;
1416 		}
1417 		if (proc_getcsflags(p) & CS_DATAVAULT_CONTROLLER) {
1418 			imgp->ip_csflags |= CS_DATAVAULT_CONTROLLER;
1419 		}
1420 		if (proc_getcsflags(p) & CS_NVRAM_UNRESTRICTED) {
1421 			imgp->ip_csflags |= CS_NVRAM_UNRESTRICTED;
1422 		}
1423 	}
1424 
1425 #if __has_feature(ptrauth_calls) && defined(XNU_TARGET_OS_OSX)
1426 	/*
1427 	 * ptrauth version 0 is a preview ABI.  Developers can opt into running
1428 	 * their own arm64e binaries for local testing, with the understanding
1429 	 * that future OSes may break ABI.
1430 	 */
1431 	if ((imgp->ip_origcpusubtype & ~CPU_SUBTYPE_MASK) == CPU_SUBTYPE_ARM64E &&
1432 	    CPU_SUBTYPE_ARM64_PTR_AUTH_VERSION(imgp->ip_origcpusubtype) == 0 &&
1433 	    !load_result.platform_binary &&
1434 	    !bootarg_arm64e_preview_abi) {
1435 		static bool logged_once = false;
1436 		set_proc_name(imgp, p);
1437 
1438 		printf("%s: not running binary \"%s\" built against preview arm64e ABI\n", __func__, p->p_name);
1439 		if (!os_atomic_xchg(&logged_once, true, relaxed)) {
1440 			printf("%s: (to allow this, add \"-arm64e_preview_abi\" to boot-args)\n", __func__);
1441 		}
1442 
1443 		exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_BAD_MACHO);
1444 		if (bootarg_execfailurereports) {
1445 			exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT;
1446 			exec_failure_reason->osr_flags |= OS_REASON_FLAG_CONSISTENT_FAILURE;
1447 		}
1448 
1449 		/* release new address space since we won't use it */
1450 		imgp->ip_free_map = map;
1451 		map = VM_MAP_NULL;
1452 		goto badtoolate;
1453 	}
1454 
1455 	if ((imgp->ip_origcpusubtype & ~CPU_SUBTYPE_MASK) != CPU_SUBTYPE_ARM64E &&
1456 	    imgp->ip_origcputype == CPU_TYPE_ARM64 &&
1457 	    load_result.platform_binary &&
1458 	    (imgp->ip_flags & IMGPF_DRIVER) != 0) {
1459 		set_proc_name(imgp, p);
1460 		printf("%s: disallowing arm64 platform driverkit binary \"%s\", should be arm64e\n", __func__, p->p_name);
1461 		exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_BAD_MACHO);
1462 		if (bootarg_execfailurereports) {
1463 			exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT;
1464 			exec_failure_reason->osr_flags |= OS_REASON_FLAG_CONSISTENT_FAILURE;
1465 		}
1466 
1467 		/* release new address space since we won't use it */
1468 		imgp->ip_free_map = map;
1469 		map = VM_MAP_NULL;
1470 		goto badtoolate;
1471 	}
1472 #endif /* __has_feature(ptrauth_calls) && defined(XNU_TARGET_OS_OSX) */
1473 
1474 
1475 	/*
1476 	 * Set up the shared cache region in the new process.
1477 	 *
1478 	 * Normally there is a single shared region per architecture.
1479 	 * However on systems with Pointer Authentication, we can create
1480 	 * multiple shared caches with the amount of sharing determined
1481 	 * by team-id or entitlement. Inherited shared region IDs are used
1482 	 * for system processes that need to match and be able to inspect
1483 	 * a pre-existing task.
1484 	 */
1485 	int cpu_subtype = 0; /* all cpu_subtypes use the same shared region */
1486 #if __has_feature(ptrauth_calls)
1487 	char *shared_region_id = NULL;
1488 	size_t len;
1489 	char *base;
1490 	const char *cbase;
1491 #define TEAM_ID_PREFIX "T-"
1492 #define ENTITLE_PREFIX "E-"
1493 #define SR_PREFIX_LEN  2
1494 #define SR_ENTITLEMENT "com.apple.pac.shared_region_id"
1495 
1496 	if (cpu_type() == CPU_TYPE_ARM64 &&
1497 	    arm64_cpusubtype_uses_ptrauth(p->p_cpusubtype) &&
1498 	    (imgp->ip_flags & IMGPF_NOJOP) == 0) {
1499 		assertf(p->p_cputype == CPU_TYPE_ARM64,
1500 		    "p %p cpu_type() 0x%x p->p_cputype 0x%x p->p_cpusubtype 0x%x",
1501 		    p, cpu_type(), p->p_cputype, p->p_cpusubtype);
1502 
1503 		/*
1504 		 * arm64e uses pointer authentication, so request a separate
1505 		 * shared region for this CPU subtype.
1506 		 */
1507 		cpu_subtype = p->p_cpusubtype & ~CPU_SUBTYPE_MASK;
1508 
1509 		/*
1510 		 * Determine which shared cache to select based on being told,
1511 		 * matching a team-id or matching an entitlement.
1512 		 */
1513 		if (imgp->ip_inherited_shared_region_id) {
1514 			len = strlen(imgp->ip_inherited_shared_region_id);
1515 			shared_region_id = kalloc_data(len + 1, Z_WAITOK | Z_NOFAIL);
1516 			memcpy(shared_region_id, imgp->ip_inherited_shared_region_id, len + 1);
1517 		} else if ((cbase = get_teamid_for_shared_region(imgp)) != NULL) {
1518 			len = strlen(cbase);
1519 			if (vm_shared_region_per_team_id) {
1520 				shared_region_id = kalloc_data(len + SR_PREFIX_LEN + 1,
1521 				    Z_WAITOK | Z_NOFAIL);
1522 				memcpy(shared_region_id, TEAM_ID_PREFIX, SR_PREFIX_LEN);
1523 				memcpy(shared_region_id + SR_PREFIX_LEN, cbase, len + 1);
1524 			}
1525 		} else if ((base = IOVnodeGetEntitlement(imgp->ip_vp,
1526 		    (int64_t)imgp->ip_arch_offset, SR_ENTITLEMENT)) != NULL) {
1527 			len = strlen(base);
1528 			if (vm_shared_region_by_entitlement) {
1529 				shared_region_id = kalloc_data(len + SR_PREFIX_LEN + 1,
1530 				    Z_WAITOK | Z_NOFAIL);
1531 				memcpy(shared_region_id, ENTITLE_PREFIX, SR_PREFIX_LEN);
1532 				memcpy(shared_region_id + SR_PREFIX_LEN, base, len + 1);
1533 			}
1534 			/* Discard the copy of the entitlement */
1535 			kfree_data(base, len + 1);
1536 		}
1537 	}
1538 
1539 	if (imgp->ip_flags & IMGPF_RESLIDE) {
1540 		reslide = TRUE;
1541 	}
1542 
1543 	/* use "" as the default shared_region_id */
1544 	if (shared_region_id == NULL) {
1545 		shared_region_id = kalloc_data(1, Z_WAITOK | Z_ZERO | Z_NOFAIL);
1546 	}
1547 
1548 	/* ensure there's a unique pointer signing key for this shared_region_id */
1549 	shared_region_key_alloc(shared_region_id,
1550 	    imgp->ip_inherited_shared_region_id != NULL, imgp->ip_inherited_jop_pid);
1551 	task_set_shared_region_id(task, shared_region_id);
1552 	shared_region_id = NULL;
1553 #endif /* __has_feature(ptrauth_calls) */
1554 
1555 #if CONFIG_ROSETTA
1556 	if (imgp->ip_flags & IMGPF_ROSETTA) {
1557 		OSBitOrAtomic(P_TRANSLATED, &p->p_flag);
1558 	} else if (p->p_flag & P_TRANSLATED) {
1559 		OSBitAndAtomic(~P_TRANSLATED, &p->p_flag);
1560 	}
1561 #endif
1562 
1563 	int cputype = cpu_type();
1564 
1565 	uint32_t rsr_version = 0;
1566 #if XNU_TARGET_OS_OSX
1567 	if (vnode_is_rsr(imgp->ip_vp)) {
1568 		rsr_version = rsr_get_version();
1569 		os_atomic_or(&p->p_ladvflag, P_RSR, relaxed);
1570 		os_atomic_or(&p->p_vfs_iopolicy, P_VFS_IOPOLICY_ALTLINK, relaxed);
1571 	}
1572 #endif /* XNU_TARGET_OS_OSX */
1573 
1574 	vm_map_exec(map, task, load_result.is_64bit_addr,
1575 	    (void *)p->p_fd.fd_rdir, cputype, cpu_subtype, reslide,
1576 	    (imgp->ip_flags & IMGPF_DRIVER) != 0,
1577 	    rsr_version);
1578 
1579 	/*
1580 	 * Close file descriptors which specify close-on-exec.
1581 	 */
1582 	fdt_exec(p, psa != NULL ? psa->psa_flags : 0, imgp->ip_new_thread, exec);
1583 
1584 	/*
1585 	 * deal with set[ug]id.
1586 	 */
1587 	error = exec_handle_sugid(imgp);
1588 	if (error) {
1589 		KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
1590 		    proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_SUGID_FAILURE, 0, 0);
1591 
1592 		exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_SUGID_FAILURE);
1593 		if (bootarg_execfailurereports) {
1594 			set_proc_name(imgp, p);
1595 			exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT;
1596 		}
1597 
1598 		/* release new address space since we won't use it */
1599 		imgp->ip_free_map = map;
1600 		map = VM_MAP_NULL;
1601 		goto badtoolate;
1602 	}
1603 
1604 	/*
1605 	 * Commit to new map.
1606 	 *
1607 	 * Swap the new map for the old for target task, which consumes
1608 	 * our new map reference but each leaves us responsible for the
1609 	 * old_map reference.  That lets us get off the pmap associated
1610 	 * with it, and then we can release it.
1611 	 *
1612 	 * The map needs to be set on the target task which is different
1613 	 * than current task, thus swap_task_map is used instead of
1614 	 * vm_map_switch.
1615 	 */
1616 	old_map = swap_task_map(task, thread, map);
1617 #if MACH_ASSERT
1618 	/*
1619 	 * Reset the pmap's process info to prevent ledger checks
1620 	 * which might fail due to the ledgers being shared between
1621 	 * the old and new pmaps.
1622 	 */
1623 	vm_map_pmap_set_process(old_map, -1, "<old_map>");
1624 #endif /* MACH_ASSERT */
1625 	imgp->ip_free_map = old_map;
1626 	old_map = NULL;
1627 
1628 	lret = activate_exec_state(task, p, thread, &load_result);
1629 	if (lret != KERN_SUCCESS) {
1630 		KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
1631 		    proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_ACTV_THREADSTATE, 0, 0);
1632 
1633 		exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_ACTV_THREADSTATE);
1634 		if (bootarg_execfailurereports) {
1635 			set_proc_name(imgp, p);
1636 			exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT;
1637 		}
1638 
1639 		goto badtoolate;
1640 	}
1641 
1642 	/*
1643 	 * deal with voucher on exec-calling thread.
1644 	 */
1645 	if (imgp->ip_new_thread == NULL) {
1646 		thread_set_mach_voucher(current_thread(), IPC_VOUCHER_NULL);
1647 	}
1648 
1649 	/* Make sure we won't interrupt ourself signalling a partial process */
1650 	if (!vfexec && !spawn && (p->p_lflag & P_LTRACED)) {
1651 		psignal(p, SIGTRAP);
1652 	}
1653 
1654 	if (load_result.unixproc &&
1655 	    create_unix_stack(get_task_map(task),
1656 	    &load_result,
1657 	    p) != KERN_SUCCESS) {
1658 		error = load_return_to_errno(LOAD_NOSPACE);
1659 
1660 		KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
1661 		    proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_STACK_ALLOC, 0, 0);
1662 
1663 		exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_STACK_ALLOC);
1664 		if (bootarg_execfailurereports) {
1665 			set_proc_name(imgp, p);
1666 			exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT;
1667 		}
1668 
1669 		goto badtoolate;
1670 	}
1671 
1672 	/*
1673 	 * The load result will have already been munged by AMFI to include the
1674 	 * platform binary flag if boot-args dictated it (AMFI will mark anything
1675 	 * that doesn't go through the upcall path as a platform binary if its
1676 	 * enforcement is disabled).
1677 	 */
1678 	if (load_result.platform_binary) {
1679 		if (cs_debug) {
1680 			printf("setting platform binary on task: pid = %d\n", proc_getpid(p));
1681 		}
1682 
1683 		/*
1684 		 * We must use 'task' here because the proc's task has not yet been
1685 		 * switched to the new one.
1686 		 */
1687 		task_set_platform_binary(task, TRUE);
1688 	} else {
1689 		if (cs_debug) {
1690 			printf("clearing platform binary on task: pid = %d\n", proc_getpid(p));
1691 		}
1692 
1693 		task_set_platform_binary(task, FALSE);
1694 	}
1695 
1696 	/*
1697 	 * Set starting EXC_GUARD and control port behavior for task now that
1698 	 * platform is set. Use the name directly from imgp since we haven't
1699 	 * set_proc_name() yet. Also make control port for the task and main thread
1700 	 * immovable/pinned based on task's option.
1701 	 *
1702 	 * Must happen before main thread port copyout in exc_add_apple_strings.
1703 	 */
1704 	task_set_exc_guard_ctrl_port_default(task, thread,
1705 	    imgp->ip_ndp->ni_cnd.cn_nameptr,
1706 	    (unsigned)imgp->ip_ndp->ni_cnd.cn_namelen,
1707 	    proc_is_simulated(p),
1708 	    load_result.ip_platform,
1709 	    load_result.lr_sdk);
1710 
1711 	error = exec_add_apple_strings(imgp, &load_result); /* copies out main thread port */
1712 
1713 	if (error) {
1714 		KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
1715 		    proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_APPLE_STRING_INIT, 0, 0);
1716 
1717 		exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_APPLE_STRING_INIT);
1718 		if (bootarg_execfailurereports) {
1719 			set_proc_name(imgp, p);
1720 			exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT;
1721 		}
1722 		goto badtoolate;
1723 	}
1724 
1725 	/* Switch to target task's map to copy out strings */
1726 	old_map = vm_map_switch(get_task_map(task));
1727 
1728 	if (load_result.unixproc) {
1729 		user_addr_t     ap;
1730 
1731 		/*
1732 		 * Copy the strings area out into the new process address
1733 		 * space.
1734 		 */
1735 		ap = p->user_stack;
1736 		error = exec_copyout_strings(imgp, &ap);
1737 		if (error) {
1738 			vm_map_switch(old_map);
1739 
1740 			KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
1741 			    proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_COPYOUT_STRINGS, 0, 0);
1742 
1743 			exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_COPYOUT_STRINGS);
1744 			if (bootarg_execfailurereports) {
1745 				set_proc_name(imgp, p);
1746 				exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT;
1747 			}
1748 			goto badtoolate;
1749 		}
1750 		/* Set the stack */
1751 		thread_setuserstack(thread, ap);
1752 	}
1753 
1754 	if (load_result.dynlinker || load_result.is_rosetta) {
1755 		user_addr_t        ap;
1756 		int                     new_ptr_size = (imgp->ip_flags & IMGPF_IS_64BIT_ADDR) ? 8 : 4;
1757 
1758 		/* Adjust the stack */
1759 		ap = thread_adjuserstack(thread, -new_ptr_size);
1760 		error = copyoutptr(load_result.mach_header, ap, new_ptr_size);
1761 
1762 		if (error) {
1763 			vm_map_switch(old_map);
1764 
1765 			KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
1766 			    proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_COPYOUT_DYNLINKER, 0, 0);
1767 
1768 			exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_COPYOUT_DYNLINKER);
1769 			if (bootarg_execfailurereports) {
1770 				set_proc_name(imgp, p);
1771 				exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT;
1772 			}
1773 			goto badtoolate;
1774 		}
1775 		error = task_set_dyld_info(task, load_result.all_image_info_addr,
1776 		    load_result.all_image_info_size);
1777 		if (error) {
1778 			vm_map_switch(old_map);
1779 
1780 			KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
1781 			    proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_SET_DYLD_INFO, 0, 0);
1782 
1783 			exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_SET_DYLD_INFO);
1784 			if (bootarg_execfailurereports) {
1785 				set_proc_name(imgp, p);
1786 				exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT;
1787 			}
1788 			error = EINVAL;
1789 			goto badtoolate;
1790 		}
1791 	}
1792 
1793 #if CONFIG_ROSETTA
1794 	if (load_result.is_rosetta) {
1795 		// Add an fd for the executable file for Rosetta's use
1796 		int main_binary_fd;
1797 		struct fileproc *fp;
1798 
1799 		error = falloc(p, &fp, &main_binary_fd, imgp->ip_vfs_context);
1800 		if (error) {
1801 			vm_map_switch(old_map);
1802 
1803 			KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
1804 			    proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_MAIN_FD_ALLOC, 0, 0);
1805 
1806 			exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_MAIN_FD_ALLOC);
1807 			if (bootarg_execfailurereports) {
1808 				set_proc_name(imgp, p);
1809 				exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT;
1810 			}
1811 			goto badtoolate;
1812 		}
1813 
1814 		error = VNOP_OPEN(imgp->ip_vp, FREAD, imgp->ip_vfs_context);
1815 		if (error) {
1816 			vm_map_switch(old_map);
1817 
1818 			KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
1819 			    proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_MAIN_FD_ALLOC, 0, 0);
1820 
1821 			exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_MAIN_FD_ALLOC);
1822 			if (bootarg_execfailurereports) {
1823 				set_proc_name(imgp, p);
1824 				exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT;
1825 			}
1826 			goto cleanup_rosetta_fp;
1827 		}
1828 
1829 		fp->fp_glob->fg_flag = FREAD;
1830 		fp->fp_glob->fg_ops = &vnops;
1831 		fp_set_data(fp, imgp->ip_vp);
1832 
1833 		proc_fdlock(p);
1834 		procfdtbl_releasefd(p, main_binary_fd, NULL);
1835 		fp_drop(p, main_binary_fd, fp, 1);
1836 		proc_fdunlock(p);
1837 
1838 		vnode_ref(imgp->ip_vp);
1839 
1840 		// Pass the dyld load address, main binary fd, and dyld fd on the stack
1841 		uint64_t ap = thread_adjuserstack(thread, -24);
1842 
1843 		error = copyoutptr((user_addr_t)load_result.dynlinker_fd, ap, 8);
1844 		if (error) {
1845 			vm_map_switch(old_map);
1846 
1847 			KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
1848 			    proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_COPYOUT_ROSETTA, 0, 0);
1849 
1850 			exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_COPYOUT_ROSETTA);
1851 			if (bootarg_execfailurereports) {
1852 				set_proc_name(imgp, p);
1853 				exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT;
1854 			}
1855 			goto cleanup_rosetta_fp;
1856 		}
1857 
1858 		error = copyoutptr(load_result.dynlinker_mach_header, ap + 8, 8);
1859 		if (error) {
1860 			vm_map_switch(old_map);
1861 
1862 			KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
1863 			    proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_COPYOUT_ROSETTA, 0, 0);
1864 
1865 			exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_COPYOUT_ROSETTA);
1866 			if (bootarg_execfailurereports) {
1867 				set_proc_name(imgp, p);
1868 				exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT;
1869 			}
1870 			goto cleanup_rosetta_fp;
1871 		}
1872 
1873 		error = copyoutptr((user_addr_t)main_binary_fd, ap + 16, 8);
1874 		if (error) {
1875 			vm_map_switch(old_map);
1876 
1877 			KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
1878 			    proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_COPYOUT_ROSETTA, 0, 0);
1879 
1880 			exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_COPYOUT_ROSETTA);
1881 			if (bootarg_execfailurereports) {
1882 				set_proc_name(imgp, p);
1883 				exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT;
1884 			}
1885 			goto cleanup_rosetta_fp;
1886 		}
1887 
1888 cleanup_rosetta_fp:
1889 		if (error) {
1890 			fp_free(p, load_result.dynlinker_fd, load_result.dynlinker_fp);
1891 			fp_free(p, main_binary_fd, fp);
1892 			goto badtoolate;
1893 		}
1894 	}
1895 
1896 #endif
1897 
1898 	/* Avoid immediate VM faults back into kernel */
1899 	exec_prefault_data(p, imgp, &load_result);
1900 
1901 	vm_map_switch(old_map);
1902 
1903 	/*
1904 	 * Reset signal state.
1905 	 */
1906 	execsigs(p, thread);
1907 
1908 	/*
1909 	 * need to cancel async IO requests that can be cancelled and wait for those
1910 	 * already active.  MAY BLOCK!
1911 	 */
1912 	_aio_exec( p );
1913 
1914 #if SYSV_SHM
1915 	/* FIXME: Till vmspace inherit is fixed: */
1916 	if (!vfexec && p->vm_shm) {
1917 		shmexec(p);
1918 	}
1919 #endif
1920 #if SYSV_SEM
1921 	/* Clean up the semaphores */
1922 	semexit(p);
1923 #endif
1924 
1925 	/*
1926 	 * Remember file name for accounting.
1927 	 */
1928 	p->p_acflag &= ~AFORK;
1929 
1930 	set_proc_name(imgp, p);
1931 
1932 #if CONFIG_SECLUDED_MEMORY
1933 	if (secluded_for_apps &&
1934 	    load_result.platform_binary) {
1935 		if (strncmp(p->p_name,
1936 		    "Camera",
1937 		    sizeof(p->p_name)) == 0) {
1938 			task_set_could_use_secluded_mem(task, TRUE);
1939 		} else {
1940 			task_set_could_use_secluded_mem(task, FALSE);
1941 		}
1942 		if (strncmp(p->p_name,
1943 		    "mediaserverd",
1944 		    sizeof(p->p_name)) == 0) {
1945 			task_set_could_also_use_secluded_mem(task, TRUE);
1946 		}
1947 	}
1948 #endif /* CONFIG_SECLUDED_MEMORY */
1949 
1950 #if __arm64__
1951 	if (load_result.legacy_footprint) {
1952 		task_set_legacy_footprint(task);
1953 	}
1954 #endif /* __arm64__ */
1955 
1956 	pal_dbg_set_task_name(task);
1957 
1958 #if DEVELOPMENT || DEBUG
1959 	/*
1960 	 * Update the pid an proc name for importance base if any
1961 	 */
1962 	task_importance_update_owner_info(task);
1963 #endif
1964 
1965 	proc_setexecutableuuid(p, &load_result.uuid[0]);
1966 
1967 #if CONFIG_DTRACE
1968 	dtrace_proc_exec(p);
1969 #endif
1970 
1971 	if (kdebug_enable) {
1972 		long args[4] = {};
1973 
1974 		uintptr_t fsid = 0, fileid = 0;
1975 		if (imgp->ip_vattr) {
1976 			uint64_t fsid64 = vnode_get_va_fsid(imgp->ip_vattr);
1977 			fsid   = (uintptr_t)fsid64;
1978 			fileid = (uintptr_t)imgp->ip_vattr->va_fileid;
1979 			// check for (unexpected) overflow and trace zero in that case
1980 			if (fsid != fsid64 || fileid != imgp->ip_vattr->va_fileid) {
1981 				fsid = fileid = 0;
1982 			}
1983 		}
1984 		KERNEL_DEBUG_CONSTANT_IST1(TRACE_DATA_EXEC, proc_getpid(p), fsid, fileid, 0,
1985 		    (uintptr_t)thread_tid(thread));
1986 
1987 		extern void kdebug_proc_name_args(struct proc *proc, long args[static 4]);
1988 		kdebug_proc_name_args(p, args);
1989 		KERNEL_DEBUG_CONSTANT_IST1(TRACE_STRING_EXEC, args[0], args[1],
1990 		    args[2], args[3], (uintptr_t)thread_tid(thread));
1991 	}
1992 
1993 
1994 	/*
1995 	 * If posix_spawned with the START_SUSPENDED flag, stop the
1996 	 * process before it runs.
1997 	 */
1998 	if (imgp->ip_px_sa != NULL) {
1999 		psa = (struct _posix_spawnattr *) imgp->ip_px_sa;
2000 		if (psa->psa_flags & POSIX_SPAWN_START_SUSPENDED) {
2001 			proc_lock(p);
2002 			p->p_stat = SSTOP;
2003 			proc_unlock(p);
2004 			(void) task_suspend_internal(task);
2005 		}
2006 	}
2007 
2008 	/*
2009 	 * mark as execed
2010 	 */
2011 	OSBitOrAtomic(P_EXEC, &p->p_flag);
2012 	proc_resetregister(p);
2013 	if (p->p_pptr && (p->p_lflag & P_LPPWAIT)) {
2014 		proc_lock(p);
2015 		p->p_lflag &= ~P_LPPWAIT;
2016 		proc_unlock(p);
2017 		wakeup((caddr_t)p->p_pptr);
2018 	}
2019 
2020 	/*
2021 	 * Set up dext coredumps on kernel panic.
2022 	 * This requires the following:
2023 	 * - dext_panic_coredump=1 boot-arg (enabled by default on DEVELOPMENT, DEBUG and certain Seed builds)
2024 	 * - process must be a driver
2025 	 * - process must have the com.apple.private.enable-coredump-on-panic entitlement, and the
2026 	 *   entitlement has a string value.
2027 	 * - process must have the com.apple.private.enable-coredump-on-panic-seed-privacy-approved
2028 	 *   entitlement (Seed builds only).
2029 	 *
2030 	 * The core dump file name is formatted with the entitlement string value, followed by a hyphen
2031 	 * and the process PID.
2032 	 */
2033 	if (enable_dext_coredumps_on_panic &&
2034 	    (imgp->ip_flags & IMGPF_DRIVER) != 0 &&
2035 	    (userspace_coredump_name = IOVnodeGetEntitlement(imgp->ip_vp,
2036 	    (int64_t)imgp->ip_arch_offset, USERSPACE_COREDUMP_PANIC_ENTITLEMENT)) != NULL) {
2037 		size_t userspace_coredump_name_len = strlen(userspace_coredump_name);
2038 
2039 		char core_name[MACH_CORE_FILEHEADER_NAMELEN];
2040 		/* 16 - NULL char - strlen("-") - maximum of 5 digits for pid */
2041 		snprintf(core_name, MACH_CORE_FILEHEADER_NAMELEN, "%.9s-%d", userspace_coredump_name, proc_getpid(p));
2042 
2043 		kern_register_userspace_coredump(task, core_name);
2044 
2045 		/* Discard the copy of the entitlement */
2046 		kfree_data(userspace_coredump_name, userspace_coredump_name_len + 1);
2047 		userspace_coredump_name = NULL;
2048 	}
2049 
2050 	goto done;
2051 
2052 badtoolate:
2053 	/* Don't allow child process to execute any instructions */
2054 	if (!spawn) {
2055 		{
2056 			assert(exec_failure_reason != OS_REASON_NULL);
2057 			if (bootarg_execfailurereports) {
2058 				set_proc_name(imgp, current_proc());
2059 			}
2060 			psignal_with_reason(current_proc(), SIGKILL, exec_failure_reason);
2061 			exec_failure_reason = OS_REASON_NULL;
2062 
2063 			if (exec) {
2064 				/* Terminate the exec copy task */
2065 				task_terminate_internal(task);
2066 			}
2067 		}
2068 
2069 		/* We can't stop this system call at this point, so just pretend we succeeded */
2070 		error = 0;
2071 	} else {
2072 		os_reason_free(exec_failure_reason);
2073 		exec_failure_reason = OS_REASON_NULL;
2074 	}
2075 
2076 done:
2077 	if (load_result.threadstate) {
2078 		kfree_data(load_result.threadstate, load_result.threadstate_sz);
2079 		load_result.threadstate = NULL;
2080 	}
2081 
2082 bad:
2083 	/* If we hit this, we likely would have leaked an exit reason */
2084 	assert(exec_failure_reason == OS_REASON_NULL);
2085 	return error;
2086 }
2087 
2088 
2089 
2090 
2091 /*
2092  * Our image activator table; this is the table of the image types we are
2093  * capable of loading.  We list them in order of preference to ensure the
2094  * fastest image load speed.
2095  *
2096  * XXX hardcoded, for now; should use linker sets
2097  */
2098 struct execsw {
2099 	int(*const ex_imgact)(struct image_params *);
2100 	const char *ex_name;
2101 }const execsw[] = {
2102 	{ exec_mach_imgact, "Mach-o Binary" },
2103 	{ exec_fat_imgact, "Fat Binary" },
2104 	{ exec_shell_imgact, "Interpreter Script" },
2105 	{ NULL, NULL}
2106 };
2107 
2108 
2109 /*
2110  * exec_activate_image
2111  *
2112  * Description:	Iterate through the available image activators, and activate
2113  *		the image associated with the imgp structure.  We start with
2114  *		the activator for Mach-o binaries followed by that for Fat binaries
2115  *		for Interpreter scripts.
2116  *
2117  * Parameters:	struct image_params *	Image parameter block
2118  *
2119  * Returns:	0			Success
2120  *		ENOEXEC			No activator for image.
2121  *		EBADEXEC		The executable is corrupt/unknown
2122  *	execargs_alloc:EINVAL		Invalid argument
2123  *	execargs_alloc:EACCES		Permission denied
2124  *	execargs_alloc:EINTR		Interrupted function
2125  *	execargs_alloc:ENOMEM		Not enough space
2126  *	exec_save_path:EFAULT		Bad address
2127  *	exec_save_path:ENAMETOOLONG	Filename too long
2128  *	exec_check_permissions:EACCES	Permission denied
2129  *	exec_check_permissions:ENOEXEC	Executable file format error
2130  *	exec_check_permissions:ETXTBSY	Text file busy [misuse of error code]
2131  *	exec_check_permissions:???
2132  *	namei:???
2133  *	vn_rdwr:???			[anything vn_rdwr can return]
2134  *	<ex_imgact>:???			[anything an imgact can return]
2135  *	EDEADLK				Process is being terminated
2136  */
2137 static int
exec_activate_image(struct image_params * imgp)2138 exec_activate_image(struct image_params *imgp)
2139 {
2140 	struct nameidata *ndp = NULL;
2141 	const char *excpath;
2142 	int error;
2143 	int resid;
2144 	int once = 1;   /* save SGUID-ness for interpreted files */
2145 	int i;
2146 	int itercount = 0;
2147 	proc_t p = vfs_context_proc(imgp->ip_vfs_context);
2148 
2149 	/*
2150 	 * For exec, the translock needs to be taken on old proc and not
2151 	 * on new shadow proc.
2152 	 */
2153 	if (imgp->ip_flags & IMGPF_EXEC) {
2154 		p = current_proc();
2155 	}
2156 
2157 	error = execargs_alloc(imgp);
2158 	if (error) {
2159 		goto bad_notrans;
2160 	}
2161 
2162 	error = exec_save_path(imgp, imgp->ip_user_fname, imgp->ip_seg, &excpath);
2163 	if (error) {
2164 		goto bad_notrans;
2165 	}
2166 
2167 	/* Use excpath, which contains the copyin-ed exec path */
2168 	DTRACE_PROC1(exec, uintptr_t, excpath);
2169 
2170 	ndp = kalloc_type(struct nameidata, Z_WAITOK | Z_ZERO | Z_NOFAIL);
2171 
2172 	NDINIT(ndp, LOOKUP, OP_LOOKUP, FOLLOW | LOCKLEAF | AUDITVNPATH1,
2173 	    UIO_SYSSPACE, CAST_USER_ADDR_T(excpath), imgp->ip_vfs_context);
2174 
2175 again:
2176 	error = namei(ndp);
2177 	if (error) {
2178 		if (error == ERESTART) {
2179 			error = EINTR;
2180 		}
2181 		goto bad_notrans;
2182 	}
2183 	imgp->ip_ndp = ndp;     /* successful namei(); call nameidone() later */
2184 	imgp->ip_vp = ndp->ni_vp;       /* if set, need to vnode_put() at some point */
2185 
2186 	/*
2187 	 * Before we start the transition from binary A to binary B, make
2188 	 * sure another thread hasn't started exiting the process.  We grab
2189 	 * the proc lock to check p_lflag initially, and the transition
2190 	 * mechanism ensures that the value doesn't change after we release
2191 	 * the lock.
2192 	 */
2193 	proc_lock(p);
2194 	if (p->p_lflag & P_LEXIT) {
2195 		error = EDEADLK;
2196 		proc_unlock(p);
2197 		goto bad_notrans;
2198 	}
2199 	error = proc_transstart(p, 1, 0);
2200 	proc_unlock(p);
2201 	if (error) {
2202 		goto bad_notrans;
2203 	}
2204 
2205 	error = exec_check_permissions(imgp);
2206 	if (error) {
2207 		goto bad;
2208 	}
2209 
2210 	/* Copy; avoid invocation of an interpreter overwriting the original */
2211 	if (once) {
2212 		once = 0;
2213 		*imgp->ip_origvattr = *imgp->ip_vattr;
2214 	}
2215 
2216 	error = vn_rdwr(UIO_READ, imgp->ip_vp, imgp->ip_vdata, PAGE_SIZE, 0,
2217 	    UIO_SYSSPACE, IO_NODELOCKED,
2218 	    vfs_context_ucred(imgp->ip_vfs_context),
2219 	    &resid, vfs_context_proc(imgp->ip_vfs_context));
2220 	if (error) {
2221 		goto bad;
2222 	}
2223 
2224 	if (resid) {
2225 		memset(imgp->ip_vdata + (PAGE_SIZE - resid), 0x0, resid);
2226 	}
2227 
2228 encapsulated_binary:
2229 	/* Limit the number of iterations we will attempt on each binary */
2230 	if (++itercount > EAI_ITERLIMIT) {
2231 		error = EBADEXEC;
2232 		goto bad;
2233 	}
2234 	error = -1;
2235 	for (i = 0; error == -1 && execsw[i].ex_imgact != NULL; i++) {
2236 		error = (*execsw[i].ex_imgact)(imgp);
2237 
2238 		switch (error) {
2239 		/* case -1: not claimed: continue */
2240 		case -2:                /* Encapsulated binary, imgp->ip_XXX set for next iteration */
2241 			goto encapsulated_binary;
2242 
2243 		case -3:                /* Interpreter */
2244 #if CONFIG_MACF
2245 			/*
2246 			 * Copy the script label for later use. Note that
2247 			 * the label can be different when the script is
2248 			 * actually read by the interpreter.
2249 			 */
2250 			if (imgp->ip_scriptlabelp) {
2251 				mac_vnode_label_free(imgp->ip_scriptlabelp);
2252 				imgp->ip_scriptlabelp = NULL;
2253 			}
2254 			imgp->ip_scriptlabelp = mac_vnode_label_alloc(NULL);
2255 			if (imgp->ip_scriptlabelp == NULL) {
2256 				error = ENOMEM;
2257 				break;
2258 			}
2259 			mac_vnode_label_copy(mac_vnode_label(imgp->ip_vp),
2260 			    imgp->ip_scriptlabelp);
2261 
2262 			/*
2263 			 * Take a ref of the script vnode for later use.
2264 			 */
2265 			if (imgp->ip_scriptvp) {
2266 				vnode_put(imgp->ip_scriptvp);
2267 				imgp->ip_scriptvp = NULLVP;
2268 			}
2269 			if (vnode_getwithref(imgp->ip_vp) == 0) {
2270 				imgp->ip_scriptvp = imgp->ip_vp;
2271 			}
2272 #endif
2273 
2274 			nameidone(ndp);
2275 
2276 			vnode_put(imgp->ip_vp);
2277 			imgp->ip_vp = NULL;     /* already put */
2278 			imgp->ip_ndp = NULL; /* already nameidone */
2279 
2280 			/* Use excpath, which exec_shell_imgact reset to the interpreter */
2281 			NDINIT(ndp, LOOKUP, OP_LOOKUP, FOLLOW | LOCKLEAF,
2282 			    UIO_SYSSPACE, CAST_USER_ADDR_T(excpath), imgp->ip_vfs_context);
2283 
2284 			proc_transend(p, 0);
2285 			goto again;
2286 
2287 		default:
2288 			break;
2289 		}
2290 	}
2291 
2292 	if (error == -1) {
2293 		error = ENOEXEC;
2294 	} else if (error == 0) {
2295 		if (imgp->ip_flags & IMGPF_INTERPRET && ndp->ni_vp) {
2296 			AUDIT_ARG(vnpath, ndp->ni_vp, ARG_VNODE2);
2297 		}
2298 
2299 		/*
2300 		 * Call out to allow 3rd party notification of exec.
2301 		 * Ignore result of kauth_authorize_fileop call.
2302 		 */
2303 		if (kauth_authorize_fileop_has_listeners()) {
2304 			kauth_authorize_fileop(vfs_context_ucred(imgp->ip_vfs_context),
2305 			    KAUTH_FILEOP_EXEC,
2306 			    (uintptr_t)ndp->ni_vp, 0);
2307 		}
2308 	}
2309 bad:
2310 	proc_transend(p, 0);
2311 
2312 bad_notrans:
2313 	if (imgp->ip_strings) {
2314 		execargs_free(imgp);
2315 	}
2316 	if (imgp->ip_ndp) {
2317 		nameidone(imgp->ip_ndp);
2318 	}
2319 	kfree_type(struct nameidata, ndp);
2320 
2321 	return error;
2322 }
2323 
2324 /*
2325  * exec_validate_spawnattr_policy
2326  *
2327  * Description: Validates the entitlements required to set the apptype.
2328  *
2329  * Parameters:  int psa_apptype         posix spawn attribute apptype
2330  *
2331  * Returns:     0                       Success
2332  *              EPERM                   Failure
2333  */
2334 static errno_t
exec_validate_spawnattr_policy(int psa_apptype)2335 exec_validate_spawnattr_policy(int psa_apptype)
2336 {
2337 	if ((psa_apptype & POSIX_SPAWN_PROC_TYPE_MASK) != 0) {
2338 		int proctype = psa_apptype & POSIX_SPAWN_PROC_TYPE_MASK;
2339 		if (proctype == POSIX_SPAWN_PROC_TYPE_DRIVER) {
2340 			if (!IOCurrentTaskHasEntitlement(POSIX_SPAWN_ENTITLEMENT_DRIVER)) {
2341 				return EPERM;
2342 			}
2343 		}
2344 	}
2345 
2346 	return 0;
2347 }
2348 
2349 /*
2350  * exec_handle_spawnattr_policy
2351  *
2352  * Description: Decode and apply the posix_spawn apptype, qos clamp, and watchport ports to the task.
2353  *
2354  * Parameters:  proc_t p                process to apply attributes to
2355  *              int psa_apptype         posix spawn attribute apptype
2356  *
2357  * Returns:     0                       Success
2358  */
2359 static errno_t
exec_handle_spawnattr_policy(proc_t p,thread_t thread,int psa_apptype,uint64_t psa_qos_clamp,task_role_t psa_darwin_role,struct exec_port_actions * port_actions)2360 exec_handle_spawnattr_policy(proc_t p, thread_t thread, int psa_apptype, uint64_t psa_qos_clamp,
2361     task_role_t psa_darwin_role, struct exec_port_actions *port_actions)
2362 {
2363 	int apptype     = TASK_APPTYPE_NONE;
2364 	int qos_clamp   = THREAD_QOS_UNSPECIFIED;
2365 	task_role_t role = TASK_UNSPECIFIED;
2366 
2367 	if ((psa_apptype & POSIX_SPAWN_PROC_TYPE_MASK) != 0) {
2368 		int proctype = psa_apptype & POSIX_SPAWN_PROC_TYPE_MASK;
2369 
2370 		switch (proctype) {
2371 		case POSIX_SPAWN_PROC_TYPE_DAEMON_INTERACTIVE:
2372 			apptype = TASK_APPTYPE_DAEMON_INTERACTIVE;
2373 			break;
2374 		case POSIX_SPAWN_PROC_TYPE_DAEMON_STANDARD:
2375 			apptype = TASK_APPTYPE_DAEMON_STANDARD;
2376 			break;
2377 		case POSIX_SPAWN_PROC_TYPE_DAEMON_ADAPTIVE:
2378 			apptype = TASK_APPTYPE_DAEMON_ADAPTIVE;
2379 			break;
2380 		case POSIX_SPAWN_PROC_TYPE_DAEMON_BACKGROUND:
2381 			apptype = TASK_APPTYPE_DAEMON_BACKGROUND;
2382 			break;
2383 		case POSIX_SPAWN_PROC_TYPE_APP_DEFAULT:
2384 			apptype = TASK_APPTYPE_APP_DEFAULT;
2385 			break;
2386 		case POSIX_SPAWN_PROC_TYPE_DRIVER:
2387 			apptype = TASK_APPTYPE_DRIVER;
2388 			break;
2389 		default:
2390 			apptype = TASK_APPTYPE_NONE;
2391 			/* TODO: Should an invalid value here fail the spawn? */
2392 			break;
2393 		}
2394 	}
2395 
2396 	if (psa_qos_clamp != POSIX_SPAWN_PROC_CLAMP_NONE) {
2397 		switch (psa_qos_clamp) {
2398 		case POSIX_SPAWN_PROC_CLAMP_UTILITY:
2399 			qos_clamp = THREAD_QOS_UTILITY;
2400 			break;
2401 		case POSIX_SPAWN_PROC_CLAMP_BACKGROUND:
2402 			qos_clamp = THREAD_QOS_BACKGROUND;
2403 			break;
2404 		case POSIX_SPAWN_PROC_CLAMP_MAINTENANCE:
2405 			qos_clamp = THREAD_QOS_MAINTENANCE;
2406 			break;
2407 		default:
2408 			qos_clamp = THREAD_QOS_UNSPECIFIED;
2409 			/* TODO: Should an invalid value here fail the spawn? */
2410 			break;
2411 		}
2412 	}
2413 
2414 	if (psa_darwin_role != PRIO_DARWIN_ROLE_DEFAULT) {
2415 		proc_darwin_role_to_task_role(psa_darwin_role, &role);
2416 	}
2417 
2418 	if (apptype != TASK_APPTYPE_NONE ||
2419 	    qos_clamp != THREAD_QOS_UNSPECIFIED ||
2420 	    role != TASK_UNSPECIFIED ||
2421 	    port_actions->portwatch_count) {
2422 		proc_set_task_spawnpolicy(proc_task(p), thread, apptype, qos_clamp, role,
2423 		    port_actions->portwatch_array, port_actions->portwatch_count);
2424 	}
2425 
2426 	if (port_actions->registered_count) {
2427 		if (mach_ports_register(proc_task(p), port_actions->registered_array,
2428 		    port_actions->registered_count)) {
2429 			return EINVAL;
2430 		}
2431 		/* mach_ports_register() consumed the array */
2432 		port_actions->registered_array = NULL;
2433 		port_actions->registered_count = 0;
2434 	}
2435 
2436 	return 0;
2437 }
2438 
2439 static void
exec_port_actions_destroy(struct exec_port_actions * port_actions)2440 exec_port_actions_destroy(struct exec_port_actions *port_actions)
2441 {
2442 	if (port_actions->portwatch_array) {
2443 		for (uint32_t i = 0; i < port_actions->portwatch_count; i++) {
2444 			ipc_port_t port = NULL;
2445 			if ((port = port_actions->portwatch_array[i]) != NULL) {
2446 				ipc_port_release_send(port);
2447 			}
2448 		}
2449 		kfree_type(ipc_port_t, port_actions->portwatch_count,
2450 		    port_actions->portwatch_array);
2451 	}
2452 
2453 	if (port_actions->registered_array) {
2454 		for (uint32_t i = 0; i < port_actions->registered_count; i++) {
2455 			ipc_port_t port = NULL;
2456 			if ((port = port_actions->registered_array[i]) != NULL) {
2457 				ipc_port_release_send(port);
2458 			}
2459 		}
2460 		kfree_type(ipc_port_t, port_actions->registered_count,
2461 		    port_actions->registered_array);
2462 	}
2463 }
2464 
2465 /*
2466  * exec_handle_port_actions
2467  *
2468  * Description:	Go through the _posix_port_actions_t contents,
2469  *              calling task_set_special_port, task_set_exception_ports
2470  *              and/or audit_session_spawnjoin for the current task.
2471  *
2472  * Parameters:	struct image_params *	Image parameter block
2473  *
2474  * Returns:	0			Success
2475  *              EINVAL			Failure
2476  *              ENOTSUP			Illegal posix_spawn attr flag was set
2477  */
2478 static errno_t
exec_handle_port_actions(struct image_params * imgp,struct exec_port_actions * actions)2479 exec_handle_port_actions(struct image_params *imgp,
2480     struct exec_port_actions *actions)
2481 {
2482 	_posix_spawn_port_actions_t pacts = imgp->ip_px_spa;
2483 #if CONFIG_AUDIT
2484 	proc_t p = vfs_context_proc(imgp->ip_vfs_context);
2485 #endif
2486 	_ps_port_action_t *act = NULL;
2487 	task_t task = get_threadtask(imgp->ip_new_thread);
2488 	ipc_port_t port = NULL;
2489 	errno_t ret = 0;
2490 	int i, portwatch_i = 0, registered_i = 0;
2491 	kern_return_t kr;
2492 	boolean_t task_has_watchport_boost = task_has_watchports(current_task());
2493 	boolean_t in_exec = (imgp->ip_flags & IMGPF_EXEC);
2494 	int ptrauth_task_port_count = 0;
2495 
2496 	for (i = 0; i < pacts->pspa_count; i++) {
2497 		act = &pacts->pspa_actions[i];
2498 
2499 		switch (act->port_type) {
2500 		case PSPA_SPECIAL:
2501 		case PSPA_EXCEPTION:
2502 #if CONFIG_AUDIT
2503 		case PSPA_AU_SESSION:
2504 #endif
2505 			break;
2506 		case PSPA_IMP_WATCHPORTS:
2507 			if (++actions->portwatch_count > TASK_MAX_WATCHPORT_COUNT) {
2508 				ret = EINVAL;
2509 				goto done;
2510 			}
2511 			break;
2512 		case PSPA_REGISTERED_PORTS:
2513 			if (++actions->registered_count > TASK_PORT_REGISTER_MAX) {
2514 				ret = EINVAL;
2515 				goto done;
2516 			}
2517 			break;
2518 		case PSPA_PTRAUTH_TASK_PORT:
2519 			if (++ptrauth_task_port_count > 1) {
2520 				ret = EINVAL;
2521 				goto done;
2522 			}
2523 			break;
2524 		default:
2525 			ret = EINVAL;
2526 			goto done;
2527 		}
2528 	}
2529 
2530 	if (actions->portwatch_count) {
2531 		if (in_exec && task_has_watchport_boost) {
2532 			ret = EINVAL;
2533 			goto done;
2534 		}
2535 		actions->portwatch_array = kalloc_type(ipc_port_t,
2536 		    actions->portwatch_count, Z_WAITOK | Z_ZERO);
2537 		if (actions->portwatch_array == NULL) {
2538 			ret = ENOMEM;
2539 			goto done;
2540 		}
2541 	}
2542 
2543 	if (actions->registered_count) {
2544 		actions->registered_array = kalloc_type(ipc_port_t,
2545 		    actions->registered_count, Z_WAITOK | Z_ZERO);
2546 		if (actions->registered_array == NULL) {
2547 			ret = ENOMEM;
2548 			goto done;
2549 		}
2550 	}
2551 
2552 	for (i = 0; i < pacts->pspa_count; i++) {
2553 		act = &pacts->pspa_actions[i];
2554 
2555 		if (MACH_PORT_VALID(act->new_port)) {
2556 			kr = ipc_object_copyin(get_task_ipcspace(current_task()),
2557 			    act->new_port, MACH_MSG_TYPE_COPY_SEND,
2558 			    (ipc_object_t *) &port, 0, NULL, IPC_OBJECT_COPYIN_FLAGS_ALLOW_IMMOVABLE_SEND);
2559 
2560 			if (kr != KERN_SUCCESS) {
2561 				ret = EINVAL;
2562 				goto done;
2563 			}
2564 		} else {
2565 			/* it's NULL or DEAD */
2566 			port = CAST_MACH_NAME_TO_PORT(act->new_port);
2567 		}
2568 
2569 		switch (act->port_type) {
2570 		case PSPA_SPECIAL:
2571 			kr = task_set_special_port(task, act->which, port);
2572 
2573 			if (kr != KERN_SUCCESS) {
2574 				ret = EINVAL;
2575 			}
2576 			break;
2577 
2578 		case PSPA_EXCEPTION:
2579 			kr = task_set_exception_ports(task, act->mask, port,
2580 			    act->behavior, act->flavor);
2581 			if (kr != KERN_SUCCESS) {
2582 				ret = EINVAL;
2583 			}
2584 			break;
2585 #if CONFIG_AUDIT
2586 		case PSPA_AU_SESSION:
2587 			ret = audit_session_spawnjoin(p, port);
2588 			if (ret) {
2589 				/* audit_session_spawnjoin() has already dropped the reference in case of error. */
2590 				goto done;
2591 			}
2592 
2593 			break;
2594 #endif
2595 		case PSPA_IMP_WATCHPORTS:
2596 			if (actions->portwatch_array) {
2597 				/* hold on to this till end of spawn */
2598 				actions->portwatch_array[portwatch_i++] = port;
2599 			} else {
2600 				ipc_port_release_send(port);
2601 			}
2602 			break;
2603 		case PSPA_REGISTERED_PORTS:
2604 			/* hold on to this till end of spawn */
2605 			actions->registered_array[registered_i++] = port;
2606 			break;
2607 
2608 		case PSPA_PTRAUTH_TASK_PORT:
2609 			/* No one uses this, this is no longer supported, just a no-op */
2610 			ipc_port_release_send(port);
2611 			break;
2612 		default:
2613 			ret = EINVAL;
2614 			break;
2615 		}
2616 
2617 		if (ret) {
2618 			/* action failed, so release port resources */
2619 			ipc_port_release_send(port);
2620 			break;
2621 		}
2622 	}
2623 
2624 done:
2625 	if (0 != ret) {
2626 		DTRACE_PROC1(spawn__port__failure, mach_port_name_t, act->new_port);
2627 	}
2628 	return ret;
2629 }
2630 
2631 /*
2632  * exec_handle_file_actions
2633  *
2634  * Description:	Go through the _posix_file_actions_t contents applying the
2635  *		open, close, and dup2 operations to the open file table for
2636  *		the current process.
2637  *
2638  * Parameters:	struct image_params *	Image parameter block
2639  *
2640  * Returns:	0			Success
2641  *		???
2642  *
2643  * Note:	Actions are applied in the order specified, with the credential
2644  *		of the parent process.  This is done to permit the parent
2645  *		process to utilize POSIX_SPAWN_RESETIDS to drop privilege in
2646  *		the child following operations the child may in fact not be
2647  *		normally permitted to perform.
2648  */
2649 static int
exec_handle_file_actions(struct image_params * imgp,short psa_flags)2650 exec_handle_file_actions(struct image_params *imgp, short psa_flags)
2651 {
2652 	int error = 0;
2653 	int action;
2654 	proc_t p = vfs_context_proc(imgp->ip_vfs_context);
2655 	_posix_spawn_file_actions_t px_sfap = imgp->ip_px_sfa;
2656 	int ival[2];            /* dummy retval for system calls) */
2657 #if CONFIG_AUDIT
2658 	struct uthread *uthread = current_uthread();
2659 #endif
2660 
2661 	for (action = 0; action < px_sfap->psfa_act_count; action++) {
2662 		_psfa_action_t *psfa = &px_sfap->psfa_act_acts[action];
2663 
2664 		switch (psfa->psfaa_type) {
2665 		case PSFA_OPEN: {
2666 			/*
2667 			 * Open is different, in that it requires the use of
2668 			 * a path argument, which is normally copied in from
2669 			 * user space; because of this, we have to support an
2670 			 * open from kernel space that passes an address space
2671 			 * context of UIO_SYSSPACE, and casts the address
2672 			 * argument to a user_addr_t.
2673 			 */
2674 			struct vnode_attr *vap;
2675 			struct nameidata *ndp;
2676 			int mode = psfa->psfaa_openargs.psfao_mode;
2677 			int origfd;
2678 			struct {
2679 				struct vnode_attr va;
2680 				struct nameidata nd;
2681 			} *__open_data;
2682 
2683 			__open_data = kalloc_type(typeof(*__open_data), Z_WAITOK | Z_ZERO);
2684 			if (__open_data == NULL) {
2685 				error = ENOMEM;
2686 				break;
2687 			}
2688 
2689 			vap = &__open_data->va;
2690 			ndp = &__open_data->nd;
2691 
2692 			VATTR_INIT(vap);
2693 			/* Mask off all but regular access permissions */
2694 			mode = ((mode & ~p->p_fd.fd_cmask) & ALLPERMS) & ~S_ISTXT;
2695 			VATTR_SET(vap, va_mode, mode & ACCESSPERMS);
2696 
2697 			AUDIT_SUBCALL_ENTER(OPEN, p, uthread);
2698 
2699 			NDINIT(ndp, LOOKUP, OP_OPEN, FOLLOW | AUDITVNPATH1, UIO_SYSSPACE,
2700 			    CAST_USER_ADDR_T(psfa->psfaa_openargs.psfao_path),
2701 			    imgp->ip_vfs_context);
2702 
2703 			error = open1(imgp->ip_vfs_context, ndp,
2704 			    psfa->psfaa_openargs.psfao_oflag,
2705 			    vap, NULL, NULL, &origfd, AUTH_OPEN_NOAUTHFD);
2706 
2707 			kfree_type(typeof(*__open_data), __open_data);
2708 
2709 			AUDIT_SUBCALL_EXIT(uthread, error);
2710 
2711 			/*
2712 			 * If there's an error, or we get the right fd by
2713 			 * accident, then drop out here.  This is easier than
2714 			 * reworking all the open code to preallocate fd
2715 			 * slots, and internally taking one as an argument.
2716 			 */
2717 			if (error || origfd == psfa->psfaa_filedes) {
2718 				break;
2719 			}
2720 
2721 			/*
2722 			 * If we didn't fall out from an error, we ended up
2723 			 * with the wrong fd; so now we've got to try to dup2
2724 			 * it to the right one.
2725 			 */
2726 			AUDIT_SUBCALL_ENTER(DUP2, p, uthread);
2727 			error = dup2(p, origfd, psfa->psfaa_filedes, ival);
2728 			AUDIT_SUBCALL_EXIT(uthread, error);
2729 			if (error) {
2730 				break;
2731 			}
2732 
2733 			/*
2734 			 * Finally, close the original fd.
2735 			 */
2736 			AUDIT_SUBCALL_ENTER(CLOSE, p, uthread);
2737 			error = close_nocancel(p, origfd);
2738 			AUDIT_SUBCALL_EXIT(uthread, error);
2739 		}
2740 		break;
2741 
2742 		case PSFA_DUP2: {
2743 			AUDIT_SUBCALL_ENTER(DUP2, p, uthread);
2744 			error = dup2(p, psfa->psfaa_filedes,
2745 			    psfa->psfaa_dup2args.psfad_newfiledes, ival);
2746 			AUDIT_SUBCALL_EXIT(uthread, error);
2747 		}
2748 		break;
2749 
2750 		case PSFA_FILEPORT_DUP2: {
2751 			ipc_port_t port;
2752 			kern_return_t kr;
2753 			int origfd;
2754 
2755 			if (!MACH_PORT_VALID(psfa->psfaa_fileport)) {
2756 				error = EINVAL;
2757 				break;
2758 			}
2759 
2760 			kr = ipc_object_copyin(get_task_ipcspace(current_task()),
2761 			    psfa->psfaa_fileport, MACH_MSG_TYPE_COPY_SEND,
2762 			    (ipc_object_t *) &port, 0, NULL, IPC_OBJECT_COPYIN_FLAGS_ALLOW_IMMOVABLE_SEND);
2763 
2764 			if (kr != KERN_SUCCESS) {
2765 				error = EINVAL;
2766 				break;
2767 			}
2768 
2769 			error = fileport_makefd(p, port, 0, &origfd);
2770 
2771 			if (IPC_PORT_NULL != port) {
2772 				ipc_port_release_send(port);
2773 			}
2774 
2775 			if (error || origfd == psfa->psfaa_dup2args.psfad_newfiledes) {
2776 				break;
2777 			}
2778 
2779 			AUDIT_SUBCALL_ENTER(DUP2, p, uthread);
2780 			error = dup2(p, origfd,
2781 			    psfa->psfaa_dup2args.psfad_newfiledes, ival);
2782 			AUDIT_SUBCALL_EXIT(uthread, error);
2783 			if (error) {
2784 				break;
2785 			}
2786 
2787 			AUDIT_SUBCALL_ENTER(CLOSE, p, uthread);
2788 			error = close_nocancel(p, origfd);
2789 			AUDIT_SUBCALL_EXIT(uthread, error);
2790 		}
2791 		break;
2792 
2793 		case PSFA_CLOSE: {
2794 			AUDIT_SUBCALL_ENTER(CLOSE, p, uthread);
2795 			error = close_nocancel(p, psfa->psfaa_filedes);
2796 			AUDIT_SUBCALL_EXIT(uthread, error);
2797 		}
2798 		break;
2799 
2800 		case PSFA_INHERIT: {
2801 			struct fileproc *fp;
2802 
2803 			/*
2804 			 * Check to see if the descriptor exists, and
2805 			 * ensure it's -not- marked as close-on-exec.
2806 			 *
2807 			 * Attempting to "inherit" a guarded fd will
2808 			 * result in a error.
2809 			 */
2810 
2811 			proc_fdlock(p);
2812 			if ((fp = fp_get_noref_locked(p, psfa->psfaa_filedes)) == NULL) {
2813 				error = EBADF;
2814 			} else if (fp->fp_guard_attrs) {
2815 				error = fp_guard_exception(p, psfa->psfaa_filedes,
2816 				    fp, kGUARD_EXC_NOCLOEXEC);
2817 			} else {
2818 				fp->fp_flags &= ~FP_CLOEXEC;
2819 				error = 0;
2820 			}
2821 			proc_fdunlock(p);
2822 		}
2823 		break;
2824 
2825 		case PSFA_CHDIR: {
2826 			/*
2827 			 * Chdir is different, in that it requires the use of
2828 			 * a path argument, which is normally copied in from
2829 			 * user space; because of this, we have to support a
2830 			 * chdir from kernel space that passes an address space
2831 			 * context of UIO_SYSSPACE, and casts the address
2832 			 * argument to a user_addr_t.
2833 			 */
2834 			struct nameidata *nd;
2835 			nd = kalloc_type(struct nameidata,
2836 			    Z_WAITOK | Z_ZERO | Z_NOFAIL);
2837 
2838 			AUDIT_SUBCALL_ENTER(CHDIR, p, uthread);
2839 			NDINIT(nd, LOOKUP, OP_CHDIR, FOLLOW | AUDITVNPATH1, UIO_SYSSPACE,
2840 			    CAST_USER_ADDR_T(psfa->psfaa_chdirargs.psfac_path),
2841 			    imgp->ip_vfs_context);
2842 
2843 			error = chdir_internal(p, imgp->ip_vfs_context, nd, 0);
2844 			kfree_type(struct nameidata, nd);
2845 			AUDIT_SUBCALL_EXIT(uthread, error);
2846 		}
2847 		break;
2848 
2849 		case PSFA_FCHDIR: {
2850 			struct fchdir_args fchdira;
2851 
2852 			fchdira.fd = psfa->psfaa_filedes;
2853 
2854 			AUDIT_SUBCALL_ENTER(FCHDIR, p, uthread);
2855 			error = fchdir(p, &fchdira, ival);
2856 			AUDIT_SUBCALL_EXIT(uthread, error);
2857 		}
2858 		break;
2859 
2860 		default:
2861 			error = EINVAL;
2862 			break;
2863 		}
2864 
2865 		/* All file actions failures are considered fatal, per POSIX */
2866 
2867 		if (error) {
2868 			if (PSFA_OPEN == psfa->psfaa_type) {
2869 				DTRACE_PROC1(spawn__open__failure, uintptr_t,
2870 				    psfa->psfaa_openargs.psfao_path);
2871 			} else {
2872 				DTRACE_PROC1(spawn__fd__failure, int, psfa->psfaa_filedes);
2873 			}
2874 			break;
2875 		}
2876 	}
2877 
2878 	if (error != 0 || (psa_flags & POSIX_SPAWN_CLOEXEC_DEFAULT) == 0) {
2879 		return error;
2880 	}
2881 
2882 	/*
2883 	 * If POSIX_SPAWN_CLOEXEC_DEFAULT is set, behave (during
2884 	 * this spawn only) as if "close on exec" is the default
2885 	 * disposition of all pre-existing file descriptors.  In this case,
2886 	 * the list of file descriptors mentioned in the file actions
2887 	 * are the only ones that can be inherited, so mark them now.
2888 	 *
2889 	 * The actual closing part comes later, in fdt_exec().
2890 	 */
2891 	proc_fdlock(p);
2892 	for (action = 0; action < px_sfap->psfa_act_count; action++) {
2893 		_psfa_action_t *psfa = &px_sfap->psfa_act_acts[action];
2894 		int fd = psfa->psfaa_filedes;
2895 
2896 		switch (psfa->psfaa_type) {
2897 		case PSFA_DUP2:
2898 		case PSFA_FILEPORT_DUP2:
2899 			fd = psfa->psfaa_dup2args.psfad_newfiledes;
2900 			OS_FALLTHROUGH;
2901 		case PSFA_OPEN:
2902 		case PSFA_INHERIT:
2903 			*fdflags(p, fd) |= UF_INHERIT;
2904 			break;
2905 
2906 		case PSFA_CLOSE:
2907 		case PSFA_CHDIR:
2908 		case PSFA_FCHDIR:
2909 			/*
2910 			 * Although PSFA_FCHDIR does have a file descriptor, it is not
2911 			 * *creating* one, thus we do not automatically mark it for
2912 			 * inheritance under POSIX_SPAWN_CLOEXEC_DEFAULT. A client that
2913 			 * wishes it to be inherited should use the PSFA_INHERIT action
2914 			 * explicitly.
2915 			 */
2916 			break;
2917 		}
2918 	}
2919 	proc_fdunlock(p);
2920 
2921 	return 0;
2922 }
2923 
2924 #if CONFIG_MACF
2925 /*
2926  * Check that the extension's data is within the bounds of the
2927  * allocation storing all extensions' data
2928  */
2929 static inline errno_t
exec_spawnattr_validate_policyext_data(const struct ip_px_smpx_s * px_s,const _ps_mac_policy_extension_t * ext)2930 exec_spawnattr_validate_policyext_data(const struct ip_px_smpx_s *px_s,
2931     const _ps_mac_policy_extension_t *ext)
2932 {
2933 	uint64_t dataend;
2934 
2935 	if (__improbable(os_add_overflow(ext->dataoff, ext->datalen, &dataend))) {
2936 		return EOVERFLOW;
2937 	}
2938 	if (__improbable(dataend > px_s->datalen)) {
2939 		return EINVAL;
2940 	}
2941 
2942 	return 0;
2943 }
2944 
2945 /*
2946  * exec_spawnattr_getmacpolicyinfo
2947  */
2948 void *
exec_spawnattr_getmacpolicyinfo(const void * macextensions,const char * policyname,size_t * lenp)2949 exec_spawnattr_getmacpolicyinfo(const void *macextensions, const char *policyname, size_t *lenp)
2950 {
2951 	const struct ip_px_smpx_s *px_s = macextensions;
2952 	const struct _posix_spawn_mac_policy_extensions *psmx = NULL;
2953 	int i;
2954 
2955 	if (px_s == NULL) {
2956 		return NULL;
2957 	}
2958 
2959 	psmx = px_s->array;
2960 	if (psmx == NULL) {
2961 		return NULL;
2962 	}
2963 
2964 	for (i = 0; i < psmx->psmx_count; i++) {
2965 		const _ps_mac_policy_extension_t *extension = &psmx->psmx_extensions[i];
2966 		if (strncmp(extension->policyname, policyname, sizeof(extension->policyname)) == 0) {
2967 			if (__improbable(exec_spawnattr_validate_policyext_data(px_s, extension))) {
2968 				panic("invalid mac policy extension data");
2969 			}
2970 			if (lenp != NULL) {
2971 				*lenp = (size_t)extension->datalen;
2972 			}
2973 			return (void *)((uintptr_t)px_s->data + extension->dataoff);
2974 		}
2975 	}
2976 
2977 	if (lenp != NULL) {
2978 		*lenp = 0;
2979 	}
2980 	return NULL;
2981 }
2982 
2983 static int
spawn_copyin_macpolicyinfo(const struct user__posix_spawn_args_desc * px_args,struct ip_px_smpx_s * pxsp)2984 spawn_copyin_macpolicyinfo(const struct user__posix_spawn_args_desc *px_args,
2985     struct ip_px_smpx_s *pxsp)
2986 {
2987 	_posix_spawn_mac_policy_extensions_t psmx = NULL;
2988 	uint8_t *data = NULL;
2989 	uint64_t datalen = 0;
2990 	uint64_t dataoff = 0;
2991 	int error = 0;
2992 
2993 	bzero(pxsp, sizeof(*pxsp));
2994 
2995 	if (px_args->mac_extensions_size < PS_MAC_EXTENSIONS_SIZE(1) ||
2996 	    px_args->mac_extensions_size > PAGE_SIZE) {
2997 		error = EINVAL;
2998 		goto bad;
2999 	}
3000 
3001 	psmx = kalloc_data(px_args->mac_extensions_size, Z_WAITOK);
3002 	if (psmx == NULL) {
3003 		error = ENOMEM;
3004 		goto bad;
3005 	}
3006 
3007 	error = copyin(px_args->mac_extensions, psmx, px_args->mac_extensions_size);
3008 	if (error) {
3009 		goto bad;
3010 	}
3011 
3012 	size_t extsize = PS_MAC_EXTENSIONS_SIZE(psmx->psmx_count);
3013 	if (extsize == 0 || extsize > px_args->mac_extensions_size) {
3014 		error = EINVAL;
3015 		goto bad;
3016 	}
3017 
3018 	for (int i = 0; i < psmx->psmx_count; i++) {
3019 		_ps_mac_policy_extension_t *extension = &psmx->psmx_extensions[i];
3020 		if (extension->datalen == 0 || extension->datalen > PAGE_SIZE) {
3021 			error = EINVAL;
3022 			goto bad;
3023 		}
3024 		if (__improbable(os_add_overflow(datalen, extension->datalen, &datalen))) {
3025 			error = ENOMEM;
3026 			goto bad;
3027 		}
3028 	}
3029 
3030 	data = kalloc_data((vm_size_t)datalen, Z_WAITOK);
3031 	if (data == NULL) {
3032 		error = ENOMEM;
3033 		goto bad;
3034 	}
3035 
3036 	for (int i = 0; i < psmx->psmx_count; i++) {
3037 		_ps_mac_policy_extension_t *extension = &psmx->psmx_extensions[i];
3038 
3039 #if !__LP64__
3040 		if (extension->data > UINT32_MAX) {
3041 			goto bad;
3042 		}
3043 #endif
3044 		error = copyin((user_addr_t)extension->data, &data[dataoff], (size_t)extension->datalen);
3045 		if (error) {
3046 			error = ENOMEM;
3047 			goto bad;
3048 		}
3049 		extension->dataoff = dataoff;
3050 		dataoff += extension->datalen;
3051 	}
3052 
3053 	pxsp->array = psmx;
3054 	pxsp->data = data;
3055 	pxsp->datalen = datalen;
3056 	return 0;
3057 
3058 bad:
3059 	kfree_data(psmx, px_args->mac_extensions_size);
3060 	kfree_data(data, (vm_size_t)datalen);
3061 	return error;
3062 }
3063 #endif /* CONFIG_MACF */
3064 
3065 #if CONFIG_COALITIONS
3066 static inline void
spawn_coalitions_release_all(coalition_t coal[COALITION_NUM_TYPES])3067 spawn_coalitions_release_all(coalition_t coal[COALITION_NUM_TYPES])
3068 {
3069 	for (int c = 0; c < COALITION_NUM_TYPES; c++) {
3070 		if (coal[c]) {
3071 			coalition_remove_active(coal[c]);
3072 			coalition_release(coal[c]);
3073 		}
3074 	}
3075 }
3076 #endif
3077 
3078 #if CONFIG_PERSONAS
3079 static int
spawn_validate_persona(struct _posix_spawn_persona_info * px_persona)3080 spawn_validate_persona(struct _posix_spawn_persona_info *px_persona)
3081 {
3082 	int error = 0;
3083 	struct persona *persona = NULL;
3084 
3085 	if (!IOCurrentTaskHasEntitlement( PERSONA_MGMT_ENTITLEMENT)) {
3086 		return EPERM;
3087 	}
3088 
3089 	if (px_persona->pspi_flags & POSIX_SPAWN_PERSONA_GROUPS) {
3090 		if (px_persona->pspi_ngroups > NGROUPS_MAX) {
3091 			return EINVAL;
3092 		}
3093 	}
3094 
3095 	persona = persona_lookup(px_persona->pspi_id);
3096 	if (!persona) {
3097 		error = ESRCH;
3098 		goto out;
3099 	}
3100 
3101 out:
3102 	if (persona) {
3103 		persona_put(persona);
3104 	}
3105 
3106 	return error;
3107 }
3108 
3109 static bool
kauth_cred_model_setpersona(kauth_cred_t model,struct _posix_spawn_persona_info * px_persona)3110 kauth_cred_model_setpersona(
3111 	kauth_cred_t            model,
3112 	struct _posix_spawn_persona_info *px_persona)
3113 {
3114 	bool updated = false;
3115 
3116 	if (px_persona->pspi_flags & POSIX_SPAWN_PERSONA_UID) {
3117 		updated |= kauth_cred_model_setresuid(model,
3118 		    px_persona->pspi_uid,
3119 		    px_persona->pspi_uid,
3120 		    px_persona->pspi_uid,
3121 		    KAUTH_UID_NONE);
3122 	}
3123 
3124 	if (px_persona->pspi_flags & POSIX_SPAWN_PERSONA_GID) {
3125 		updated |= kauth_cred_model_setresgid(model,
3126 		    px_persona->pspi_gid,
3127 		    px_persona->pspi_gid,
3128 		    px_persona->pspi_gid);
3129 	}
3130 
3131 	if (px_persona->pspi_flags & POSIX_SPAWN_PERSONA_GROUPS) {
3132 		updated |= kauth_cred_model_setgroups(model,
3133 		    px_persona->pspi_groups,
3134 		    px_persona->pspi_ngroups,
3135 		    px_persona->pspi_gmuid);
3136 	}
3137 
3138 	return updated;
3139 }
3140 
3141 static int
spawn_persona_adopt(proc_t p,struct _posix_spawn_persona_info * px_persona)3142 spawn_persona_adopt(proc_t p, struct _posix_spawn_persona_info *px_persona)
3143 {
3144 	struct persona *persona = NULL;
3145 
3146 	/*
3147 	 * we want to spawn into the given persona, but we want to override
3148 	 * the kauth with a different UID/GID combo
3149 	 */
3150 	persona = persona_lookup(px_persona->pspi_id);
3151 	if (!persona) {
3152 		return ESRCH;
3153 	}
3154 
3155 	return persona_proc_adopt(p, persona,
3156 	           ^bool (kauth_cred_t parent __unused, kauth_cred_t model) {
3157 		return kauth_cred_model_setpersona(model, px_persona);
3158 	});
3159 }
3160 #endif
3161 
3162 #if __arm64__
3163 #if DEVELOPMENT || DEBUG
3164 TUNABLE(int, legacy_footprint_entitlement_mode, "legacy_footprint_entitlement_mode",
3165     LEGACY_FOOTPRINT_ENTITLEMENT_IGNORE);
3166 
3167 __startup_func
3168 static void
legacy_footprint_entitlement_mode_init(void)3169 legacy_footprint_entitlement_mode_init(void)
3170 {
3171 	/*
3172 	 * legacy_footprint_entitlement_mode specifies the behavior we want associated
3173 	 * with the entitlement. The supported modes are:
3174 	 *
3175 	 * LEGACY_FOOTPRINT_ENTITLEMENT_IGNORE:
3176 	 *	Indicates that we want every process to have the memory accounting
3177 	 *	that is available in iOS 12.0 and beyond.
3178 	 *
3179 	 * LEGACY_FOOTPRINT_ENTITLEMENT_IOS11_ACCT:
3180 	 *	Indicates that for every process that has the 'legacy footprint entitlement',
3181 	 *      we want to give it the old iOS 11.0 accounting behavior which accounted some
3182 	 *	of the process's memory to the kernel.
3183 	 *
3184 	 * LEGACY_FOOTPRINT_ENTITLEMENT_LIMIT_INCREASE:
3185 	 *      Indicates that for every process that has the 'legacy footprint entitlement',
3186 	 *	we want it to have a higher memory limit which will help them acclimate to the
3187 	 *	iOS 12.0 (& beyond) accounting behavior that does the right accounting.
3188 	 *      The bonus added to the system-wide task limit to calculate this higher memory limit
3189 	 *      is available in legacy_footprint_bonus_mb.
3190 	 */
3191 
3192 	if (legacy_footprint_entitlement_mode < LEGACY_FOOTPRINT_ENTITLEMENT_IGNORE ||
3193 	    legacy_footprint_entitlement_mode > LEGACY_FOOTPRINT_ENTITLEMENT_LIMIT_INCREASE) {
3194 		legacy_footprint_entitlement_mode = LEGACY_FOOTPRINT_ENTITLEMENT_LIMIT_INCREASE;
3195 	}
3196 }
3197 STARTUP(TUNABLES, STARTUP_RANK_MIDDLE, legacy_footprint_entitlement_mode_init);
3198 #else
3199 const int legacy_footprint_entitlement_mode = LEGACY_FOOTPRINT_ENTITLEMENT_IGNORE;
3200 #endif
3201 
3202 static inline void
proc_legacy_footprint_entitled(proc_t p,task_t task)3203 proc_legacy_footprint_entitled(proc_t p, task_t task)
3204 {
3205 #pragma unused(p)
3206 	boolean_t legacy_footprint_entitled;
3207 
3208 	switch (legacy_footprint_entitlement_mode) {
3209 	case LEGACY_FOOTPRINT_ENTITLEMENT_IGNORE:
3210 		/* the entitlement is ignored */
3211 		break;
3212 	case LEGACY_FOOTPRINT_ENTITLEMENT_IOS11_ACCT:
3213 		/* the entitlement grants iOS11 legacy accounting */
3214 		legacy_footprint_entitled = memorystatus_task_has_legacy_footprint_entitlement(proc_task(p));
3215 		if (legacy_footprint_entitled) {
3216 			task_set_legacy_footprint(task);
3217 		}
3218 		break;
3219 	case LEGACY_FOOTPRINT_ENTITLEMENT_LIMIT_INCREASE:
3220 		/* the entitlement grants a footprint limit increase */
3221 		legacy_footprint_entitled = memorystatus_task_has_legacy_footprint_entitlement(proc_task(p));
3222 		if (legacy_footprint_entitled) {
3223 			task_set_extra_footprint_limit(task);
3224 		}
3225 		break;
3226 	default:
3227 		break;
3228 	}
3229 }
3230 
3231 static inline void
proc_ios13extended_footprint_entitled(proc_t p,task_t task)3232 proc_ios13extended_footprint_entitled(proc_t p, task_t task)
3233 {
3234 #pragma unused(p)
3235 	boolean_t ios13extended_footprint_entitled;
3236 
3237 	/* the entitlement grants a footprint limit increase */
3238 	ios13extended_footprint_entitled = memorystatus_task_has_ios13extended_footprint_limit(proc_task(p));
3239 	if (ios13extended_footprint_entitled) {
3240 		task_set_ios13extended_footprint_limit(task);
3241 	}
3242 }
3243 
3244 static inline void
proc_increased_memory_limit_entitled(proc_t p,task_t task)3245 proc_increased_memory_limit_entitled(proc_t p, task_t task)
3246 {
3247 	bool entitled = memorystatus_task_has_increased_memory_limit_entitlement(task);
3248 
3249 	if (entitled) {
3250 		memorystatus_act_on_entitled_task_limit(p);
3251 	}
3252 }
3253 
3254 /*
3255  * Check for any of the various entitlements that permit a higher
3256  * task footprint limit or alternate accounting and apply them.
3257  */
3258 static inline void
proc_footprint_entitlement_hacks(proc_t p,task_t task)3259 proc_footprint_entitlement_hacks(proc_t p, task_t task)
3260 {
3261 	proc_legacy_footprint_entitled(p, task);
3262 	proc_ios13extended_footprint_entitled(p, task);
3263 	proc_increased_memory_limit_entitled(p, task);
3264 }
3265 #endif /* __arm64__ */
3266 
3267 /*
3268  * Processes with certain entitlements are granted a jumbo-size VM map.
3269  */
3270 static inline void
proc_apply_jit_and_vm_policies(struct image_params * imgp,proc_t p,task_t task)3271 proc_apply_jit_and_vm_policies(struct image_params *imgp, proc_t p, task_t task)
3272 {
3273 #if CONFIG_MACF
3274 	bool jit_entitled = false;
3275 #endif /* CONFIG_MACF */
3276 	bool needs_jumbo_va = false;
3277 	struct _posix_spawnattr *psa = imgp->ip_px_sa;
3278 
3279 #if CONFIG_MACF
3280 	jit_entitled = (mac_proc_check_map_anon(p, 0, 0, 0, MAP_JIT, NULL) == 0);
3281 	needs_jumbo_va = jit_entitled || IOTaskHasEntitlement(task,
3282 	    "com.apple.developer.kernel.extended-virtual-addressing") ||
3283 	    memorystatus_task_has_increased_memory_limit_entitlement(task);
3284 #else
3285 #pragma unused(p)
3286 #endif /* CONFIG_MACF */
3287 
3288 	if (needs_jumbo_va) {
3289 		vm_map_set_jumbo(get_task_map(task));
3290 	}
3291 
3292 	if (psa && psa->psa_max_addr) {
3293 		vm_map_set_max_addr(get_task_map(task), psa->psa_max_addr);
3294 	}
3295 
3296 #if CONFIG_MAP_RANGES
3297 	if (task_get_platform_binary(task) && !proc_is_simulated(p)) {
3298 		/*
3299 		 * This must be done last as it needs to observe
3300 		 * any kind of VA space growth that was requested
3301 		 */
3302 		vm_map_range_configure(get_task_map(task));
3303 	}
3304 #endif /* CONFIG_MAP_RANGES */
3305 
3306 #if CONFIG_MACF
3307 	if (jit_entitled) {
3308 		vm_map_set_jit_entitled(get_task_map(task));
3309 
3310 	}
3311 #endif /* CONFIG_MACF */
3312 
3313 	if (task_get_platform_binary(task)) {
3314 		/*
3315 		 * Pre-emptively disable TPRO remapping for
3316 		 * platform binaries
3317 		 */
3318 		vm_map_set_tpro_enforcement(get_task_map(task));
3319 	}
3320 }
3321 
3322 static int
spawn_posix_cred_adopt(proc_t p,struct _posix_spawn_posix_cred_info * px_pcred_info)3323 spawn_posix_cred_adopt(proc_t p,
3324     struct _posix_spawn_posix_cred_info *px_pcred_info)
3325 {
3326 	int error = 0;
3327 
3328 	if (px_pcred_info->pspci_flags & POSIX_SPAWN_POSIX_CRED_GID) {
3329 		struct setgid_args args = {
3330 			.gid = px_pcred_info->pspci_gid,
3331 		};
3332 		error = setgid(p, &args, NULL);
3333 		if (error) {
3334 			return error;
3335 		}
3336 	}
3337 
3338 	if (px_pcred_info->pspci_flags & POSIX_SPAWN_POSIX_CRED_GROUPS) {
3339 		error = setgroups_internal(p,
3340 		    px_pcred_info->pspci_ngroups,
3341 		    px_pcred_info->pspci_groups,
3342 		    px_pcred_info->pspci_gmuid);
3343 		if (error) {
3344 			return error;
3345 		}
3346 	}
3347 
3348 	if (px_pcred_info->pspci_flags & POSIX_SPAWN_POSIX_CRED_UID) {
3349 		struct setuid_args args = {
3350 			.uid = px_pcred_info->pspci_uid,
3351 		};
3352 		error = setuid(p, &args, NULL);
3353 		if (error) {
3354 			return error;
3355 		}
3356 	}
3357 	return 0;
3358 }
3359 
3360 /*
3361  * posix_spawn
3362  *
3363  * Parameters:	uap->pid		Pointer to pid return area
3364  *		uap->fname		File name to exec
3365  *		uap->argp		Argument list
3366  *		uap->envp		Environment list
3367  *
3368  * Returns:	0			Success
3369  *		EINVAL			Invalid argument
3370  *		ENOTSUP			Not supported
3371  *		ENOEXEC			Executable file format error
3372  *	exec_activate_image:EINVAL	Invalid argument
3373  *	exec_activate_image:EACCES	Permission denied
3374  *	exec_activate_image:EINTR	Interrupted function
3375  *	exec_activate_image:ENOMEM	Not enough space
3376  *	exec_activate_image:EFAULT	Bad address
3377  *	exec_activate_image:ENAMETOOLONG	Filename too long
3378  *	exec_activate_image:ENOEXEC	Executable file format error
3379  *	exec_activate_image:ETXTBSY	Text file busy [misuse of error code]
3380  *	exec_activate_image:EAUTH	Image decryption failed
3381  *	exec_activate_image:EBADEXEC	The executable is corrupt/unknown
3382  *	exec_activate_image:???
3383  *	mac_execve_enter:???
3384  *
3385  * TODO:	Expect to need __mac_posix_spawn() at some point...
3386  *		Handle posix_spawnattr_t
3387  *		Handle posix_spawn_file_actions_t
3388  */
3389 int
posix_spawn(proc_t ap,struct posix_spawn_args * uap,int32_t * retval)3390 posix_spawn(proc_t ap, struct posix_spawn_args *uap, int32_t *retval)
3391 {
3392 	proc_t p = ap;
3393 	user_addr_t pid = uap->pid;
3394 	int ival[2];            /* dummy retval for setpgid() */
3395 	char *subsystem_root_path = NULL;
3396 	struct image_params *imgp = NULL;
3397 	struct vnode_attr *vap = NULL;
3398 	struct vnode_attr *origvap = NULL;
3399 	struct uthread  *uthread = 0;   /* compiler complains if not set to 0*/
3400 	int error, sig;
3401 	int is_64 = IS_64BIT_PROCESS(p);
3402 	struct vfs_context context;
3403 	struct user__posix_spawn_args_desc px_args = {};
3404 	struct _posix_spawnattr px_sa = {};
3405 	_posix_spawn_file_actions_t px_sfap = NULL;
3406 	_posix_spawn_port_actions_t px_spap = NULL;
3407 	struct __kern_sigaction vec;
3408 	boolean_t spawn_no_exec = FALSE;
3409 	boolean_t proc_transit_set = TRUE;
3410 	boolean_t proc_signal_set = TRUE;
3411 	boolean_t exec_done = FALSE;
3412 	os_reason_t exec_failure_reason = NULL;
3413 
3414 	struct exec_port_actions port_actions = { };
3415 	vm_size_t px_sa_offset = offsetof(struct _posix_spawnattr, psa_ports);
3416 	task_t old_task = current_task();
3417 	task_t new_task = NULL;
3418 	boolean_t should_release_proc_ref = FALSE;
3419 	void *inherit = NULL;
3420 	uint8_t crash_behavior = 0;
3421 	uint64_t crash_behavior_deadline = 0;
3422 #if CONFIG_PERSONAS
3423 	struct _posix_spawn_persona_info *px_persona = NULL;
3424 #endif
3425 	struct _posix_spawn_posix_cred_info *px_pcred_info = NULL;
3426 	struct {
3427 		struct image_params imgp;
3428 		struct vnode_attr va;
3429 		struct vnode_attr origva;
3430 	} *__spawn_data;
3431 
3432 	/*
3433 	 * Allocate a big chunk for locals instead of using stack since these
3434 	 * structures are pretty big.
3435 	 */
3436 	__spawn_data = kalloc_type(typeof(*__spawn_data), Z_WAITOK | Z_ZERO);
3437 	if (__spawn_data == NULL) {
3438 		error = ENOMEM;
3439 		goto bad;
3440 	}
3441 	imgp = &__spawn_data->imgp;
3442 	vap = &__spawn_data->va;
3443 	origvap = &__spawn_data->origva;
3444 
3445 	/* Initialize the common data in the image_params structure */
3446 	imgp->ip_user_fname = uap->path;
3447 	imgp->ip_user_argv = uap->argv;
3448 	imgp->ip_user_envv = uap->envp;
3449 	imgp->ip_vattr = vap;
3450 	imgp->ip_origvattr = origvap;
3451 	imgp->ip_vfs_context = &context;
3452 	imgp->ip_flags = (is_64 ? IMGPF_WAS_64BIT_ADDR : IMGPF_NONE);
3453 	imgp->ip_seg = (is_64 ? UIO_USERSPACE64 : UIO_USERSPACE32);
3454 	imgp->ip_mac_return = 0;
3455 	imgp->ip_px_persona = NULL;
3456 	imgp->ip_px_pcred_info = NULL;
3457 	imgp->ip_cs_error = OS_REASON_NULL;
3458 	imgp->ip_simulator_binary = IMGPF_SB_DEFAULT;
3459 	imgp->ip_subsystem_root_path = NULL;
3460 	imgp->ip_inherited_shared_region_id = NULL;
3461 	imgp->ip_inherited_jop_pid = 0;
3462 	uthread_set_exec_data(current_uthread(), imgp);
3463 
3464 	if (uap->adesc != USER_ADDR_NULL) {
3465 		if (is_64) {
3466 			error = copyin(uap->adesc, &px_args, sizeof(px_args));
3467 		} else {
3468 			struct user32__posix_spawn_args_desc px_args32;
3469 
3470 			error = copyin(uap->adesc, &px_args32, sizeof(px_args32));
3471 
3472 			/*
3473 			 * Convert arguments descriptor from external 32 bit
3474 			 * representation to internal 64 bit representation
3475 			 */
3476 			px_args.attr_size = px_args32.attr_size;
3477 			px_args.attrp = CAST_USER_ADDR_T(px_args32.attrp);
3478 			px_args.file_actions_size = px_args32.file_actions_size;
3479 			px_args.file_actions = CAST_USER_ADDR_T(px_args32.file_actions);
3480 			px_args.port_actions_size = px_args32.port_actions_size;
3481 			px_args.port_actions = CAST_USER_ADDR_T(px_args32.port_actions);
3482 			px_args.mac_extensions_size = px_args32.mac_extensions_size;
3483 			px_args.mac_extensions = CAST_USER_ADDR_T(px_args32.mac_extensions);
3484 			px_args.coal_info_size = px_args32.coal_info_size;
3485 			px_args.coal_info = CAST_USER_ADDR_T(px_args32.coal_info);
3486 			px_args.persona_info_size = px_args32.persona_info_size;
3487 			px_args.persona_info = CAST_USER_ADDR_T(px_args32.persona_info);
3488 			px_args.posix_cred_info_size = px_args32.posix_cred_info_size;
3489 			px_args.posix_cred_info = CAST_USER_ADDR_T(px_args32.posix_cred_info);
3490 			px_args.subsystem_root_path_size = px_args32.subsystem_root_path_size;
3491 			px_args.subsystem_root_path = CAST_USER_ADDR_T(px_args32.subsystem_root_path);
3492 			px_args.conclave_id_size = px_args32.conclave_id_size;
3493 			px_args.conclave_id = CAST_USER_ADDR_T(px_args32.conclave_id);
3494 		}
3495 		if (error) {
3496 			goto bad;
3497 		}
3498 
3499 		if (px_args.attr_size != 0) {
3500 			/*
3501 			 * We are not copying the port_actions pointer,
3502 			 * because we already have it from px_args.
3503 			 * This is a bit fragile: <rdar://problem/16427422>
3504 			 */
3505 
3506 			if ((error = copyin(px_args.attrp, &px_sa, px_sa_offset)) != 0) {
3507 				goto bad;
3508 			}
3509 
3510 			imgp->ip_px_sa = &px_sa;
3511 		}
3512 		if (px_args.file_actions_size != 0) {
3513 			/* Limit file_actions to allowed number of open files */
3514 			size_t maxfa_size = PSF_ACTIONS_SIZE(proc_limitgetcur_nofile(p));
3515 
3516 			if (px_args.file_actions_size < PSF_ACTIONS_SIZE(1) ||
3517 			    maxfa_size == 0 || px_args.file_actions_size > maxfa_size) {
3518 				error = EINVAL;
3519 				goto bad;
3520 			}
3521 
3522 			px_sfap = kalloc_data(px_args.file_actions_size, Z_WAITOK);
3523 			if (px_sfap == NULL) {
3524 				error = ENOMEM;
3525 				goto bad;
3526 			}
3527 			imgp->ip_px_sfa = px_sfap;
3528 
3529 			if ((error = copyin(px_args.file_actions, px_sfap,
3530 			    px_args.file_actions_size)) != 0) {
3531 				goto bad;
3532 			}
3533 
3534 			/* Verify that the action count matches the struct size */
3535 			size_t psfsize = PSF_ACTIONS_SIZE(px_sfap->psfa_act_count);
3536 			if (psfsize == 0 || psfsize != px_args.file_actions_size) {
3537 				error = EINVAL;
3538 				goto bad;
3539 			}
3540 		}
3541 		if (px_args.port_actions_size != 0) {
3542 			/* Limit port_actions to one page of data */
3543 			if (px_args.port_actions_size < PS_PORT_ACTIONS_SIZE(1) ||
3544 			    px_args.port_actions_size > PAGE_SIZE) {
3545 				error = EINVAL;
3546 				goto bad;
3547 			}
3548 
3549 			px_spap = kalloc_data(px_args.port_actions_size, Z_WAITOK);
3550 			if (px_spap == NULL) {
3551 				error = ENOMEM;
3552 				goto bad;
3553 			}
3554 			imgp->ip_px_spa = px_spap;
3555 
3556 			if ((error = copyin(px_args.port_actions, px_spap,
3557 			    px_args.port_actions_size)) != 0) {
3558 				goto bad;
3559 			}
3560 
3561 			/* Verify that the action count matches the struct size */
3562 			size_t pasize = PS_PORT_ACTIONS_SIZE(px_spap->pspa_count);
3563 			if (pasize == 0 || pasize != px_args.port_actions_size) {
3564 				error = EINVAL;
3565 				goto bad;
3566 			}
3567 		}
3568 #if CONFIG_PERSONAS
3569 		/* copy in the persona info */
3570 		if (px_args.persona_info_size != 0 && px_args.persona_info != 0) {
3571 			/* for now, we need the exact same struct in user space */
3572 			if (px_args.persona_info_size != sizeof(*px_persona)) {
3573 				error = ERANGE;
3574 				goto bad;
3575 			}
3576 
3577 			px_persona = kalloc_data(px_args.persona_info_size, Z_WAITOK);
3578 			if (px_persona == NULL) {
3579 				error = ENOMEM;
3580 				goto bad;
3581 			}
3582 			imgp->ip_px_persona = px_persona;
3583 
3584 			if ((error = copyin(px_args.persona_info, px_persona,
3585 			    px_args.persona_info_size)) != 0) {
3586 				goto bad;
3587 			}
3588 			if ((error = spawn_validate_persona(px_persona)) != 0) {
3589 				goto bad;
3590 			}
3591 		}
3592 #endif
3593 		/* copy in the posix cred info */
3594 		if (px_args.posix_cred_info_size != 0 && px_args.posix_cred_info != 0) {
3595 			/* for now, we need the exact same struct in user space */
3596 			if (px_args.posix_cred_info_size != sizeof(*px_pcred_info)) {
3597 				error = ERANGE;
3598 				goto bad;
3599 			}
3600 
3601 			if (!kauth_cred_issuser(kauth_cred_get())) {
3602 				error = EPERM;
3603 				goto bad;
3604 			}
3605 
3606 			px_pcred_info = kalloc_data(px_args.posix_cred_info_size, Z_WAITOK);
3607 			if (px_pcred_info == NULL) {
3608 				error = ENOMEM;
3609 				goto bad;
3610 			}
3611 			imgp->ip_px_pcred_info = px_pcred_info;
3612 
3613 			if ((error = copyin(px_args.posix_cred_info, px_pcred_info,
3614 			    px_args.posix_cred_info_size)) != 0) {
3615 				goto bad;
3616 			}
3617 
3618 			if (px_pcred_info->pspci_flags & POSIX_SPAWN_POSIX_CRED_GROUPS) {
3619 				if (px_pcred_info->pspci_ngroups > NGROUPS_MAX) {
3620 					error = EINVAL;
3621 					goto bad;
3622 				}
3623 			}
3624 		}
3625 #if CONFIG_MACF
3626 		if (px_args.mac_extensions_size != 0) {
3627 			if ((error = spawn_copyin_macpolicyinfo(&px_args, (struct ip_px_smpx_s *)&imgp->ip_px_smpx)) != 0) {
3628 				goto bad;
3629 			}
3630 		}
3631 #endif /* CONFIG_MACF */
3632 		if ((px_args.subsystem_root_path_size > 0) && (px_args.subsystem_root_path_size <= MAXPATHLEN)) {
3633 			/*
3634 			 * If a valid-looking subsystem root has been
3635 			 * specified...
3636 			 */
3637 			if (IOTaskHasEntitlement(old_task, SPAWN_SUBSYSTEM_ROOT_ENTITLEMENT)) {
3638 				/*
3639 				 * ...AND the parent has the entitlement, copy
3640 				 * the subsystem root path in.
3641 				 */
3642 				subsystem_root_path = zalloc_flags(ZV_NAMEI,
3643 				    Z_WAITOK | Z_ZERO | Z_NOFAIL);
3644 
3645 				if ((error = copyin(px_args.subsystem_root_path, subsystem_root_path, px_args.subsystem_root_path_size))) {
3646 					goto bad;
3647 				}
3648 
3649 				/* Paranoia */
3650 				subsystem_root_path[px_args.subsystem_root_path_size - 1] = 0;
3651 			}
3652 		}
3653 	}
3654 
3655 	if (IOTaskHasEntitlement(old_task, SPAWN_SET_PANIC_CRASH_BEHAVIOR)) {
3656 		/* Truncate to uint8_t since we only support 2 flags for now */
3657 		crash_behavior = (uint8_t)px_sa.psa_crash_behavior;
3658 		crash_behavior_deadline = px_sa.psa_crash_behavior_deadline;
3659 	}
3660 
3661 	/* set uthread to parent */
3662 	uthread = current_uthread();
3663 
3664 	/*
3665 	 * <rdar://6640530>; this does not result in a behaviour change
3666 	 * relative to Leopard, so there should not be any existing code
3667 	 * which depends on it.
3668 	 */
3669 
3670 	if (imgp->ip_px_sa != NULL) {
3671 		struct _posix_spawnattr *psa = (struct _posix_spawnattr *) imgp->ip_px_sa;
3672 		if ((psa->psa_options & PSA_OPTION_PLUGIN_HOST_DISABLE_A_KEYS) == PSA_OPTION_PLUGIN_HOST_DISABLE_A_KEYS) {
3673 			imgp->ip_flags |= IMGPF_PLUGIN_HOST_DISABLE_A_KEYS;
3674 		}
3675 #if (DEVELOPMENT || DEBUG)
3676 		if ((psa->psa_options & PSA_OPTION_ALT_ROSETTA) == PSA_OPTION_ALT_ROSETTA) {
3677 			imgp->ip_flags |= (IMGPF_ROSETTA | IMGPF_ALT_ROSETTA);
3678 		}
3679 #endif
3680 
3681 		if ((error = exec_validate_spawnattr_policy(psa->psa_apptype)) != 0) {
3682 			goto bad;
3683 		}
3684 	}
3685 
3686 	/*
3687 	 * If we don't have the extension flag that turns "posix_spawn()"
3688 	 * into "execve() with options", then we will be creating a new
3689 	 * process which does not inherit memory from the parent process,
3690 	 * which is one of the most expensive things about using fork()
3691 	 * and execve().
3692 	 */
3693 	if (imgp->ip_px_sa == NULL || !(px_sa.psa_flags & POSIX_SPAWN_SETEXEC)) {
3694 		/* Set the new task's coalition, if it is requested.  */
3695 		coalition_t coal[COALITION_NUM_TYPES] = { COALITION_NULL };
3696 #if CONFIG_COALITIONS
3697 		int i, ncoals;
3698 		kern_return_t kr = KERN_SUCCESS;
3699 		struct _posix_spawn_coalition_info coal_info;
3700 		int coal_role[COALITION_NUM_TYPES];
3701 
3702 		if (imgp->ip_px_sa == NULL || !px_args.coal_info) {
3703 			goto do_fork1;
3704 		}
3705 
3706 		memset(&coal_info, 0, sizeof(coal_info));
3707 
3708 		if (px_args.coal_info_size > sizeof(coal_info)) {
3709 			px_args.coal_info_size = sizeof(coal_info);
3710 		}
3711 		error = copyin(px_args.coal_info,
3712 		    &coal_info, px_args.coal_info_size);
3713 		if (error != 0) {
3714 			goto bad;
3715 		}
3716 
3717 		ncoals = 0;
3718 		for (i = 0; i < COALITION_NUM_TYPES; i++) {
3719 			uint64_t cid = coal_info.psci_info[i].psci_id;
3720 			if (cid != 0) {
3721 				/*
3722 				 * don't allow tasks which are not in a
3723 				 * privileged coalition to spawn processes
3724 				 * into coalitions other than their own
3725 				 */
3726 				if (!task_is_in_privileged_coalition(proc_task(p), i) &&
3727 				    !IOTaskHasEntitlement(proc_task(p), COALITION_SPAWN_ENTITLEMENT)) {
3728 					coal_dbg("ERROR: %d not in privilegd "
3729 					    "coalition of type %d",
3730 					    proc_getpid(p), i);
3731 					spawn_coalitions_release_all(coal);
3732 					error = EPERM;
3733 					goto bad;
3734 				}
3735 
3736 				coal_dbg("searching for coalition id:%llu", cid);
3737 				/*
3738 				 * take a reference and activation on the
3739 				 * coalition to guard against free-while-spawn
3740 				 * races
3741 				 */
3742 				coal[i] = coalition_find_and_activate_by_id(cid);
3743 				if (coal[i] == COALITION_NULL) {
3744 					coal_dbg("could not find coalition id:%llu "
3745 					    "(perhaps it has been terminated or reaped)", cid);
3746 					/*
3747 					 * release any other coalition's we
3748 					 * may have a reference to
3749 					 */
3750 					spawn_coalitions_release_all(coal);
3751 					error = ESRCH;
3752 					goto bad;
3753 				}
3754 				if (coalition_type(coal[i]) != i) {
3755 					coal_dbg("coalition with id:%lld is not of type:%d"
3756 					    " (it's type:%d)", cid, i, coalition_type(coal[i]));
3757 					spawn_coalitions_release_all(coal);
3758 					error = ESRCH;
3759 					goto bad;
3760 				}
3761 				coal_role[i] = coal_info.psci_info[i].psci_role;
3762 				ncoals++;
3763 			}
3764 		}
3765 		if (ncoals < COALITION_NUM_TYPES) {
3766 			/*
3767 			 * If the user is attempting to spawn into a subset of
3768 			 * the known coalition types, then make sure they have
3769 			 * _at_least_ specified a resource coalition. If not,
3770 			 * the following fork1() call will implicitly force an
3771 			 * inheritance from 'p' and won't actually spawn the
3772 			 * new task into the coalitions the user specified.
3773 			 * (also the call to coalitions_set_roles will panic)
3774 			 */
3775 			if (coal[COALITION_TYPE_RESOURCE] == COALITION_NULL) {
3776 				spawn_coalitions_release_all(coal);
3777 				error = EINVAL;
3778 				goto bad;
3779 			}
3780 		}
3781 do_fork1:
3782 #endif /* CONFIG_COALITIONS */
3783 
3784 		/*
3785 		 * note that this will implicitly inherit the
3786 		 * caller's persona (if it exists)
3787 		 */
3788 		error = fork1(p, &imgp->ip_new_thread, PROC_CREATE_SPAWN, coal);
3789 		/* returns a thread and task reference */
3790 
3791 		if (error == 0) {
3792 			new_task = get_threadtask(imgp->ip_new_thread);
3793 		}
3794 #if CONFIG_COALITIONS
3795 		/* set the roles of this task within each given coalition */
3796 		if (error == 0) {
3797 			kr = coalitions_set_roles(coal, new_task, coal_role);
3798 			if (kr != KERN_SUCCESS) {
3799 				error = EINVAL;
3800 			}
3801 			if (kdebug_debugid_enabled(MACHDBG_CODE(DBG_MACH_COALITION,
3802 			    MACH_COALITION_ADOPT))) {
3803 				for (i = 0; i < COALITION_NUM_TYPES; i++) {
3804 					if (coal[i] != COALITION_NULL) {
3805 						/*
3806 						 * On 32-bit targets, uniqueid
3807 						 * will get truncated to 32 bits
3808 						 */
3809 						KDBG_RELEASE(MACHDBG_CODE(
3810 							    DBG_MACH_COALITION,
3811 							    MACH_COALITION_ADOPT),
3812 						    coalition_id(coal[i]),
3813 						    get_task_uniqueid(new_task));
3814 					}
3815 				}
3816 			}
3817 		}
3818 
3819 		/* drop our references and activations - fork1() now holds them */
3820 		spawn_coalitions_release_all(coal);
3821 #endif /* CONFIG_COALITIONS */
3822 		if (error != 0) {
3823 			goto bad;
3824 		}
3825 		imgp->ip_flags |= IMGPF_SPAWN;  /* spawn w/o exec */
3826 		spawn_no_exec = TRUE;           /* used in later tests */
3827 	} else {
3828 		/* Adjust the user proc count */
3829 		(void)chgproccnt(kauth_getruid(), 1);
3830 		/*
3831 		 * For execve case, create a new proc, task and thread
3832 		 * but don't make the proc visible to userland. After
3833 		 * image activation, the new proc would take place of
3834 		 * the old proc in pid hash and other lists that make
3835 		 * the proc visible to the system.
3836 		 */
3837 		imgp->ip_new_thread = cloneproc(old_task, NULL, p, CLONEPROC_FLAGS_FOR_EXEC);
3838 
3839 		/* task and thread ref returned by cloneproc */
3840 		if (imgp->ip_new_thread == NULL) {
3841 			(void)chgproccnt(kauth_getruid(), -1);
3842 			error = ENOMEM;
3843 			goto bad;
3844 		}
3845 
3846 		new_task = get_threadtask(imgp->ip_new_thread);
3847 		imgp->ip_flags |= IMGPF_EXEC;
3848 	}
3849 
3850 	p = (proc_t)get_bsdthreadtask_info(imgp->ip_new_thread);
3851 
3852 	if (spawn_no_exec) {
3853 		/*
3854 		 * We had to wait until this point before firing the
3855 		 * proc:::create probe, otherwise p would not point to the
3856 		 * child process.
3857 		 */
3858 		DTRACE_PROC1(create, proc_t, p);
3859 	}
3860 	assert(p != NULL);
3861 
3862 	if (subsystem_root_path) {
3863 		/* If a subsystem root was specified, swap it in */
3864 		char * old_subsystem_root_path = p->p_subsystem_root_path;
3865 		p->p_subsystem_root_path = subsystem_root_path;
3866 		subsystem_root_path = old_subsystem_root_path;
3867 	}
3868 
3869 	p->p_crash_behavior = crash_behavior;
3870 	p->p_crash_behavior_deadline = crash_behavior_deadline;
3871 
3872 	p->p_crash_count = px_sa.psa_crash_count;
3873 	p->p_throttle_timeout = px_sa.psa_throttle_timeout;
3874 
3875 	/* We'll need the subsystem root for setting up Apple strings */
3876 	imgp->ip_subsystem_root_path = p->p_subsystem_root_path;
3877 
3878 	context.vc_thread = imgp->ip_new_thread;
3879 	context.vc_ucred = proc_ucred_unsafe(p);  /* in init */
3880 
3881 	/*
3882 	 * Post fdt_fork(), pre exec_handle_sugid() - this is where we want
3883 	 * to handle the file_actions.
3884 	 */
3885 
3886 	/* Has spawn file actions? */
3887 	if (imgp->ip_px_sfa != NULL) {
3888 		/*
3889 		 * The POSIX_SPAWN_CLOEXEC_DEFAULT flag
3890 		 * is handled in exec_handle_file_actions().
3891 		 */
3892 #if CONFIG_AUDIT
3893 		/*
3894 		 * The file actions auditing can overwrite the upath of
3895 		 * AUE_POSIX_SPAWN audit record.  Save the audit record.
3896 		 */
3897 		struct kaudit_record *save_uu_ar = uthread->uu_ar;
3898 		uthread->uu_ar = NULL;
3899 #endif
3900 		error = exec_handle_file_actions(imgp,
3901 		    imgp->ip_px_sa != NULL ? px_sa.psa_flags : 0);
3902 #if CONFIG_AUDIT
3903 		/* Restore the AUE_POSIX_SPAWN audit record. */
3904 		uthread->uu_ar = save_uu_ar;
3905 #endif
3906 		if (error != 0) {
3907 			goto bad;
3908 		}
3909 	}
3910 
3911 	/* Has spawn port actions? */
3912 	if (imgp->ip_px_spa != NULL) {
3913 #if CONFIG_AUDIT
3914 		/*
3915 		 * Do the same for the port actions as we did for the file
3916 		 * actions.  Save the AUE_POSIX_SPAWN audit record.
3917 		 */
3918 		struct kaudit_record *save_uu_ar = uthread->uu_ar;
3919 		uthread->uu_ar = NULL;
3920 #endif
3921 		error = exec_handle_port_actions(imgp, &port_actions);
3922 #if CONFIG_AUDIT
3923 		/* Restore the AUE_POSIX_SPAWN audit record. */
3924 		uthread->uu_ar = save_uu_ar;
3925 #endif
3926 		if (error != 0) {
3927 			goto bad;
3928 		}
3929 	}
3930 
3931 	/* Has spawn attr? */
3932 	if (imgp->ip_px_sa != NULL) {
3933 		/*
3934 		 * Reset UID/GID to parent's RUID/RGID; This works only
3935 		 * because the operation occurs before the call
3936 		 * to exec_handle_sugid() by the image activator called
3937 		 * from exec_activate_image().
3938 		 *
3939 		 * POSIX requires that any setuid/setgid bits on the process
3940 		 * image will take precedence over the spawn attributes
3941 		 * (re)setting them.
3942 		 *
3943 		 * Modifications to p_ucred must be guarded using the
3944 		 * proc's ucred lock. This prevents others from accessing
3945 		 * a garbage credential.
3946 		 */
3947 		if (px_sa.psa_flags & POSIX_SPAWN_RESETIDS) {
3948 			kauth_cred_proc_update(p, PROC_SETTOKEN_NONE,
3949 			    ^bool (kauth_cred_t parent __unused, kauth_cred_t model){
3950 				return kauth_cred_model_setuidgid(model,
3951 				kauth_cred_getruid(parent),
3952 				kauth_cred_getrgid(parent));
3953 			});
3954 		}
3955 
3956 		if (imgp->ip_px_pcred_info) {
3957 			if (!spawn_no_exec) {
3958 				error = ENOTSUP;
3959 				goto bad;
3960 			}
3961 
3962 			error = spawn_posix_cred_adopt(p, imgp->ip_px_pcred_info);
3963 			if (error != 0) {
3964 				goto bad;
3965 			}
3966 		}
3967 
3968 #if CONFIG_PERSONAS
3969 		if (imgp->ip_px_persona != NULL) {
3970 			if (!spawn_no_exec) {
3971 				error = ENOTSUP;
3972 				goto bad;
3973 			}
3974 
3975 			/*
3976 			 * If we were asked to spawn a process into a new persona,
3977 			 * do the credential switch now (which may override the UID/GID
3978 			 * inherit done just above). It's important to do this switch
3979 			 * before image activation both for reasons stated above, and
3980 			 * to ensure that the new persona has access to the image/file
3981 			 * being executed.
3982 			 */
3983 			error = spawn_persona_adopt(p, imgp->ip_px_persona);
3984 			if (error != 0) {
3985 				goto bad;
3986 			}
3987 		}
3988 #endif /* CONFIG_PERSONAS */
3989 #if !SECURE_KERNEL
3990 		/*
3991 		 * Disable ASLR for the spawned process.
3992 		 *
3993 		 * But only do so if we are not embedded + RELEASE.
3994 		 * While embedded allows for a boot-arg (-disable_aslr)
3995 		 * to deal with this (which itself is only honored on
3996 		 * DEVELOPMENT or DEBUG builds of xnu), it is often
3997 		 * useful or necessary to disable ASLR on a per-process
3998 		 * basis for unit testing and debugging.
3999 		 */
4000 		if (px_sa.psa_flags & _POSIX_SPAWN_DISABLE_ASLR) {
4001 			OSBitOrAtomic(P_DISABLE_ASLR, &p->p_flag);
4002 		}
4003 #endif /* !SECURE_KERNEL */
4004 
4005 		/* Randomize high bits of ASLR slide */
4006 		if (px_sa.psa_flags & _POSIX_SPAWN_HIGH_BITS_ASLR) {
4007 			imgp->ip_flags |= IMGPF_HIGH_BITS_ASLR;
4008 		}
4009 
4010 #if !SECURE_KERNEL
4011 		/*
4012 		 * Forcibly disallow execution from data pages for the spawned process
4013 		 * even if it would otherwise be permitted by the architecture default.
4014 		 */
4015 		if (px_sa.psa_flags & _POSIX_SPAWN_ALLOW_DATA_EXEC) {
4016 			imgp->ip_flags |= IMGPF_ALLOW_DATA_EXEC;
4017 		}
4018 #endif /* !SECURE_KERNEL */
4019 
4020 #if     __has_feature(ptrauth_calls)
4021 		if (vm_shared_region_reslide_aslr && is_64 && (px_sa.psa_flags & _POSIX_SPAWN_RESLIDE)) {
4022 			imgp->ip_flags |= IMGPF_RESLIDE;
4023 		}
4024 #endif /* __has_feature(ptrauth_calls) */
4025 
4026 		if ((px_sa.psa_apptype & POSIX_SPAWN_PROC_TYPE_MASK) ==
4027 		    POSIX_SPAWN_PROC_TYPE_DRIVER) {
4028 			imgp->ip_flags |= IMGPF_DRIVER;
4029 		}
4030 	}
4031 
4032 	/*
4033 	 * Disable ASLR during image activation.  This occurs either if the
4034 	 * _POSIX_SPAWN_DISABLE_ASLR attribute was found above or if
4035 	 * P_DISABLE_ASLR was inherited from the parent process.
4036 	 */
4037 	if (p->p_flag & P_DISABLE_ASLR) {
4038 		imgp->ip_flags |= IMGPF_DISABLE_ASLR;
4039 	}
4040 
4041 	/*
4042 	 * Clear transition flag so we won't hang if exec_activate_image() causes
4043 	 * an automount (and launchd does a proc sysctl to service it).
4044 	 *
4045 	 * <rdar://problem/6848672>, <rdar://problem/5959568>.
4046 	 */
4047 	proc_transend(p, 0);
4048 	proc_transit_set = 0;
4049 
4050 	if (!spawn_no_exec) {
4051 		/*
4052 		 * Clear the signal lock in case of exec, since
4053 		 * image activation uses psignal on child process.
4054 		 */
4055 		proc_signalend(p, 0);
4056 		proc_signal_set = 0;
4057 	}
4058 
4059 #if MAC_SPAWN   /* XXX */
4060 	if (uap->mac_p != USER_ADDR_NULL) {
4061 		error = mac_execve_enter(uap->mac_p, imgp);
4062 		if (error) {
4063 			goto bad;
4064 		}
4065 	}
4066 #endif
4067 
4068 	/*
4069 	 * Activate the image.
4070 	 * Warning: If activation failed after point of no return, it returns error
4071 	 * as 0 and pretends the call succeeded.
4072 	 */
4073 	error = exec_activate_image(imgp);
4074 #if defined(HAS_APPLE_PAC)
4075 	ml_task_set_jop_pid_from_shared_region(new_task);
4076 	ml_task_set_disable_user_jop(new_task, imgp->ip_flags & IMGPF_NOJOP ? TRUE : FALSE);
4077 	ml_thread_set_disable_user_jop(imgp->ip_new_thread, imgp->ip_flags & IMGPF_NOJOP ? TRUE : FALSE);
4078 	ml_thread_set_jop_pid(imgp->ip_new_thread, new_task);
4079 #endif
4080 
4081 	/*
4082 	 * If you've come here to add support for some new HW feature or some per-process or per-vmmap
4083 	 * or per-pmap flag that needs to be set before the process runs, or are in general lost, here
4084 	 * is some help. This summary was accurate as of Jul 2022. Use git log as needed. This comment
4085 	 * is here to prevent a recurrence of rdar://96307913
4086 	 *
4087 	 * In posix_spawn, following is what happens:
4088 	 * 1. Lots of prep and checking work
4089 	 * 2. Image activation via exec_activate_image(). The new task will get a new pmap here
4090 	 * 3. More prep work. (YOU ARE HERE)
4091 	 * 4. exec_resettextvp() is called
4092 	 * 5. At this point it is safe to check entitlements and code signatures
4093 	 * 6. task_clear_return_wait(get_threadtask(imgp->ip_new_thread), TCRW_CLEAR_INITIAL_WAIT);
4094 	 *    The new thread is allowed to run in kernel. It cannot yet get to userland
4095 	 * 7. More things done here. This is your chance to affect the task before it runs in
4096 	 *    userspace
4097 	 * 8. task_clear_return_wait(get_threadtask(imgp->ip_new_thread), TCRW_CLEAR_FINAL_WAIT);
4098 	 *     The new thread is allowed to run in userland
4099 	 */
4100 
4101 	if (error == 0 && !spawn_no_exec) {
4102 		p = proc_exec_switch_task(current_proc(), p, old_task, new_task, imgp->ip_new_thread, &inherit);
4103 		/* proc ref returned */
4104 		should_release_proc_ref = TRUE;
4105 	}
4106 
4107 	if (error == 0) {
4108 		/* process completed the exec, but may have failed after point of no return */
4109 		exec_done = TRUE;
4110 		/*
4111 		 * Enable new task IPC access if exec_activate_image() returned an
4112 		 * active task. (Checks active bit in ipc_task_enable() under lock).
4113 		 */
4114 		ipc_task_enable(new_task);
4115 	}
4116 
4117 
4118 	if (!error && imgp->ip_px_sa != NULL) {
4119 		thread_t child_thread = imgp->ip_new_thread;
4120 		uthread_t child_uthread = get_bsdthread_info(child_thread);
4121 
4122 		/*
4123 		 * Because of POSIX_SPAWN_SETEXEC, we need to handle this after image
4124 		 * activation, else when image activation fails (before the point of no
4125 		 * return) would leave the parent process in a modified state.
4126 		 */
4127 		if (px_sa.psa_flags & POSIX_SPAWN_SETPGROUP) {
4128 			struct setpgid_args spga;
4129 			spga.pid = proc_getpid(p);
4130 			spga.pgid = px_sa.psa_pgroup;
4131 			/*
4132 			 * Effectively, call setpgid() system call; works
4133 			 * because there are no pointer arguments.
4134 			 */
4135 			if ((error = setpgid(p, &spga, ival)) != 0) {
4136 				goto bad_px_sa;
4137 			}
4138 		}
4139 
4140 		if (px_sa.psa_flags & POSIX_SPAWN_SETSID) {
4141 			error = setsid_internal(p);
4142 			if (error != 0) {
4143 				goto bad_px_sa;
4144 			}
4145 		}
4146 
4147 		/*
4148 		 * If we have a spawn attr, and it contains signal related flags,
4149 		 * the we need to process them in the "context" of the new child
4150 		 * process, so we have to process it following image activation,
4151 		 * prior to making the thread runnable in user space.  This is
4152 		 * necessitated by some signal information being per-thread rather
4153 		 * than per-process, and we don't have the new allocation in hand
4154 		 * until after the image is activated.
4155 		 */
4156 
4157 		/*
4158 		 * Mask a list of signals, instead of them being unmasked, if
4159 		 * they were unmasked in the parent; note that some signals
4160 		 * are not maskable.
4161 		 */
4162 		if (px_sa.psa_flags & POSIX_SPAWN_SETSIGMASK) {
4163 			child_uthread->uu_sigmask = (px_sa.psa_sigmask & ~sigcantmask);
4164 		}
4165 		/*
4166 		 * Default a list of signals instead of ignoring them, if
4167 		 * they were ignored in the parent.  Note that we pass
4168 		 * spawn_no_exec to setsigvec() to indicate that we called
4169 		 * fork1() and therefore do not need to call proc_signalstart()
4170 		 * internally.
4171 		 */
4172 		if (px_sa.psa_flags & POSIX_SPAWN_SETSIGDEF) {
4173 			vec.sa_handler = SIG_DFL;
4174 			vec.sa_tramp = 0;
4175 			vec.sa_mask = 0;
4176 			vec.sa_flags = 0;
4177 			for (sig = 1; sig < NSIG; sig++) {
4178 				if (px_sa.psa_sigdefault & (1 << (sig - 1))) {
4179 					error = setsigvec(p, child_thread, sig, &vec, spawn_no_exec);
4180 				}
4181 			}
4182 		}
4183 
4184 		/*
4185 		 * Activate the CPU usage monitor, if requested. This is done via a task-wide, per-thread CPU
4186 		 * usage limit, which will generate a resource exceeded exception if any one thread exceeds the
4187 		 * limit.
4188 		 *
4189 		 * Userland gives us interval in seconds, and the kernel SPI expects nanoseconds.
4190 		 */
4191 		if ((px_sa.psa_cpumonitor_percent != 0) && (px_sa.psa_cpumonitor_percent < UINT8_MAX)) {
4192 			/*
4193 			 * Always treat a CPU monitor activation coming from spawn as entitled. Requiring
4194 			 * an entitlement to configure the monitor a certain way seems silly, since
4195 			 * whomever is turning it on could just as easily choose not to do so.
4196 			 */
4197 			error = proc_set_task_ruse_cpu(proc_task(p),
4198 			    TASK_POLICY_RESOURCE_ATTRIBUTE_NOTIFY_EXC,
4199 			    (uint8_t)px_sa.psa_cpumonitor_percent,
4200 			    px_sa.psa_cpumonitor_interval * NSEC_PER_SEC,
4201 			    0, TRUE);
4202 		}
4203 
4204 
4205 		if (px_pcred_info &&
4206 		    (px_pcred_info->pspci_flags & POSIX_SPAWN_POSIX_CRED_LOGIN)) {
4207 			/*
4208 			 * setlogin() must happen after setsid()
4209 			 */
4210 			setlogin_internal(p, px_pcred_info->pspci_login);
4211 		}
4212 
4213 bad_px_sa:
4214 		if (error != 0) {
4215 			KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
4216 			    proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_BAD_PSATTR, 0, 0);
4217 			exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_BAD_PSATTR);
4218 		}
4219 	}
4220 
4221 bad:
4222 
4223 	if (error == 0) {
4224 		/* reset delay idle sleep status if set */
4225 #if CONFIG_DELAY_IDLE_SLEEP
4226 		if ((p->p_flag & P_DELAYIDLESLEEP) == P_DELAYIDLESLEEP) {
4227 			OSBitAndAtomic(~((uint32_t)P_DELAYIDLESLEEP), &p->p_flag);
4228 		}
4229 #endif /* CONFIG_DELAY_IDLE_SLEEP */
4230 		/* upon  successful spawn, re/set the proc control state */
4231 		if (imgp->ip_px_sa != NULL) {
4232 			switch (px_sa.psa_pcontrol) {
4233 			case POSIX_SPAWN_PCONTROL_THROTTLE:
4234 				p->p_pcaction = P_PCTHROTTLE;
4235 				break;
4236 			case POSIX_SPAWN_PCONTROL_SUSPEND:
4237 				p->p_pcaction = P_PCSUSP;
4238 				break;
4239 			case POSIX_SPAWN_PCONTROL_KILL:
4240 				p->p_pcaction = P_PCKILL;
4241 				break;
4242 			case POSIX_SPAWN_PCONTROL_NONE:
4243 			default:
4244 				p->p_pcaction = 0;
4245 				break;
4246 			}
4247 			;
4248 		}
4249 		exec_resettextvp(p, imgp);
4250 
4251 #if CONFIG_MEMORYSTATUS
4252 		/* Set jetsam priority for DriverKit processes */
4253 		if (px_sa.psa_apptype == POSIX_SPAWN_PROC_TYPE_DRIVER) {
4254 			px_sa.psa_priority = JETSAM_PRIORITY_DRIVER_APPLE;
4255 		}
4256 
4257 		/* Has jetsam attributes? */
4258 		if (imgp->ip_px_sa != NULL && (px_sa.psa_jetsam_flags & POSIX_SPAWN_JETSAM_SET)) {
4259 			/*
4260 			 * With 2-level high-water-mark support, POSIX_SPAWN_JETSAM_HIWATER_BACKGROUND is no
4261 			 * longer relevant, as background limits are described via the inactive limit slots.
4262 			 *
4263 			 * That said, however, if the POSIX_SPAWN_JETSAM_HIWATER_BACKGROUND is passed in,
4264 			 * we attempt to mimic previous behavior by forcing the BG limit data into the
4265 			 * inactive/non-fatal mode and force the active slots to hold system_wide/fatal mode.
4266 			 */
4267 
4268 			if (px_sa.psa_jetsam_flags & POSIX_SPAWN_JETSAM_HIWATER_BACKGROUND) {
4269 				memorystatus_update(p, px_sa.psa_priority, 0, FALSE, /* assertion priority */
4270 				    (px_sa.psa_jetsam_flags & POSIX_SPAWN_JETSAM_USE_EFFECTIVE_PRIORITY),
4271 				    TRUE,
4272 				    -1, TRUE,
4273 				    px_sa.psa_memlimit_inactive, FALSE);
4274 			} else {
4275 				memorystatus_update(p, px_sa.psa_priority, 0, FALSE, /* assertion priority */
4276 				    (px_sa.psa_jetsam_flags & POSIX_SPAWN_JETSAM_USE_EFFECTIVE_PRIORITY),
4277 				    TRUE,
4278 				    px_sa.psa_memlimit_active,
4279 				    (px_sa.psa_jetsam_flags & POSIX_SPAWN_JETSAM_MEMLIMIT_ACTIVE_FATAL),
4280 				    px_sa.psa_memlimit_inactive,
4281 				    (px_sa.psa_jetsam_flags & POSIX_SPAWN_JETSAM_MEMLIMIT_INACTIVE_FATAL));
4282 			}
4283 		}
4284 
4285 		/* Has jetsam relaunch behavior? */
4286 		if (imgp->ip_px_sa != NULL && (px_sa.psa_jetsam_flags & POSIX_SPAWN_JETSAM_RELAUNCH_BEHAVIOR_MASK)) {
4287 			/*
4288 			 * Launchd has passed in data indicating the behavior of this process in response to jetsam.
4289 			 * This data would be used by the jetsam subsystem to determine the position and protection
4290 			 * offered to this process on dirty -> clean transitions.
4291 			 */
4292 			int relaunch_flags = P_MEMSTAT_RELAUNCH_UNKNOWN;
4293 			switch (px_sa.psa_jetsam_flags & POSIX_SPAWN_JETSAM_RELAUNCH_BEHAVIOR_MASK) {
4294 			case POSIX_SPAWN_JETSAM_RELAUNCH_BEHAVIOR_LOW:
4295 				relaunch_flags = P_MEMSTAT_RELAUNCH_LOW;
4296 				break;
4297 			case POSIX_SPAWN_JETSAM_RELAUNCH_BEHAVIOR_MED:
4298 				relaunch_flags = P_MEMSTAT_RELAUNCH_MED;
4299 				break;
4300 			case POSIX_SPAWN_JETSAM_RELAUNCH_BEHAVIOR_HIGH:
4301 				relaunch_flags = P_MEMSTAT_RELAUNCH_HIGH;
4302 				break;
4303 			default:
4304 				break;
4305 			}
4306 			memorystatus_relaunch_flags_update(p, relaunch_flags);
4307 		}
4308 
4309 #endif /* CONFIG_MEMORYSTATUS */
4310 		if (imgp->ip_px_sa != NULL && px_sa.psa_thread_limit > 0) {
4311 			task_set_thread_limit(new_task, (uint16_t)px_sa.psa_thread_limit);
4312 		}
4313 
4314 #if CONFIG_PROC_RESOURCE_LIMITS
4315 		if (imgp->ip_px_sa != NULL && (px_sa.psa_port_soft_limit > 0 || px_sa.psa_port_hard_limit > 0)) {
4316 			task_set_port_space_limits(new_task, (uint32_t)px_sa.psa_port_soft_limit,
4317 			    (uint32_t)px_sa.psa_port_hard_limit);
4318 		}
4319 
4320 		if (imgp->ip_px_sa != NULL && (px_sa.psa_filedesc_soft_limit > 0 || px_sa.psa_filedesc_hard_limit > 0)) {
4321 			proc_set_filedesc_limits(p, (int)px_sa.psa_filedesc_soft_limit,
4322 			    (int)px_sa.psa_filedesc_hard_limit);
4323 		}
4324 #endif /* CONFIG_PROC_RESOURCE_LIMITS */
4325 
4326 		/* Disable wakeup monitoring for DriverKit processes */
4327 		if (px_sa.psa_apptype == POSIX_SPAWN_PROC_TYPE_DRIVER) {
4328 			uint32_t      flags = WAKEMON_DISABLE;
4329 			task_wakeups_monitor_ctl(new_task, &flags, NULL);
4330 		}
4331 	}
4332 
4333 	/*
4334 	 * If we successfully called fork1() or cloneproc, we always need
4335 	 * to do this. This is because we come back from that call with
4336 	 * signals blocked in the child, and we have to unblock them, for exec
4337 	 * case they are unblocked before activation, but for true spawn case
4338 	 * we want to wait until after we've performed any spawn actions.
4339 	 * This has to happen before process_signature(), which uses psignal.
4340 	 */
4341 	if (proc_transit_set) {
4342 		proc_transend(p, 0);
4343 	}
4344 
4345 	/*
4346 	 * Drop the signal lock on the child which was taken on our
4347 	 * behalf by forkproc()/cloneproc() to prevent signals being
4348 	 * received by the child in a partially constructed state.
4349 	 */
4350 	if (proc_signal_set) {
4351 		proc_signalend(p, 0);
4352 	}
4353 
4354 	if (error == 0) {
4355 		/*
4356 		 * We need to initialize the bank context behind the protection of
4357 		 * the proc_trans lock to prevent a race with exit. We can't do this during
4358 		 * exec_activate_image because task_bank_init checks entitlements that
4359 		 * aren't loaded until subsequent calls (including exec_resettextvp).
4360 		 */
4361 		error = proc_transstart(p, 0, 0);
4362 
4363 		if (error == 0) {
4364 			task_bank_init(new_task);
4365 			proc_transend(p, 0);
4366 		}
4367 
4368 #if __arm64__
4369 		proc_footprint_entitlement_hacks(p, new_task);
4370 #endif /* __arm64__ */
4371 
4372 #if XNU_TARGET_OS_OSX
4373 #define SINGLE_JIT_ENTITLEMENT "com.apple.security.cs.single-jit"
4374 		if (IOTaskHasEntitlement(new_task, SINGLE_JIT_ENTITLEMENT)) {
4375 			vm_map_single_jit(get_task_map(new_task));
4376 		}
4377 #endif /* XNU_TARGET_OS_OSX */
4378 
4379 #if __has_feature(ptrauth_calls)
4380 		task_set_pac_exception_fatal_flag(new_task);
4381 #endif /* __has_feature(ptrauth_calls) */
4382 	}
4383 
4384 	/* Inherit task role from old task to new task for exec */
4385 	if (error == 0 && !spawn_no_exec) {
4386 		proc_inherit_task_role(new_task, old_task);
4387 	}
4388 
4389 #if CONFIG_ARCADE
4390 	if (error == 0) {
4391 		/*
4392 		 * Check to see if we need to trigger an arcade upcall AST now
4393 		 * that the vnode has been reset on the task.
4394 		 */
4395 		arcade_prepare(new_task, imgp->ip_new_thread);
4396 	}
4397 #endif /* CONFIG_ARCADE */
4398 
4399 	if (error == 0) {
4400 		proc_apply_jit_and_vm_policies(imgp, p, new_task);
4401 	}
4402 
4403 	/* Clear the initial wait on the thread before handling spawn policy */
4404 	if (imgp && imgp->ip_new_thread) {
4405 		task_clear_return_wait(get_threadtask(imgp->ip_new_thread), TCRW_CLEAR_INITIAL_WAIT);
4406 	}
4407 
4408 	/*
4409 	 * Apply the spawnattr policy, apptype (which primes the task for importance donation),
4410 	 * and bind any portwatch ports to the new task.
4411 	 * This must be done after the exec so that the child's thread is ready,
4412 	 * and after the in transit state has been released, because priority is
4413 	 * dropped here so we need to be prepared for a potentially long preemption interval
4414 	 *
4415 	 * TODO: Consider splitting this up into separate phases
4416 	 */
4417 	if (error == 0 && imgp->ip_px_sa != NULL) {
4418 		struct _posix_spawnattr *psa = (struct _posix_spawnattr *) imgp->ip_px_sa;
4419 
4420 		error = exec_handle_spawnattr_policy(p, imgp->ip_new_thread, psa->psa_apptype, psa->psa_qos_clamp,
4421 		    psa->psa_darwin_role, &port_actions);
4422 	}
4423 
4424 	/* Transfer the turnstile watchport boost to new task if in exec */
4425 	if (error == 0 && !spawn_no_exec) {
4426 		task_transfer_turnstile_watchports(old_task, new_task, imgp->ip_new_thread);
4427 	}
4428 
4429 	if (error == 0 && imgp->ip_px_sa != NULL) {
4430 		struct _posix_spawnattr *psa = (struct _posix_spawnattr *) imgp->ip_px_sa;
4431 
4432 		if (psa->psa_no_smt) {
4433 			task_set_no_smt(new_task);
4434 		}
4435 		if (psa->psa_tecs) {
4436 			task_set_tecs(new_task);
4437 		}
4438 	}
4439 
4440 	if (error == 0 && imgp->ip_px_sa != NULL) {
4441 		struct _posix_spawnattr *psa = (struct _posix_spawnattr *) imgp->ip_px_sa;
4442 
4443 		if (psa->psa_options & PSA_OPTION_DATALESS_IOPOLICY) {
4444 			struct _iopol_param_t iop_param = {
4445 				.iop_scope = IOPOL_SCOPE_PROCESS,
4446 				.iop_iotype = IOPOL_TYPE_VFS_MATERIALIZE_DATALESS_FILES,
4447 				.iop_policy = psa->psa_dataless_iopolicy,
4448 			};
4449 			error = iopolicysys_vfs_materialize_dataless_files(p, IOPOL_CMD_SET, iop_param.iop_scope,
4450 			    iop_param.iop_policy, &iop_param);
4451 		}
4452 	}
4453 
4454 	if (error == 0) {
4455 		/* Apply the main thread qos */
4456 		thread_t main_thread = imgp->ip_new_thread;
4457 		task_set_main_thread_qos(new_task, main_thread);
4458 	}
4459 
4460 	/*
4461 	 * Release any ports we kept around for binding to the new task
4462 	 * We need to release the rights even if the posix_spawn has failed.
4463 	 */
4464 	if (imgp->ip_px_spa != NULL) {
4465 		exec_port_actions_destroy(&port_actions);
4466 	}
4467 
4468 	/*
4469 	 * We have to delay operations which might throw a signal until after
4470 	 * the signals have been unblocked; however, we want that to happen
4471 	 * after exec_resettextvp() so that the textvp is correct when they
4472 	 * fire.
4473 	 */
4474 	if (error == 0) {
4475 		error = process_signature(p, imgp);
4476 
4477 		/*
4478 		 * Pay for our earlier safety; deliver the delayed signals from
4479 		 * the incomplete spawn process now that it's complete.
4480 		 */
4481 		if (imgp != NULL && spawn_no_exec && (p->p_lflag & P_LTRACED)) {
4482 			psignal_vfork(p, proc_task(p), imgp->ip_new_thread, SIGTRAP);
4483 		}
4484 
4485 		if (error == 0 && !spawn_no_exec) {
4486 			KDBG(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXEC),
4487 			    proc_getpid(p));
4488 		}
4489 	}
4490 
4491 	if (spawn_no_exec) {
4492 		/* flag the 'fork' has occurred */
4493 		proc_knote(p->p_pptr, NOTE_FORK | proc_getpid(p));
4494 	}
4495 
4496 	/* flag exec has occurred, notify only if it has not failed due to FP Key error */
4497 	if (!error && ((p->p_lflag & P_LTERM_DECRYPTFAIL) == 0)) {
4498 		proc_knote(p, NOTE_EXEC);
4499 	}
4500 
4501 	if (imgp != NULL) {
4502 		uthread_set_exec_data(current_uthread(), NULL);
4503 		if (imgp->ip_vp) {
4504 			vnode_put(imgp->ip_vp);
4505 		}
4506 		if (imgp->ip_scriptvp) {
4507 			vnode_put(imgp->ip_scriptvp);
4508 		}
4509 		if (imgp->ip_strings) {
4510 			execargs_free(imgp);
4511 		}
4512 		if (imgp->ip_free_map) {
4513 			/* Free the map after dropping iocount on vnode to avoid deadlock */
4514 			vm_map_deallocate(imgp->ip_free_map);
4515 		}
4516 		kfree_data(imgp->ip_px_sfa,
4517 		    px_args.file_actions_size);
4518 		kfree_data(imgp->ip_px_spa,
4519 		    px_args.port_actions_size);
4520 #if CONFIG_PERSONAS
4521 		kfree_data(imgp->ip_px_persona,
4522 		    px_args.persona_info_size);
4523 #endif
4524 		kfree_data(imgp->ip_px_pcred_info,
4525 		    px_args.posix_cred_info_size);
4526 
4527 		if (subsystem_root_path != NULL) {
4528 			zfree(ZV_NAMEI, subsystem_root_path);
4529 		}
4530 #if CONFIG_MACF
4531 		struct ip_px_smpx_s *px_s = &imgp->ip_px_smpx;
4532 		kfree_data(px_s->array, px_args.mac_extensions_size);
4533 		kfree_data(px_s->data, (vm_size_t)px_s->datalen);
4534 
4535 		if (imgp->ip_execlabelp) {
4536 			mac_cred_label_free(imgp->ip_execlabelp);
4537 			imgp->ip_execlabelp = NULL;
4538 		}
4539 		if (imgp->ip_scriptlabelp) {
4540 			mac_vnode_label_free(imgp->ip_scriptlabelp);
4541 			imgp->ip_scriptlabelp = NULL;
4542 		}
4543 		if (imgp->ip_cs_error != OS_REASON_NULL) {
4544 			os_reason_free(imgp->ip_cs_error);
4545 			imgp->ip_cs_error = OS_REASON_NULL;
4546 		}
4547 		if (imgp->ip_inherited_shared_region_id != NULL) {
4548 			kfree_data(imgp->ip_inherited_shared_region_id,
4549 			    strlen(imgp->ip_inherited_shared_region_id) + 1);
4550 			imgp->ip_inherited_shared_region_id = NULL;
4551 		}
4552 #endif
4553 	}
4554 
4555 #if CONFIG_DTRACE
4556 	if (spawn_no_exec) {
4557 		/*
4558 		 * In the original DTrace reference implementation,
4559 		 * posix_spawn() was a libc routine that just
4560 		 * did vfork(2) then exec(2).  Thus the proc::: probes
4561 		 * are very fork/exec oriented.  The details of this
4562 		 * in-kernel implementation of posix_spawn() is different
4563 		 * (while producing the same process-observable effects)
4564 		 * particularly w.r.t. errors, and which thread/process
4565 		 * is constructing what on behalf of whom.
4566 		 */
4567 		if (error) {
4568 			DTRACE_PROC1(spawn__failure, int, error);
4569 		} else {
4570 			DTRACE_PROC(spawn__success);
4571 			/*
4572 			 * Some DTrace scripts, e.g. newproc.d in
4573 			 * /usr/bin, rely on the the 'exec-success'
4574 			 * probe being fired in the child after the
4575 			 * new process image has been constructed
4576 			 * in order to determine the associated pid.
4577 			 *
4578 			 * So, even though the parent built the image
4579 			 * here, for compatibility, mark the new thread
4580 			 * so 'exec-success' fires on it as it leaves
4581 			 * the kernel.
4582 			 */
4583 			dtrace_thread_didexec(imgp->ip_new_thread);
4584 		}
4585 	} else {
4586 		if (error) {
4587 			DTRACE_PROC1(exec__failure, int, error);
4588 		} else {
4589 			dtrace_thread_didexec(imgp->ip_new_thread);
4590 		}
4591 	}
4592 
4593 	if ((dtrace_proc_waitfor_hook = dtrace_proc_waitfor_exec_ptr) != NULL) {
4594 		(*dtrace_proc_waitfor_hook)(p);
4595 	}
4596 #endif
4597 
4598 #if CONFIG_AUDIT
4599 	if (!error && AUDIT_ENABLED() && p) {
4600 		/* Add the CDHash of the new process to the audit record */
4601 		uint8_t *cdhash = cs_get_cdhash(p);
4602 		if (cdhash) {
4603 			AUDIT_ARG(data, cdhash, sizeof(uint8_t), CS_CDHASH_LEN);
4604 		}
4605 	}
4606 #endif
4607 
4608 	/* terminate the new task if exec failed  */
4609 	if (new_task != NULL && task_is_exec_copy(new_task)) {
4610 		task_terminate_internal(new_task);
4611 	}
4612 
4613 	if (exec_failure_reason && !spawn_no_exec) {
4614 		psignal_with_reason(p, SIGKILL, exec_failure_reason);
4615 		exec_failure_reason = NULL;
4616 	}
4617 
4618 	/* Return to both the parent and the child? */
4619 	if (imgp != NULL && spawn_no_exec) {
4620 		/*
4621 		 * If the parent wants the pid, copy it out
4622 		 */
4623 		if (error == 0 && pid != USER_ADDR_NULL) {
4624 			_Static_assert(sizeof(pid_t) == 4, "posix_spawn() assumes a 32-bit pid_t");
4625 			bool aligned = (pid & 3) == 0;
4626 			if (aligned) {
4627 				(void)copyout_atomic32(proc_getpid(p), pid);
4628 			} else {
4629 				(void)suword(pid, proc_getpid(p));
4630 			}
4631 		}
4632 		retval[0] = error;
4633 
4634 		/*
4635 		 * If we had an error, perform an internal reap ; this is
4636 		 * entirely safe, as we have a real process backing us.
4637 		 */
4638 		if (error) {
4639 			proc_list_lock();
4640 			p->p_listflag |= P_LIST_DEADPARENT;
4641 			proc_list_unlock();
4642 			proc_lock(p);
4643 			/* make sure no one else has killed it off... */
4644 			if (p->p_stat != SZOMB && p->exit_thread == NULL) {
4645 				p->exit_thread = current_thread();
4646 				p->p_posix_spawn_failed = true;
4647 				proc_unlock(p);
4648 				exit1(p, 1, (int *)NULL);
4649 			} else {
4650 				/* someone is doing it for us; just skip it */
4651 				proc_unlock(p);
4652 			}
4653 		}
4654 	}
4655 
4656 	/*
4657 	 * Do not terminate the current task, if proc_exec_switch_task did not
4658 	 * switch the tasks, terminating the current task without the switch would
4659 	 * result in loosing the SIGKILL status.
4660 	 */
4661 	if (task_did_exec(old_task)) {
4662 		/* Terminate the current task, since exec will start in new task */
4663 		task_terminate_internal(old_task);
4664 	}
4665 
4666 	/* Release the thread ref returned by cloneproc/fork1 */
4667 	if (imgp != NULL && imgp->ip_new_thread) {
4668 		/* clear the exec complete flag if there is an error before point of no-return */
4669 		uint32_t clearwait_flags = TCRW_CLEAR_FINAL_WAIT;
4670 		if (!spawn_no_exec && !exec_done && error != 0) {
4671 			clearwait_flags |= TCRW_CLEAR_EXEC_COMPLETE;
4672 		}
4673 		/* wake up the new thread */
4674 		task_clear_return_wait(get_threadtask(imgp->ip_new_thread), clearwait_flags);
4675 		thread_deallocate(imgp->ip_new_thread);
4676 		imgp->ip_new_thread = NULL;
4677 	}
4678 
4679 	/* Release the ref returned by cloneproc/fork1 */
4680 	if (new_task) {
4681 		task_deallocate(new_task);
4682 		new_task = NULL;
4683 	}
4684 
4685 	if (should_release_proc_ref) {
4686 		proc_rele(p);
4687 	}
4688 
4689 	kfree_type(typeof(*__spawn_data), __spawn_data);
4690 
4691 	if (inherit != NULL) {
4692 		ipc_importance_release(inherit);
4693 	}
4694 
4695 
4696 	assert(exec_failure_reason == NULL);
4697 	return error;
4698 }
4699 
4700 /*
4701  * proc_exec_switch_task
4702  *
4703  * Parameters:  old_proc		proc before exec
4704  *		new_proc		proc after exec
4705  *		old_task		task before exec
4706  *		new_task		task after exec
4707  *		new_thread		thread in new task
4708  *		inherit			resulting importance linkage
4709  *
4710  * Returns: proc.
4711  *
4712  * Note: The function will switch proc in pid hash from old proc to new proc.
4713  * The switch needs to happen after draining all proc refs and inside
4714  * a proc list lock. In the case of failure to switch the proc, which
4715  * might happen if the process received a SIGKILL or jetsam killed it,
4716  * it will make sure that the new tasks terminates. User proc ref returned
4717  * to caller.
4718  *
4719  * This function is called after point of no return, in the case
4720  * failure to switch, it will terminate the new task and swallow the
4721  * error and let the terminated process complete exec and die.
4722  */
4723 proc_t
proc_exec_switch_task(proc_t old_proc,proc_t new_proc,task_t old_task,task_t new_task,thread_t new_thread,void ** inherit)4724 proc_exec_switch_task(proc_t old_proc, proc_t new_proc, task_t old_task, task_t new_task, thread_t new_thread,
4725     void **inherit)
4726 {
4727 	boolean_t task_active;
4728 	boolean_t proc_active;
4729 	boolean_t thread_active;
4730 	boolean_t reparent_traced_child = FALSE;
4731 	thread_t old_thread = current_thread();
4732 
4733 	thread_set_exec_promotion(old_thread);
4734 	old_proc = proc_refdrain_will_exec(old_proc);
4735 
4736 	new_proc = proc_refdrain_will_exec(new_proc);
4737 	/* extra proc ref returned to the caller */
4738 
4739 	assert(get_threadtask(new_thread) == new_task);
4740 	task_active = task_is_active(new_task);
4741 	proc_active = !(old_proc->p_lflag & P_LEXIT);
4742 
4743 	/* Check if the current thread is not aborted due to SIGKILL */
4744 	thread_active = thread_is_active(old_thread);
4745 
4746 	/*
4747 	 * Do not switch the proc if the new task or proc is already terminated
4748 	 * as a result of error in exec past point of no return
4749 	 */
4750 	if (proc_active && task_active && thread_active) {
4751 		uthread_t new_uthread = get_bsdthread_info(new_thread);
4752 		uthread_t old_uthread = current_uthread();
4753 
4754 		/* Clear dispatchqueue and workloop ast offset */
4755 		new_proc->p_dispatchqueue_offset = 0;
4756 		new_proc->p_dispatchqueue_serialno_offset = 0;
4757 		new_proc->p_dispatchqueue_label_offset = 0;
4758 		new_proc->p_return_to_kernel_offset = 0;
4759 		new_proc->p_pthread_wq_quantum_offset = 0;
4760 
4761 		/* If old_proc is session leader, change the leader to new proc */
4762 		session_replace_leader(old_proc, new_proc);
4763 
4764 		proc_lock(old_proc);
4765 
4766 		/* Copy the signal state, dtrace state and set bsd ast on new thread */
4767 		act_set_astbsd(new_thread);
4768 		new_uthread->uu_siglist |= old_uthread->uu_siglist;
4769 		new_uthread->uu_siglist |= old_proc->p_siglist;
4770 		new_uthread->uu_sigwait = old_uthread->uu_sigwait;
4771 		new_uthread->uu_sigmask = old_uthread->uu_sigmask;
4772 		new_uthread->uu_oldmask = old_uthread->uu_oldmask;
4773 		new_uthread->uu_exit_reason = old_uthread->uu_exit_reason;
4774 #if CONFIG_DTRACE
4775 		new_uthread->t_dtrace_sig = old_uthread->t_dtrace_sig;
4776 		new_uthread->t_dtrace_stop = old_uthread->t_dtrace_stop;
4777 		new_uthread->t_dtrace_resumepid = old_uthread->t_dtrace_resumepid;
4778 		assert(new_uthread->t_dtrace_scratch == NULL);
4779 		new_uthread->t_dtrace_scratch = old_uthread->t_dtrace_scratch;
4780 
4781 		old_uthread->t_dtrace_sig = 0;
4782 		old_uthread->t_dtrace_stop = 0;
4783 		old_uthread->t_dtrace_resumepid = 0;
4784 		old_uthread->t_dtrace_scratch = NULL;
4785 #endif
4786 
4787 #if CONFIG_PROC_UDATA_STORAGE
4788 		new_proc->p_user_data = old_proc->p_user_data;
4789 #endif /* CONFIG_PROC_UDATA_STORAGE */
4790 
4791 		/* Copy the resource accounting info */
4792 		thread_copy_resource_info(new_thread, current_thread());
4793 
4794 		/* Clear the exit reason and signal state on old thread */
4795 		old_uthread->uu_exit_reason = NULL;
4796 		old_uthread->uu_siglist = 0;
4797 
4798 		task_set_did_exec_flag(old_task);
4799 		task_clear_exec_copy_flag(new_task);
4800 
4801 		task_copy_fields_for_exec(new_task, old_task);
4802 
4803 		/*
4804 		 * Need to transfer pending watch port boosts to the new task
4805 		 * while still making sure that the old task remains in the
4806 		 * importance linkage. Create an importance linkage from old task
4807 		 * to new task, then switch the task importance base of old task
4808 		 * and new task. After the switch the port watch boost will be
4809 		 * boosting the new task and new task will be donating importance
4810 		 * to old task.
4811 		 */
4812 		*inherit = ipc_importance_exec_switch_task(old_task, new_task);
4813 
4814 		/* Transfer parent's ptrace state to child */
4815 		new_proc->p_lflag &= ~(P_LTRACED | P_LSIGEXC | P_LNOATTACH);
4816 		new_proc->p_lflag |= (old_proc->p_lflag & (P_LTRACED | P_LSIGEXC | P_LNOATTACH));
4817 		new_proc->p_oppid = old_proc->p_oppid;
4818 
4819 		if (old_proc->p_pptr != new_proc->p_pptr) {
4820 			reparent_traced_child = TRUE;
4821 			new_proc->p_lflag |= P_LTRACE_WAIT;
4822 		}
4823 
4824 		proc_unlock(old_proc);
4825 
4826 		/* Update the list of proc knotes */
4827 		proc_transfer_knotes(old_proc, new_proc);
4828 
4829 		/* Update the proc interval timers */
4830 		proc_inherit_itimers(old_proc, new_proc);
4831 
4832 		proc_list_lock();
4833 
4834 		/* Insert the new proc in child list of parent proc */
4835 		p_reparentallchildren(old_proc, new_proc);
4836 
4837 		/* Switch proc in pid hash */
4838 		phash_replace_locked(old_proc, new_proc);
4839 
4840 		/* Transfer the shadow flag to old proc */
4841 		os_atomic_andnot(&new_proc->p_refcount, P_REF_SHADOW, relaxed);
4842 		os_atomic_or(&old_proc->p_refcount, P_REF_SHADOW, relaxed);
4843 
4844 		/* Change init proc if launchd exec */
4845 		if (old_proc == initproc) {
4846 			/* Take the ref on new proc after proc_refwake_did_exec */
4847 			initproc = new_proc;
4848 			/* Drop the proc ref on old proc */
4849 			proc_rele(old_proc);
4850 		}
4851 
4852 		proc_list_unlock();
4853 	} else {
4854 		task_terminate_internal(new_task);
4855 	}
4856 
4857 	proc_refwake_did_exec(new_proc);
4858 	proc_refwake_did_exec(old_proc);
4859 
4860 	/* Take a ref on initproc if it changed */
4861 	if (new_proc == initproc) {
4862 		initproc = proc_ref(new_proc, false);
4863 		assert(initproc != PROC_NULL);
4864 	}
4865 
4866 	thread_clear_exec_promotion(old_thread);
4867 	proc_rele(old_proc);
4868 
4869 	if (reparent_traced_child) {
4870 		proc_t pp = proc_parent(old_proc);
4871 		assert(pp != PROC_NULL);
4872 
4873 		proc_reparentlocked(new_proc, pp, 1, 0);
4874 		proc_rele(pp);
4875 
4876 		proc_lock(new_proc);
4877 		new_proc->p_lflag &= ~P_LTRACE_WAIT;
4878 		proc_unlock(new_proc);
4879 	}
4880 
4881 	return new_proc;
4882 }
4883 
4884 /*
4885  * execve
4886  *
4887  * Parameters:	uap->fname		File name to exec
4888  *		uap->argp		Argument list
4889  *		uap->envp		Environment list
4890  *
4891  * Returns:	0			Success
4892  *	__mac_execve:EINVAL		Invalid argument
4893  *	__mac_execve:ENOTSUP		Invalid argument
4894  *	__mac_execve:EACCES		Permission denied
4895  *	__mac_execve:EINTR		Interrupted function
4896  *	__mac_execve:ENOMEM		Not enough space
4897  *	__mac_execve:EFAULT		Bad address
4898  *	__mac_execve:ENAMETOOLONG	Filename too long
4899  *	__mac_execve:ENOEXEC		Executable file format error
4900  *	__mac_execve:ETXTBSY		Text file busy [misuse of error code]
4901  *	__mac_execve:???
4902  *
4903  * TODO:	Dynamic linker header address on stack is copied via suword()
4904  */
4905 /* ARGSUSED */
4906 int
execve(proc_t p,struct execve_args * uap,int32_t * retval)4907 execve(proc_t p, struct execve_args *uap, int32_t *retval)
4908 {
4909 	struct __mac_execve_args muap;
4910 	int err;
4911 
4912 	memoryshot(VM_EXECVE, DBG_FUNC_NONE);
4913 
4914 	muap.fname = uap->fname;
4915 	muap.argp = uap->argp;
4916 	muap.envp = uap->envp;
4917 	muap.mac_p = USER_ADDR_NULL;
4918 	err = __mac_execve(p, &muap, retval);
4919 
4920 	return err;
4921 }
4922 
4923 /*
4924  * __mac_execve
4925  *
4926  * Parameters:	uap->fname		File name to exec
4927  *		uap->argp		Argument list
4928  *		uap->envp		Environment list
4929  *		uap->mac_p		MAC label supplied by caller
4930  *
4931  * Returns:	0			Success
4932  *		EINVAL			Invalid argument
4933  *		ENOTSUP			Not supported
4934  *		ENOEXEC			Executable file format error
4935  *	exec_activate_image:EINVAL	Invalid argument
4936  *	exec_activate_image:EACCES	Permission denied
4937  *	exec_activate_image:EINTR	Interrupted function
4938  *	exec_activate_image:ENOMEM	Not enough space
4939  *	exec_activate_image:EFAULT	Bad address
4940  *	exec_activate_image:ENAMETOOLONG	Filename too long
4941  *	exec_activate_image:ENOEXEC	Executable file format error
4942  *	exec_activate_image:ETXTBSY	Text file busy [misuse of error code]
4943  *	exec_activate_image:EBADEXEC	The executable is corrupt/unknown
4944  *	exec_activate_image:???
4945  *	mac_execve_enter:???
4946  *
4947  * TODO:	Dynamic linker header address on stack is copied via suword()
4948  */
4949 int
__mac_execve(proc_t p,struct __mac_execve_args * uap,int32_t * retval __unused)4950 __mac_execve(proc_t p, struct __mac_execve_args *uap, int32_t *retval __unused)
4951 {
4952 	struct image_params *imgp = NULL;
4953 	struct vnode_attr *vap = NULL;
4954 	struct vnode_attr *origvap = NULL;
4955 	int error;
4956 	int is_64 = IS_64BIT_PROCESS(p);
4957 	struct vfs_context context;
4958 	struct uthread  *uthread = NULL;
4959 	task_t old_task = current_task();
4960 	task_t new_task = NULL;
4961 	boolean_t should_release_proc_ref = FALSE;
4962 	boolean_t exec_done = FALSE;
4963 	void *inherit = NULL;
4964 	struct {
4965 		struct image_params imgp;
4966 		struct vnode_attr va;
4967 		struct vnode_attr origva;
4968 	} *__execve_data;
4969 
4970 	/* Allocate a big chunk for locals instead of using stack since these
4971 	 * structures a pretty big.
4972 	 */
4973 	__execve_data = kalloc_type(typeof(*__execve_data), Z_WAITOK | Z_ZERO);
4974 	if (__execve_data == NULL) {
4975 		error = ENOMEM;
4976 		goto exit_with_error;
4977 	}
4978 	imgp = &__execve_data->imgp;
4979 	vap = &__execve_data->va;
4980 	origvap = &__execve_data->origva;
4981 
4982 	/* Initialize the common data in the image_params structure */
4983 	imgp->ip_user_fname = uap->fname;
4984 	imgp->ip_user_argv = uap->argp;
4985 	imgp->ip_user_envv = uap->envp;
4986 	imgp->ip_vattr = vap;
4987 	imgp->ip_origvattr = origvap;
4988 	imgp->ip_vfs_context = &context;
4989 	imgp->ip_flags = (is_64 ? IMGPF_WAS_64BIT_ADDR : IMGPF_NONE) | ((p->p_flag & P_DISABLE_ASLR) ? IMGPF_DISABLE_ASLR : IMGPF_NONE);
4990 	imgp->ip_seg = (is_64 ? UIO_USERSPACE64 : UIO_USERSPACE32);
4991 	imgp->ip_mac_return = 0;
4992 	imgp->ip_cs_error = OS_REASON_NULL;
4993 	imgp->ip_simulator_binary = IMGPF_SB_DEFAULT;
4994 	imgp->ip_subsystem_root_path = NULL;
4995 	uthread_set_exec_data(current_uthread(), imgp);
4996 
4997 #if CONFIG_MACF
4998 	if (uap->mac_p != USER_ADDR_NULL) {
4999 		error = mac_execve_enter(uap->mac_p, imgp);
5000 		if (error) {
5001 			goto exit_with_error;
5002 		}
5003 	}
5004 #endif
5005 	uthread = current_uthread();
5006 	{
5007 		imgp->ip_flags |= IMGPF_EXEC;
5008 
5009 		/* Adjust the user proc count */
5010 		(void)chgproccnt(kauth_getruid(), 1);
5011 		/*
5012 		 * For execve case, create a new proc, task and thread
5013 		 * but don't make the proc visible to userland. After
5014 		 * image activation, the new proc would take place of
5015 		 * the old proc in pid hash and other lists that make
5016 		 * the proc visible to the system.
5017 		 */
5018 		imgp->ip_new_thread = cloneproc(old_task, NULL, p, CLONEPROC_FLAGS_FOR_EXEC);
5019 		/* task and thread ref returned by cloneproc */
5020 		if (imgp->ip_new_thread == NULL) {
5021 			(void)chgproccnt(kauth_getruid(), -1);
5022 			error = ENOMEM;
5023 			goto exit_with_error;
5024 		}
5025 
5026 		new_task = get_threadtask(imgp->ip_new_thread);
5027 	}
5028 
5029 	p = (proc_t)get_bsdthreadtask_info(imgp->ip_new_thread);
5030 
5031 	context.vc_thread = imgp->ip_new_thread;
5032 	context.vc_ucred = kauth_cred_proc_ref(p);      /* XXX must NOT be kauth_cred_get() */
5033 
5034 	imgp->ip_subsystem_root_path = p->p_subsystem_root_path;
5035 
5036 	proc_transend(p, 0);
5037 	proc_signalend(p, 0);
5038 
5039 	/*
5040 	 * Activate the image.
5041 	 * Warning: If activation failed after point of no return, it returns error
5042 	 * as 0 and pretends the call succeeded.
5043 	 */
5044 	error = exec_activate_image(imgp);
5045 	/* thread and task ref returned for vfexec case */
5046 
5047 	if (imgp->ip_new_thread != NULL) {
5048 		/*
5049 		 * task reference might be returned by exec_activate_image
5050 		 * for vfexec.
5051 		 */
5052 		new_task = get_threadtask(imgp->ip_new_thread);
5053 #if defined(HAS_APPLE_PAC)
5054 		ml_task_set_disable_user_jop(new_task, imgp->ip_flags & IMGPF_NOJOP ? TRUE : FALSE);
5055 		ml_thread_set_disable_user_jop(imgp->ip_new_thread, imgp->ip_flags & IMGPF_NOJOP ? TRUE : FALSE);
5056 #endif
5057 	}
5058 
5059 	if (!error) {
5060 		p = proc_exec_switch_task(current_proc(), p, old_task, new_task, imgp->ip_new_thread, &inherit);
5061 		/* proc ref returned */
5062 		should_release_proc_ref = TRUE;
5063 	}
5064 
5065 	kauth_cred_unref(&context.vc_ucred);
5066 
5067 	if (!error) {
5068 		exec_done = TRUE;
5069 		assert(imgp->ip_new_thread != NULL);
5070 		/*
5071 		 * Enable new task IPC access if exec_activate_image() returned an
5072 		 * active task. (Checks active bit in ipc_task_enable() under lock).
5073 		 */
5074 		ipc_task_enable(new_task);
5075 
5076 		exec_resettextvp(p, imgp);
5077 		error = process_signature(p, imgp);
5078 	}
5079 
5080 #if defined(HAS_APPLE_PAC)
5081 	if (imgp->ip_new_thread && !error) {
5082 		ml_task_set_jop_pid_from_shared_region(new_task);
5083 		ml_thread_set_jop_pid(imgp->ip_new_thread, new_task);
5084 	}
5085 #endif /* defined(HAS_APPLE_PAC) */
5086 
5087 	/* flag exec has occurred, notify only if it has not failed due to FP Key error */
5088 	if (exec_done && ((p->p_lflag & P_LTERM_DECRYPTFAIL) == 0)) {
5089 		proc_knote(p, NOTE_EXEC);
5090 	}
5091 
5092 	if (imgp->ip_vp != NULLVP) {
5093 		vnode_put(imgp->ip_vp);
5094 	}
5095 	if (imgp->ip_scriptvp != NULLVP) {
5096 		vnode_put(imgp->ip_scriptvp);
5097 	}
5098 	if (imgp->ip_free_map) {
5099 		/* Free the map after dropping iocount on vnode to avoid deadlock */
5100 		vm_map_deallocate(imgp->ip_free_map);
5101 	}
5102 	if (imgp->ip_strings) {
5103 		execargs_free(imgp);
5104 	}
5105 #if CONFIG_MACF
5106 	if (imgp->ip_execlabelp) {
5107 		mac_cred_label_free(imgp->ip_execlabelp);
5108 		imgp->ip_execlabelp = NULL;
5109 	}
5110 	if (imgp->ip_scriptlabelp) {
5111 		mac_vnode_label_free(imgp->ip_scriptlabelp);
5112 		imgp->ip_scriptlabelp = NULL;
5113 	}
5114 #endif
5115 	if (imgp->ip_cs_error != OS_REASON_NULL) {
5116 		os_reason_free(imgp->ip_cs_error);
5117 		imgp->ip_cs_error = OS_REASON_NULL;
5118 	}
5119 
5120 	if (!error) {
5121 		/*
5122 		 * We need to initialize the bank context behind the protection of
5123 		 * the proc_trans lock to prevent a race with exit. We can't do this during
5124 		 * exec_activate_image because task_bank_init checks entitlements that
5125 		 * aren't loaded until subsequent calls (including exec_resettextvp).
5126 		 */
5127 		error = proc_transstart(p, 0, 0);
5128 	}
5129 
5130 	if (!error) {
5131 		task_bank_init(new_task);
5132 		proc_transend(p, 0);
5133 
5134 		// Don't inherit crash behavior across exec
5135 		p->p_crash_behavior = 0;
5136 		p->p_crash_behavior_deadline = 0;
5137 
5138 #if __arm64__
5139 		proc_footprint_entitlement_hacks(p, new_task);
5140 #endif /* __arm64__ */
5141 
5142 #if XNU_TARGET_OS_OSX
5143 		if (IOTaskHasEntitlement(new_task, SINGLE_JIT_ENTITLEMENT)) {
5144 			vm_map_single_jit(get_task_map(new_task));
5145 		}
5146 #endif /* XNU_TARGET_OS_OSX */
5147 
5148 		/* Sever any extant thread affinity */
5149 		thread_affinity_exec(current_thread());
5150 
5151 		/* Inherit task role from old task to new task for exec */
5152 		proc_inherit_task_role(new_task, old_task);
5153 
5154 		thread_t main_thread = imgp->ip_new_thread;
5155 
5156 		task_set_main_thread_qos(new_task, main_thread);
5157 
5158 #if __has_feature(ptrauth_calls)
5159 		task_set_pac_exception_fatal_flag(new_task);
5160 #endif /* __has_feature(ptrauth_calls) */
5161 
5162 #if CONFIG_ARCADE
5163 		/*
5164 		 * Check to see if we need to trigger an arcade upcall AST now
5165 		 * that the vnode has been reset on the task.
5166 		 */
5167 		arcade_prepare(new_task, imgp->ip_new_thread);
5168 #endif /* CONFIG_ARCADE */
5169 
5170 		proc_apply_jit_and_vm_policies(imgp, p, new_task);
5171 
5172 		if (vm_darkwake_mode == TRUE) {
5173 			/*
5174 			 * This process is being launched when the system
5175 			 * is in darkwake. So mark it specially. This will
5176 			 * cause all its pages to be entered in the background Q.
5177 			 */
5178 			task_set_darkwake_mode(new_task, vm_darkwake_mode);
5179 		}
5180 
5181 #if CONFIG_DTRACE
5182 		dtrace_thread_didexec(imgp->ip_new_thread);
5183 
5184 		if ((dtrace_proc_waitfor_hook = dtrace_proc_waitfor_exec_ptr) != NULL) {
5185 			(*dtrace_proc_waitfor_hook)(p);
5186 		}
5187 #endif
5188 
5189 #if CONFIG_AUDIT
5190 		if (!error && AUDIT_ENABLED() && p) {
5191 			/* Add the CDHash of the new process to the audit record */
5192 			uint8_t *cdhash = cs_get_cdhash(p);
5193 			if (cdhash) {
5194 				AUDIT_ARG(data, cdhash, sizeof(uint8_t), CS_CDHASH_LEN);
5195 			}
5196 		}
5197 #endif
5198 	} else {
5199 		DTRACE_PROC1(exec__failure, int, error);
5200 	}
5201 
5202 exit_with_error:
5203 
5204 	/* terminate the new task it if exec failed  */
5205 	if (new_task != NULL && task_is_exec_copy(new_task)) {
5206 		task_terminate_internal(new_task);
5207 	}
5208 
5209 	if (imgp != NULL) {
5210 		/* Clear the initial wait on the thread transferring watchports */
5211 		if (imgp->ip_new_thread) {
5212 			task_clear_return_wait(get_threadtask(imgp->ip_new_thread), TCRW_CLEAR_INITIAL_WAIT);
5213 		}
5214 
5215 		/* Transfer the watchport boost to new task */
5216 		if (!error) {
5217 			task_transfer_turnstile_watchports(old_task,
5218 			    new_task, imgp->ip_new_thread);
5219 		}
5220 		/*
5221 		 * Do not terminate the current task, if proc_exec_switch_task did not
5222 		 * switch the tasks, terminating the current task without the switch would
5223 		 * result in loosing the SIGKILL status.
5224 		 */
5225 		if (task_did_exec(old_task)) {
5226 			/* Terminate the current task, since exec will start in new task */
5227 			task_terminate_internal(old_task);
5228 		}
5229 
5230 		/* Release the thread ref returned by cloneproc */
5231 		if (imgp->ip_new_thread) {
5232 			/* clear the exec complete flag if there is an error before point of no-return */
5233 			uint32_t clearwait_flags = TCRW_CLEAR_FINAL_WAIT;
5234 			if (!exec_done && error != 0) {
5235 				clearwait_flags |= TCRW_CLEAR_EXEC_COMPLETE;
5236 			}
5237 			/* wake up the new exec thread */
5238 			task_clear_return_wait(get_threadtask(imgp->ip_new_thread), clearwait_flags);
5239 			thread_deallocate(imgp->ip_new_thread);
5240 			imgp->ip_new_thread = NULL;
5241 		}
5242 	}
5243 
5244 	/* Release the ref returned by fork_create_child */
5245 	if (new_task) {
5246 		task_deallocate(new_task);
5247 		new_task = NULL;
5248 	}
5249 
5250 	if (should_release_proc_ref) {
5251 		proc_rele(p);
5252 	}
5253 
5254 	uthread_set_exec_data(current_uthread(), NULL);
5255 	kfree_type(typeof(*__execve_data), __execve_data);
5256 
5257 	if (inherit != NULL) {
5258 		ipc_importance_release(inherit);
5259 	}
5260 
5261 	return error;
5262 }
5263 
5264 
5265 /*
5266  * copyinptr
5267  *
5268  * Description:	Copy a pointer in from user space to a user_addr_t in kernel
5269  *		space, based on 32/64 bitness of the user space
5270  *
5271  * Parameters:	froma			User space address
5272  *		toptr			Address of kernel space user_addr_t
5273  *		ptr_size		4/8, based on 'froma' address space
5274  *
5275  * Returns:	0			Success
5276  *		EFAULT			Bad 'froma'
5277  *
5278  * Implicit returns:
5279  *		*ptr_size		Modified
5280  */
5281 static int
copyinptr(user_addr_t froma,user_addr_t * toptr,int ptr_size)5282 copyinptr(user_addr_t froma, user_addr_t *toptr, int ptr_size)
5283 {
5284 	int error;
5285 
5286 	if (ptr_size == 4) {
5287 		/* 64 bit value containing 32 bit address */
5288 		unsigned int i = 0;
5289 
5290 		error = copyin(froma, &i, 4);
5291 		*toptr = CAST_USER_ADDR_T(i);   /* SAFE */
5292 	} else {
5293 		error = copyin(froma, toptr, 8);
5294 	}
5295 	return error;
5296 }
5297 
5298 
5299 /*
5300  * copyoutptr
5301  *
5302  * Description:	Copy a pointer out from a user_addr_t in kernel space to
5303  *		user space, based on 32/64 bitness of the user space
5304  *
5305  * Parameters:	ua			User space address to copy to
5306  *		ptr			Address of kernel space user_addr_t
5307  *		ptr_size		4/8, based on 'ua' address space
5308  *
5309  * Returns:	0			Success
5310  *		EFAULT			Bad 'ua'
5311  *
5312  */
5313 static int
copyoutptr(user_addr_t ua,user_addr_t ptr,int ptr_size)5314 copyoutptr(user_addr_t ua, user_addr_t ptr, int ptr_size)
5315 {
5316 	int error;
5317 
5318 	if (ptr_size == 4) {
5319 		/* 64 bit value containing 32 bit address */
5320 		unsigned int i = CAST_DOWN_EXPLICIT(unsigned int, ua);   /* SAFE */
5321 
5322 		error = copyout(&i, ptr, 4);
5323 	} else {
5324 		error = copyout(&ua, ptr, 8);
5325 	}
5326 	return error;
5327 }
5328 
5329 
5330 /*
5331  * exec_copyout_strings
5332  *
5333  * Copy out the strings segment to user space.  The strings segment is put
5334  * on a preinitialized stack frame.
5335  *
5336  * Parameters:	struct image_params *	the image parameter block
5337  *		int *			a pointer to the stack offset variable
5338  *
5339  * Returns:	0			Success
5340  *		!0			Faiure: errno
5341  *
5342  * Implicit returns:
5343  *		(*stackp)		The stack offset, modified
5344  *
5345  * Note:	The strings segment layout is backward, from the beginning
5346  *		of the top of the stack to consume the minimal amount of
5347  *		space possible; the returned stack pointer points to the
5348  *		end of the area consumed (stacks grow downward).
5349  *
5350  *		argc is an int; arg[i] are pointers; env[i] are pointers;
5351  *		the 0's are (void *)NULL's
5352  *
5353  * The stack frame layout is:
5354  *
5355  *      +-------------+ <- p->user_stack
5356  *      |     16b     |
5357  *      +-------------+
5358  *      | STRING AREA |
5359  *      |      :      |
5360  *      |      :      |
5361  *      |      :      |
5362  *      +- -- -- -- --+
5363  *      |  PATH AREA  |
5364  *      +-------------+
5365  *      |      0      |
5366  *      +-------------+
5367  *      |  applev[n]  |
5368  *      +-------------+
5369  *             :
5370  *             :
5371  *      +-------------+
5372  *      |  applev[1]  |
5373  *      +-------------+
5374  *      | exec_path / |
5375  *      |  applev[0]  |
5376  *      +-------------+
5377  *      |      0      |
5378  *      +-------------+
5379  *      |    env[n]   |
5380  *      +-------------+
5381  *             :
5382  *             :
5383  *      +-------------+
5384  *      |    env[0]   |
5385  *      +-------------+
5386  *      |      0      |
5387  *      +-------------+
5388  *      | arg[argc-1] |
5389  *      +-------------+
5390  *             :
5391  *             :
5392  *      +-------------+
5393  *      |    arg[0]   |
5394  *      +-------------+
5395  *      |     argc    |
5396  * sp-> +-------------+
5397  *
5398  * Although technically a part of the STRING AREA, we treat the PATH AREA as
5399  * a separate entity.  This allows us to align the beginning of the PATH AREA
5400  * to a pointer boundary so that the exec_path, env[i], and argv[i] pointers
5401  * which preceed it on the stack are properly aligned.
5402  */
5403 __attribute__((noinline))
5404 static int
exec_copyout_strings(struct image_params * imgp,user_addr_t * stackp)5405 exec_copyout_strings(struct image_params *imgp, user_addr_t *stackp)
5406 {
5407 	proc_t p = vfs_context_proc(imgp->ip_vfs_context);
5408 	int     ptr_size = (imgp->ip_flags & IMGPF_IS_64BIT_ADDR) ? 8 : 4;
5409 	int     ptr_area_size;
5410 	void *ptr_buffer_start, *ptr_buffer;
5411 	size_t string_size;
5412 
5413 	user_addr_t     string_area;    /* *argv[], *env[] */
5414 	user_addr_t     ptr_area;       /* argv[], env[], applev[] */
5415 	user_addr_t argc_area;  /* argc */
5416 	user_addr_t     stack;
5417 	int error;
5418 
5419 	unsigned i;
5420 	struct copyout_desc {
5421 		char    *start_string;
5422 		int             count;
5423 #if CONFIG_DTRACE
5424 		user_addr_t     *dtrace_cookie;
5425 #endif
5426 		boolean_t       null_term;
5427 	} descriptors[] = {
5428 		{
5429 			.start_string = imgp->ip_startargv,
5430 			.count = imgp->ip_argc,
5431 #if CONFIG_DTRACE
5432 			.dtrace_cookie = &p->p_dtrace_argv,
5433 #endif
5434 			.null_term = TRUE
5435 		},
5436 		{
5437 			.start_string = imgp->ip_endargv,
5438 			.count = imgp->ip_envc,
5439 #if CONFIG_DTRACE
5440 			.dtrace_cookie = &p->p_dtrace_envp,
5441 #endif
5442 			.null_term = TRUE
5443 		},
5444 		{
5445 			.start_string = imgp->ip_strings,
5446 			.count = 1,
5447 #if CONFIG_DTRACE
5448 			.dtrace_cookie = NULL,
5449 #endif
5450 			.null_term = FALSE
5451 		},
5452 		{
5453 			.start_string = imgp->ip_endenvv,
5454 			.count = imgp->ip_applec - 1, /* exec_path handled above */
5455 #if CONFIG_DTRACE
5456 			.dtrace_cookie = NULL,
5457 #endif
5458 			.null_term = TRUE
5459 		}
5460 	};
5461 
5462 	stack = *stackp;
5463 
5464 	/*
5465 	 * All previous contributors to the string area
5466 	 * should have aligned their sub-area
5467 	 */
5468 	if (imgp->ip_strspace % ptr_size != 0) {
5469 		error = EINVAL;
5470 		goto bad;
5471 	}
5472 
5473 	/* Grow the stack down for the strings we've been building up */
5474 	string_size = imgp->ip_strendp - imgp->ip_strings;
5475 	stack -= string_size;
5476 	string_area = stack;
5477 
5478 	/*
5479 	 * Need room for one pointer for each string, plus
5480 	 * one for the NULLs terminating the argv, envv, and apple areas.
5481 	 */
5482 	ptr_area_size = (imgp->ip_argc + imgp->ip_envc + imgp->ip_applec + 3) * ptr_size;
5483 	stack -= ptr_area_size;
5484 	ptr_area = stack;
5485 
5486 	/* We'll construct all the pointer arrays in our string buffer,
5487 	 * which we already know is aligned properly, and ip_argspace
5488 	 * was used to verify we have enough space.
5489 	 */
5490 	ptr_buffer_start = ptr_buffer = (void *)imgp->ip_strendp;
5491 
5492 	/*
5493 	 * Need room for pointer-aligned argc slot.
5494 	 */
5495 	stack -= ptr_size;
5496 	argc_area = stack;
5497 
5498 	/*
5499 	 * Record the size of the arguments area so that sysctl_procargs()
5500 	 * can return the argument area without having to parse the arguments.
5501 	 */
5502 	proc_lock(p);
5503 	p->p_argc = imgp->ip_argc;
5504 	p->p_argslen = (int)(*stackp - string_area);
5505 	proc_unlock(p);
5506 
5507 	/* Return the initial stack address: the location of argc */
5508 	*stackp = stack;
5509 
5510 	/*
5511 	 * Copy out the entire strings area.
5512 	 */
5513 	error = copyout(imgp->ip_strings, string_area,
5514 	    string_size);
5515 	if (error) {
5516 		goto bad;
5517 	}
5518 
5519 	for (i = 0; i < sizeof(descriptors) / sizeof(descriptors[0]); i++) {
5520 		char *cur_string = descriptors[i].start_string;
5521 		int j;
5522 
5523 #if CONFIG_DTRACE
5524 		if (descriptors[i].dtrace_cookie) {
5525 			proc_lock(p);
5526 			*descriptors[i].dtrace_cookie = ptr_area + ((uintptr_t)ptr_buffer - (uintptr_t)ptr_buffer_start); /* dtrace convenience */
5527 			proc_unlock(p);
5528 		}
5529 #endif /* CONFIG_DTRACE */
5530 
5531 		/*
5532 		 * For each segment (argv, envv, applev), copy as many pointers as requested
5533 		 * to our pointer buffer.
5534 		 */
5535 		for (j = 0; j < descriptors[i].count; j++) {
5536 			user_addr_t cur_address = string_area + (cur_string - imgp->ip_strings);
5537 
5538 			/* Copy out the pointer to the current string. Alignment has been verified  */
5539 			if (ptr_size == 8) {
5540 				*(uint64_t *)ptr_buffer = (uint64_t)cur_address;
5541 			} else {
5542 				*(uint32_t *)ptr_buffer = (uint32_t)cur_address;
5543 			}
5544 
5545 			ptr_buffer = (void *)((uintptr_t)ptr_buffer + ptr_size);
5546 			cur_string += strlen(cur_string) + 1; /* Only a NUL between strings in the same area */
5547 		}
5548 
5549 		if (descriptors[i].null_term) {
5550 			if (ptr_size == 8) {
5551 				*(uint64_t *)ptr_buffer = 0ULL;
5552 			} else {
5553 				*(uint32_t *)ptr_buffer = 0;
5554 			}
5555 
5556 			ptr_buffer = (void *)((uintptr_t)ptr_buffer + ptr_size);
5557 		}
5558 	}
5559 
5560 	/*
5561 	 * Copy out all our pointer arrays in bulk.
5562 	 */
5563 	error = copyout(ptr_buffer_start, ptr_area,
5564 	    ptr_area_size);
5565 	if (error) {
5566 		goto bad;
5567 	}
5568 
5569 	/* argc (int32, stored in a ptr_size area) */
5570 	error = copyoutptr((user_addr_t)imgp->ip_argc, argc_area, ptr_size);
5571 	if (error) {
5572 		goto bad;
5573 	}
5574 
5575 bad:
5576 	return error;
5577 }
5578 
5579 
5580 /*
5581  * exec_extract_strings
5582  *
5583  * Copy arguments and environment from user space into work area; we may
5584  * have already copied some early arguments into the work area, and if
5585  * so, any arguments opied in are appended to those already there.
5586  * This function is the primary manipulator of ip_argspace, since
5587  * these are the arguments the client of execve(2) knows about. After
5588  * each argv[]/envv[] string is copied, we charge the string length
5589  * and argv[]/envv[] pointer slot to ip_argspace, so that we can
5590  * full preflight the arg list size.
5591  *
5592  * Parameters:	struct image_params *	the image parameter block
5593  *
5594  * Returns:	0			Success
5595  *		!0			Failure: errno
5596  *
5597  * Implicit returns;
5598  *		(imgp->ip_argc)		Count of arguments, updated
5599  *		(imgp->ip_envc)		Count of environment strings, updated
5600  *		(imgp->ip_argspace)	Count of remaining of NCARGS
5601  *		(imgp->ip_interp_buffer)	Interpreter and args (mutated in place)
5602  *
5603  *
5604  * Note:	The argument and environment vectors are user space pointers
5605  *		to arrays of user space pointers.
5606  */
5607 __attribute__((noinline))
5608 static int
exec_extract_strings(struct image_params * imgp)5609 exec_extract_strings(struct image_params *imgp)
5610 {
5611 	int error = 0;
5612 	int     ptr_size = (imgp->ip_flags & IMGPF_WAS_64BIT_ADDR) ? 8 : 4;
5613 	int new_ptr_size = (imgp->ip_flags & IMGPF_IS_64BIT_ADDR) ? 8 : 4;
5614 	user_addr_t     argv = imgp->ip_user_argv;
5615 	user_addr_t     envv = imgp->ip_user_envv;
5616 
5617 	/*
5618 	 * Adjust space reserved for the path name by however much padding it
5619 	 * needs. Doing this here since we didn't know if this would be a 32-
5620 	 * or 64-bit process back in exec_save_path.
5621 	 */
5622 	while (imgp->ip_strspace % new_ptr_size != 0) {
5623 		*imgp->ip_strendp++ = '\0';
5624 		imgp->ip_strspace--;
5625 		/* imgp->ip_argspace--; not counted towards exec args total */
5626 	}
5627 
5628 	/*
5629 	 * From now on, we start attributing string space to ip_argspace
5630 	 */
5631 	imgp->ip_startargv = imgp->ip_strendp;
5632 	imgp->ip_argc = 0;
5633 
5634 	if ((imgp->ip_flags & IMGPF_INTERPRET) != 0) {
5635 		user_addr_t     arg;
5636 		char *argstart, *ch;
5637 
5638 		/* First, the arguments in the "#!" string are tokenized and extracted. */
5639 		argstart = imgp->ip_interp_buffer;
5640 		while (argstart) {
5641 			ch = argstart;
5642 			while (*ch && !IS_WHITESPACE(*ch)) {
5643 				ch++;
5644 			}
5645 
5646 			if (*ch == '\0') {
5647 				/* last argument, no need to NUL-terminate */
5648 				error = exec_add_user_string(imgp, CAST_USER_ADDR_T(argstart), UIO_SYSSPACE, TRUE);
5649 				argstart = NULL;
5650 			} else {
5651 				/* NUL-terminate */
5652 				*ch = '\0';
5653 				error = exec_add_user_string(imgp, CAST_USER_ADDR_T(argstart), UIO_SYSSPACE, TRUE);
5654 
5655 				/*
5656 				 * Find the next string. We know spaces at the end of the string have already
5657 				 * been stripped.
5658 				 */
5659 				argstart = ch + 1;
5660 				while (IS_WHITESPACE(*argstart)) {
5661 					argstart++;
5662 				}
5663 			}
5664 
5665 			/* Error-check, regardless of whether this is the last interpreter arg or not */
5666 			if (error) {
5667 				goto bad;
5668 			}
5669 			if (imgp->ip_argspace < new_ptr_size) {
5670 				error = E2BIG;
5671 				goto bad;
5672 			}
5673 			imgp->ip_argspace -= new_ptr_size; /* to hold argv[] entry */
5674 			imgp->ip_argc++;
5675 		}
5676 
5677 		if (argv != 0LL) {
5678 			/*
5679 			 * If we are running an interpreter, replace the av[0] that was
5680 			 * passed to execve() with the path name that was
5681 			 * passed to execve() for interpreters which do not use the PATH
5682 			 * to locate their script arguments.
5683 			 */
5684 			error = copyinptr(argv, &arg, ptr_size);
5685 			if (error) {
5686 				goto bad;
5687 			}
5688 			if (arg != 0LL) {
5689 				argv += ptr_size; /* consume without using */
5690 			}
5691 		}
5692 
5693 		if (imgp->ip_interp_sugid_fd != -1) {
5694 			char temp[19]; /* "/dev/fd/" + 10 digits + NUL */
5695 			snprintf(temp, sizeof(temp), "/dev/fd/%d", imgp->ip_interp_sugid_fd);
5696 			error = exec_add_user_string(imgp, CAST_USER_ADDR_T(temp), UIO_SYSSPACE, TRUE);
5697 		} else {
5698 			error = exec_add_user_string(imgp, imgp->ip_user_fname, imgp->ip_seg, TRUE);
5699 		}
5700 
5701 		if (error) {
5702 			goto bad;
5703 		}
5704 		if (imgp->ip_argspace < new_ptr_size) {
5705 			error = E2BIG;
5706 			goto bad;
5707 		}
5708 		imgp->ip_argspace -= new_ptr_size; /* to hold argv[] entry */
5709 		imgp->ip_argc++;
5710 	}
5711 
5712 	while (argv != 0LL) {
5713 		user_addr_t     arg;
5714 
5715 		error = copyinptr(argv, &arg, ptr_size);
5716 		if (error) {
5717 			goto bad;
5718 		}
5719 
5720 		if (arg == 0LL) {
5721 			break;
5722 		}
5723 
5724 		argv += ptr_size;
5725 
5726 		/*
5727 		 * av[n...] = arg[n]
5728 		 */
5729 		error = exec_add_user_string(imgp, arg, imgp->ip_seg, TRUE);
5730 		if (error) {
5731 			goto bad;
5732 		}
5733 		if (imgp->ip_argspace < new_ptr_size) {
5734 			error = E2BIG;
5735 			goto bad;
5736 		}
5737 		imgp->ip_argspace -= new_ptr_size; /* to hold argv[] entry */
5738 		imgp->ip_argc++;
5739 	}
5740 
5741 	/* Save space for argv[] NULL terminator */
5742 	if (imgp->ip_argspace < new_ptr_size) {
5743 		error = E2BIG;
5744 		goto bad;
5745 	}
5746 	imgp->ip_argspace -= new_ptr_size;
5747 
5748 	/* Note where the args ends and env begins. */
5749 	imgp->ip_endargv = imgp->ip_strendp;
5750 	imgp->ip_envc = 0;
5751 
5752 	/* Now, get the environment */
5753 	while (envv != 0LL) {
5754 		user_addr_t     env;
5755 
5756 		error = copyinptr(envv, &env, ptr_size);
5757 		if (error) {
5758 			goto bad;
5759 		}
5760 
5761 		envv += ptr_size;
5762 		if (env == 0LL) {
5763 			break;
5764 		}
5765 		/*
5766 		 * av[n...] = env[n]
5767 		 */
5768 		error = exec_add_user_string(imgp, env, imgp->ip_seg, TRUE);
5769 		if (error) {
5770 			goto bad;
5771 		}
5772 		if (imgp->ip_argspace < new_ptr_size) {
5773 			error = E2BIG;
5774 			goto bad;
5775 		}
5776 		imgp->ip_argspace -= new_ptr_size; /* to hold envv[] entry */
5777 		imgp->ip_envc++;
5778 	}
5779 
5780 	/* Save space for envv[] NULL terminator */
5781 	if (imgp->ip_argspace < new_ptr_size) {
5782 		error = E2BIG;
5783 		goto bad;
5784 	}
5785 	imgp->ip_argspace -= new_ptr_size;
5786 
5787 	/* Align the tail of the combined argv+envv area */
5788 	while (imgp->ip_strspace % new_ptr_size != 0) {
5789 		if (imgp->ip_argspace < 1) {
5790 			error = E2BIG;
5791 			goto bad;
5792 		}
5793 		*imgp->ip_strendp++ = '\0';
5794 		imgp->ip_strspace--;
5795 		imgp->ip_argspace--;
5796 	}
5797 
5798 	/* Note where the envv ends and applev begins. */
5799 	imgp->ip_endenvv = imgp->ip_strendp;
5800 
5801 	/*
5802 	 * From now on, we are no longer charging argument
5803 	 * space to ip_argspace.
5804 	 */
5805 
5806 bad:
5807 	return error;
5808 }
5809 
5810 /*
5811  * Libc has an 8-element array set up for stack guard values.  It only fills
5812  * in one of those entries, and both gcc and llvm seem to use only a single
5813  * 8-byte guard.  Until somebody needs more than an 8-byte guard value, don't
5814  * do the work to construct them.
5815  */
5816 #define GUARD_VALUES 1
5817 #define GUARD_KEY "stack_guard="
5818 
5819 /*
5820  * System malloc needs some entropy when it is initialized.
5821  */
5822 #define ENTROPY_VALUES 2
5823 #define ENTROPY_KEY "malloc_entropy="
5824 
5825 /*
5826  * libplatform needs a random pointer-obfuscation value when it is initialized.
5827  */
5828 #define PTR_MUNGE_VALUES 1
5829 #define PTR_MUNGE_KEY "ptr_munge="
5830 
5831 /*
5832  * System malloc engages nanozone for UIAPP.
5833  */
5834 #define NANO_ENGAGE_KEY "MallocNanoZone=1"
5835 
5836 /*
5837  * System malloc uses deferred reclaim
5838  * for UIAPP on embedded systems with swap.
5839  */
5840 #define RECLAIM_ENGAGE_KEY "MallocDeferredReclaim=1"
5841 /*
5842  * Used to pass experiment flags up to libmalloc.
5843  */
5844 #define LIBMALLOC_EXPERIMENT_FACTORS_KEY "MallocExperiment="
5845 
5846 #define PFZ_KEY "pfz="
5847 extern user32_addr_t commpage_text32_location;
5848 extern user64_addr_t commpage_text64_location;
5849 
5850 extern uuid_string_t bootsessionuuid_string;
5851 static TUNABLE(uint32_t, exe_boothash_salt, "exe_boothash_salt", 0);
5852 
5853 __startup_func
5854 static void
exe_boothash_salt_generate(void)5855 exe_boothash_salt_generate(void)
5856 {
5857 	if (!PE_parse_boot_argn("exe_boothash_salt", NULL, 0)) {
5858 		read_random(&exe_boothash_salt, sizeof(exe_boothash_salt));
5859 	}
5860 }
5861 STARTUP(EARLY_BOOT, STARTUP_RANK_MIDDLE, exe_boothash_salt_generate);
5862 
5863 
5864 #define MAIN_STACK_VALUES 4
5865 #define MAIN_STACK_KEY "main_stack="
5866 
5867 #define FSID_KEY "executable_file="
5868 #define DYLD_FSID_KEY "dyld_file="
5869 #define CDHASH_KEY "executable_cdhash="
5870 #define DYLD_FLAGS_KEY "dyld_flags="
5871 #define SUBSYSTEM_ROOT_PATH_KEY "subsystem_root_path="
5872 #define APP_BOOT_SESSION_KEY "executable_boothash="
5873 #if __has_feature(ptrauth_calls)
5874 #define PTRAUTH_DISABLED_FLAG "ptrauth_disabled=1"
5875 #define DYLD_ARM64E_ABI_KEY "arm64e_abi="
5876 #endif /* __has_feature(ptrauth_calls) */
5877 #define MAIN_TH_PORT_KEY "th_port="
5878 
5879 #define FSID_MAX_STRING "0x1234567890abcdef,0x1234567890abcdef"
5880 
5881 #define HEX_STR_LEN 18 // 64-bit hex value "0x0123456701234567"
5882 #define HEX_STR_LEN32 10 // 32-bit hex value "0x01234567"
5883 
5884 #if XNU_TARGET_OS_OSX && _POSIX_SPAWN_FORCE_4K_PAGES && PMAP_CREATE_FORCE_4K_PAGES
5885 #define VM_FORCE_4K_PAGES_KEY "vm_force_4k_pages=1"
5886 #endif /* XNU_TARGET_OS_OSX && _POSIX_SPAWN_FORCE_4K_PAGES && PMAP_CREATE_FORCE_4K_PAGES */
5887 
5888 static int
exec_add_entropy_key(struct image_params * imgp,const char * key,int values,boolean_t embedNUL)5889 exec_add_entropy_key(struct image_params *imgp,
5890     const char *key,
5891     int values,
5892     boolean_t embedNUL)
5893 {
5894 	const int limit = 8;
5895 	uint64_t entropy[limit];
5896 	char str[strlen(key) + (HEX_STR_LEN + 1) * limit + 1];
5897 	if (values > limit) {
5898 		values = limit;
5899 	}
5900 
5901 	read_random(entropy, sizeof(entropy[0]) * values);
5902 
5903 	if (embedNUL) {
5904 		entropy[0] &= ~(0xffull << 8);
5905 	}
5906 
5907 	int len = scnprintf(str, sizeof(str), "%s0x%llx", key, entropy[0]);
5908 	size_t remaining = sizeof(str) - len;
5909 	for (int i = 1; i < values && remaining > 0; ++i) {
5910 		size_t start = sizeof(str) - remaining;
5911 		len = scnprintf(&str[start], remaining, ",0x%llx", entropy[i]);
5912 		remaining -= len;
5913 	}
5914 
5915 	return exec_add_user_string(imgp, CAST_USER_ADDR_T(str), UIO_SYSSPACE, FALSE);
5916 }
5917 
5918 /*
5919  * Build up the contents of the apple[] string vector
5920  */
5921 #if (DEVELOPMENT || DEBUG)
5922 extern uint64_t dyld_flags;
5923 #endif
5924 
5925 #if __has_feature(ptrauth_calls)
5926 static inline bool
is_arm64e_running_as_arm64(const struct image_params * imgp)5927 is_arm64e_running_as_arm64(const struct image_params *imgp)
5928 {
5929 	return (imgp->ip_origcpusubtype & ~CPU_SUBTYPE_MASK) == CPU_SUBTYPE_ARM64E &&
5930 	       (imgp->ip_flags & IMGPF_NOJOP);
5931 }
5932 #endif /* __has_feature(ptrauth_calls) */
5933 
5934 _Atomic uint64_t libmalloc_experiment_factors = 0;
5935 
5936 static int
exec_add_apple_strings(struct image_params * imgp,const load_result_t * load_result)5937 exec_add_apple_strings(struct image_params *imgp,
5938     const load_result_t *load_result)
5939 {
5940 	int error;
5941 	int img_ptr_size = (imgp->ip_flags & IMGPF_IS_64BIT_ADDR) ? 8 : 4;
5942 	thread_t new_thread;
5943 	ipc_port_t sright;
5944 	uint64_t local_experiment_factors = 0;
5945 
5946 	/* exec_save_path stored the first string */
5947 	imgp->ip_applec = 1;
5948 
5949 	/* adding the pfz string */
5950 	{
5951 		char pfz_string[strlen(PFZ_KEY) + HEX_STR_LEN + 1];
5952 
5953 		if (img_ptr_size == 8) {
5954 			__assert_only size_t ret = snprintf(pfz_string, sizeof(pfz_string), PFZ_KEY "0x%llx", commpage_text64_location);
5955 			assert(ret < sizeof(pfz_string));
5956 		} else {
5957 			snprintf(pfz_string, sizeof(pfz_string), PFZ_KEY "0x%x", commpage_text32_location);
5958 		}
5959 		error = exec_add_user_string(imgp, CAST_USER_ADDR_T(pfz_string), UIO_SYSSPACE, FALSE);
5960 		if (error) {
5961 			printf("Failed to add the pfz string with error %d\n", error);
5962 			goto bad;
5963 		}
5964 		imgp->ip_applec++;
5965 	}
5966 
5967 	/* adding the NANO_ENGAGE_KEY key */
5968 	if (imgp->ip_px_sa) {
5969 		struct _posix_spawnattr* psa = (struct _posix_spawnattr *) imgp->ip_px_sa;
5970 		int proc_flags = psa->psa_flags;
5971 
5972 		if ((proc_flags & _POSIX_SPAWN_NANO_ALLOCATOR) == _POSIX_SPAWN_NANO_ALLOCATOR) {
5973 			const char *nano_string = NANO_ENGAGE_KEY;
5974 			error = exec_add_user_string(imgp, CAST_USER_ADDR_T(nano_string), UIO_SYSSPACE, FALSE);
5975 			if (error) {
5976 				goto bad;
5977 			}
5978 			imgp->ip_applec++;
5979 		}
5980 #if CONFIG_JETSAM && CONFIG_MEMORYSTATUS && CONFIG_DEFERRED_RECLAIM
5981 		if (vm_reclaim_max_threshold > 0) {
5982 			int psa_apptype = psa->psa_apptype;
5983 
5984 			if ((psa_apptype & POSIX_SPAWN_PROC_TYPE_MASK) == POSIX_SPAWN_PROC_TYPE_APP_DEFAULT) {
5985 				const char *reclaim_string = RECLAIM_ENGAGE_KEY;
5986 				error = exec_add_user_string(imgp, CAST_USER_ADDR_T(reclaim_string), UIO_SYSSPACE, FALSE);
5987 				if (error) {
5988 					goto bad;
5989 				}
5990 				imgp->ip_applec++;
5991 			}
5992 		}
5993 #endif /* CONFIG_JETSAM && CONFIG_MEMORYSTATUS && CONFIG_DEFERRED_RECLAIM */
5994 	}
5995 
5996 	/*
5997 	 * Supply libc with a collection of random values to use when
5998 	 * implementing -fstack-protector.
5999 	 *
6000 	 * (The first random string always contains an embedded NUL so that
6001 	 * __stack_chk_guard also protects against C string vulnerabilities)
6002 	 */
6003 	error = exec_add_entropy_key(imgp, GUARD_KEY, GUARD_VALUES, TRUE);
6004 	if (error) {
6005 		goto bad;
6006 	}
6007 	imgp->ip_applec++;
6008 
6009 	/*
6010 	 * Supply libc with entropy for system malloc.
6011 	 */
6012 	error = exec_add_entropy_key(imgp, ENTROPY_KEY, ENTROPY_VALUES, FALSE);
6013 	if (error) {
6014 		goto bad;
6015 	}
6016 	imgp->ip_applec++;
6017 
6018 	/*
6019 	 * Supply libpthread & libplatform with a random value to use for pointer
6020 	 * obfuscation.
6021 	 */
6022 	error = exec_add_entropy_key(imgp, PTR_MUNGE_KEY, PTR_MUNGE_VALUES, FALSE);
6023 	if (error) {
6024 		goto bad;
6025 	}
6026 	imgp->ip_applec++;
6027 
6028 	/*
6029 	 * Add MAIN_STACK_KEY: Supplies the address and size of the main thread's
6030 	 * stack if it was allocated by the kernel.
6031 	 *
6032 	 * The guard page is not included in this stack size as libpthread
6033 	 * expects to add it back in after receiving this value.
6034 	 */
6035 	if (load_result->unixproc) {
6036 		char stack_string[strlen(MAIN_STACK_KEY) + (HEX_STR_LEN + 1) * MAIN_STACK_VALUES + 1];
6037 		snprintf(stack_string, sizeof(stack_string),
6038 		    MAIN_STACK_KEY "0x%llx,0x%llx,0x%llx,0x%llx",
6039 		    (uint64_t)load_result->user_stack,
6040 		    (uint64_t)load_result->user_stack_size,
6041 		    (uint64_t)load_result->user_stack_alloc,
6042 		    (uint64_t)load_result->user_stack_alloc_size);
6043 		error = exec_add_user_string(imgp, CAST_USER_ADDR_T(stack_string), UIO_SYSSPACE, FALSE);
6044 		if (error) {
6045 			goto bad;
6046 		}
6047 		imgp->ip_applec++;
6048 	}
6049 
6050 	if (imgp->ip_vattr) {
6051 		uint64_t fsid    = vnode_get_va_fsid(imgp->ip_vattr);
6052 		uint64_t fsobjid = imgp->ip_vattr->va_fileid;
6053 
6054 		char fsid_string[strlen(FSID_KEY) + strlen(FSID_MAX_STRING) + 1];
6055 		snprintf(fsid_string, sizeof(fsid_string),
6056 		    FSID_KEY "0x%llx,0x%llx", fsid, fsobjid);
6057 		error = exec_add_user_string(imgp, CAST_USER_ADDR_T(fsid_string), UIO_SYSSPACE, FALSE);
6058 		if (error) {
6059 			goto bad;
6060 		}
6061 		imgp->ip_applec++;
6062 	}
6063 
6064 	if (imgp->ip_dyld_fsid || imgp->ip_dyld_fsobjid) {
6065 		char fsid_string[strlen(DYLD_FSID_KEY) + strlen(FSID_MAX_STRING) + 1];
6066 		snprintf(fsid_string, sizeof(fsid_string),
6067 		    DYLD_FSID_KEY "0x%llx,0x%llx", imgp->ip_dyld_fsid, imgp->ip_dyld_fsobjid);
6068 		error = exec_add_user_string(imgp, CAST_USER_ADDR_T(fsid_string), UIO_SYSSPACE, FALSE);
6069 		if (error) {
6070 			goto bad;
6071 		}
6072 		imgp->ip_applec++;
6073 	}
6074 
6075 	uint8_t cdhash[SHA1_RESULTLEN];
6076 	int cdhash_errror = ubc_cs_getcdhash(imgp->ip_vp, imgp->ip_arch_offset, cdhash);
6077 	if (cdhash_errror == 0) {
6078 		char hash_string[strlen(CDHASH_KEY) + 2 * SHA1_RESULTLEN + 1];
6079 		strncpy(hash_string, CDHASH_KEY, sizeof(hash_string));
6080 		char *p = hash_string + sizeof(CDHASH_KEY) - 1;
6081 		for (int i = 0; i < SHA1_RESULTLEN; i++) {
6082 			snprintf(p, 3, "%02x", (int) cdhash[i]);
6083 			p += 2;
6084 		}
6085 		error = exec_add_user_string(imgp, CAST_USER_ADDR_T(hash_string), UIO_SYSSPACE, FALSE);
6086 		if (error) {
6087 			goto bad;
6088 		}
6089 		imgp->ip_applec++;
6090 
6091 		/* hash together cd-hash and boot-session-uuid */
6092 		uint8_t sha_digest[SHA256_DIGEST_LENGTH];
6093 		SHA256_CTX sha_ctx;
6094 		SHA256_Init(&sha_ctx);
6095 		SHA256_Update(&sha_ctx, &exe_boothash_salt, sizeof(exe_boothash_salt));
6096 		SHA256_Update(&sha_ctx, bootsessionuuid_string, sizeof(bootsessionuuid_string));
6097 		SHA256_Update(&sha_ctx, cdhash, sizeof(cdhash));
6098 		SHA256_Final(sha_digest, &sha_ctx);
6099 		char app_boot_string[strlen(APP_BOOT_SESSION_KEY) + 2 * SHA1_RESULTLEN + 1];
6100 		strncpy(app_boot_string, APP_BOOT_SESSION_KEY, sizeof(app_boot_string));
6101 		char *s = app_boot_string + sizeof(APP_BOOT_SESSION_KEY) - 1;
6102 		for (int i = 0; i < SHA1_RESULTLEN; i++) {
6103 			snprintf(s, 3, "%02x", (int) sha_digest[i]);
6104 			s += 2;
6105 		}
6106 		error = exec_add_user_string(imgp, CAST_USER_ADDR_T(app_boot_string), UIO_SYSSPACE, FALSE);
6107 		if (error) {
6108 			goto bad;
6109 		}
6110 		imgp->ip_applec++;
6111 	}
6112 #if (DEVELOPMENT || DEBUG)
6113 	if (dyld_flags) {
6114 		char dyld_flags_string[strlen(DYLD_FLAGS_KEY) + HEX_STR_LEN + 1];
6115 		snprintf(dyld_flags_string, sizeof(dyld_flags_string), DYLD_FLAGS_KEY "0x%llx", dyld_flags);
6116 		error = exec_add_user_string(imgp, CAST_USER_ADDR_T(dyld_flags_string), UIO_SYSSPACE, FALSE);
6117 		if (error) {
6118 			goto bad;
6119 		}
6120 		imgp->ip_applec++;
6121 	}
6122 #endif
6123 	if (imgp->ip_subsystem_root_path) {
6124 		size_t buffer_len = MAXPATHLEN + strlen(SUBSYSTEM_ROOT_PATH_KEY);
6125 		char subsystem_root_path_string[buffer_len];
6126 		int required_len = snprintf(subsystem_root_path_string, buffer_len, SUBSYSTEM_ROOT_PATH_KEY "%s", imgp->ip_subsystem_root_path);
6127 
6128 		if (((size_t)required_len >= buffer_len) || (required_len < 0)) {
6129 			error = ENAMETOOLONG;
6130 			goto bad;
6131 		}
6132 
6133 		error = exec_add_user_string(imgp, CAST_USER_ADDR_T(subsystem_root_path_string), UIO_SYSSPACE, FALSE);
6134 		if (error) {
6135 			goto bad;
6136 		}
6137 
6138 		imgp->ip_applec++;
6139 	}
6140 #if __has_feature(ptrauth_calls)
6141 	if (is_arm64e_running_as_arm64(imgp)) {
6142 		error = exec_add_user_string(imgp, CAST_USER_ADDR_T(PTRAUTH_DISABLED_FLAG), UIO_SYSSPACE, FALSE);
6143 		if (error) {
6144 			goto bad;
6145 		}
6146 
6147 		imgp->ip_applec++;
6148 	}
6149 #endif /* __has_feature(ptrauth_calls) */
6150 
6151 
6152 #if __has_feature(ptrauth_calls) && defined(XNU_TARGET_OS_OSX)
6153 	{
6154 		char dyld_abi_string[strlen(DYLD_ARM64E_ABI_KEY) + 8];
6155 		strlcpy(dyld_abi_string, DYLD_ARM64E_ABI_KEY, sizeof(dyld_abi_string));
6156 		bool allowAll = bootarg_arm64e_preview_abi;
6157 		strlcat(dyld_abi_string, (allowAll ? "all" : "os"), sizeof(dyld_abi_string));
6158 		error = exec_add_user_string(imgp, CAST_USER_ADDR_T(dyld_abi_string), UIO_SYSSPACE, FALSE);
6159 		if (error) {
6160 			goto bad;
6161 		}
6162 
6163 		imgp->ip_applec++;
6164 	}
6165 #endif
6166 	/*
6167 	 * Add main thread mach port name
6168 	 * +1 uref on main thread port, this ref will be extracted by libpthread in __pthread_init
6169 	 * and consumed in _bsdthread_terminate. Leaking the main thread port name if not linked
6170 	 * against libpthread.
6171 	 */
6172 	if ((new_thread = imgp->ip_new_thread) != THREAD_NULL) {
6173 		thread_reference(new_thread);
6174 		sright = convert_thread_to_port_pinned(new_thread);
6175 		task_t new_task = get_threadtask(new_thread);
6176 		mach_port_name_t name = ipc_port_copyout_send(sright, get_task_ipcspace(new_task));
6177 		char port_name_hex_str[strlen(MAIN_TH_PORT_KEY) + HEX_STR_LEN32 + 1];
6178 		snprintf(port_name_hex_str, sizeof(port_name_hex_str), MAIN_TH_PORT_KEY "0x%x", name);
6179 
6180 		error = exec_add_user_string(imgp, CAST_USER_ADDR_T(port_name_hex_str), UIO_SYSSPACE, FALSE);
6181 		if (error) {
6182 			goto bad;
6183 		}
6184 		imgp->ip_applec++;
6185 	}
6186 
6187 #if XNU_TARGET_OS_OSX && _POSIX_SPAWN_FORCE_4K_PAGES && PMAP_CREATE_FORCE_4K_PAGES
6188 	if (imgp->ip_px_sa != NULL) {
6189 		struct _posix_spawnattr* psa = (struct _posix_spawnattr *) imgp->ip_px_sa;
6190 		if (psa->psa_flags & _POSIX_SPAWN_FORCE_4K_PAGES) {
6191 			const char *vm_force_4k_string = VM_FORCE_4K_PAGES_KEY;
6192 			error = exec_add_user_string(imgp, CAST_USER_ADDR_T(vm_force_4k_string), UIO_SYSSPACE, FALSE);
6193 			if (error) {
6194 				goto bad;
6195 			}
6196 			imgp->ip_applec++;
6197 		}
6198 	}
6199 #endif /* XNU_TARGET_OS_OSX && _POSIX_SPAWN_FORCE_4K_PAGES && PMAP_CREATE_FORCE_4K_PAGES */
6200 
6201 	/* adding the libmalloc experiment string */
6202 	local_experiment_factors = os_atomic_load_wide(&libmalloc_experiment_factors, relaxed);
6203 	if (__improbable(local_experiment_factors != 0)) {
6204 		char libmalloc_experiment_factors_string[strlen(LIBMALLOC_EXPERIMENT_FACTORS_KEY) + HEX_STR_LEN + 1];
6205 
6206 		snprintf(
6207 			libmalloc_experiment_factors_string,
6208 			sizeof(libmalloc_experiment_factors_string),
6209 			LIBMALLOC_EXPERIMENT_FACTORS_KEY "0x%llx",
6210 			local_experiment_factors);
6211 		error = exec_add_user_string(
6212 			imgp,
6213 			CAST_USER_ADDR_T(libmalloc_experiment_factors_string),
6214 			UIO_SYSSPACE,
6215 			FALSE);
6216 		if (error) {
6217 			printf("Failed to add the libmalloc experiment factors string with error %d\n", error);
6218 			goto bad;
6219 		}
6220 		imgp->ip_applec++;
6221 	}
6222 
6223 	/* tell dyld that it can leverage hardware for its read-only/read-write trusted path */
6224 	if (imgp->ip_flags & IMGPF_HW_TPRO) {
6225 		const char *dyld_hw_tpro = "dyld_hw_tpro=1";
6226 		error = exec_add_user_string(imgp, CAST_USER_ADDR_T(dyld_hw_tpro), UIO_SYSSPACE, FALSE);
6227 		if (error) {
6228 			printf("Failed to add dyld hw tpro setting with error %d\n", error);
6229 			goto bad;
6230 		}
6231 
6232 		imgp->ip_applec++;
6233 
6234 	}
6235 
6236 	/* Align the tail of the combined applev area */
6237 	while (imgp->ip_strspace % img_ptr_size != 0) {
6238 		*imgp->ip_strendp++ = '\0';
6239 		imgp->ip_strspace--;
6240 	}
6241 
6242 bad:
6243 	return error;
6244 }
6245 
6246 /*
6247  * exec_check_permissions
6248  *
6249  * Description:	Verify that the file that is being attempted to be executed
6250  *		is in fact allowed to be executed based on it POSIX file
6251  *		permissions and other access control criteria
6252  *
6253  * Parameters:	struct image_params *	the image parameter block
6254  *
6255  * Returns:	0			Success
6256  *		EACCES			Permission denied
6257  *		ENOEXEC			Executable file format error
6258  *		ETXTBSY			Text file busy [misuse of error code]
6259  *	vnode_getattr:???
6260  *	vnode_authorize:???
6261  */
6262 static int
exec_check_permissions(struct image_params * imgp)6263 exec_check_permissions(struct image_params *imgp)
6264 {
6265 	struct vnode *vp = imgp->ip_vp;
6266 	struct vnode_attr *vap = imgp->ip_vattr;
6267 	proc_t p = vfs_context_proc(imgp->ip_vfs_context);
6268 	int error;
6269 	kauth_action_t action;
6270 
6271 	/* Only allow execution of regular files */
6272 	if (!vnode_isreg(vp)) {
6273 		return EACCES;
6274 	}
6275 
6276 	/* Get the file attributes that we will be using here and elsewhere */
6277 	VATTR_INIT(vap);
6278 	VATTR_WANTED(vap, va_uid);
6279 	VATTR_WANTED(vap, va_gid);
6280 	VATTR_WANTED(vap, va_mode);
6281 	VATTR_WANTED(vap, va_fsid);
6282 	VATTR_WANTED(vap, va_fsid64);
6283 	VATTR_WANTED(vap, va_fileid);
6284 	VATTR_WANTED(vap, va_data_size);
6285 	if ((error = vnode_getattr(vp, vap, imgp->ip_vfs_context)) != 0) {
6286 		return error;
6287 	}
6288 
6289 	/*
6290 	 * Ensure that at least one execute bit is on - otherwise root
6291 	 * will always succeed, and we don't want to happen unless the
6292 	 * file really is executable.
6293 	 */
6294 	if (!vfs_authopaque(vnode_mount(vp)) && ((vap->va_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) == 0)) {
6295 		return EACCES;
6296 	}
6297 
6298 	/* Disallow zero length files */
6299 	if (vap->va_data_size == 0) {
6300 		return ENOEXEC;
6301 	}
6302 
6303 	imgp->ip_arch_offset = (user_size_t)0;
6304 #if __LP64__
6305 	imgp->ip_arch_size = vap->va_data_size;
6306 #else
6307 	if (vap->va_data_size > UINT32_MAX) {
6308 		return ENOEXEC;
6309 	}
6310 	imgp->ip_arch_size = (user_size_t)vap->va_data_size;
6311 #endif
6312 
6313 	/* Disable setuid-ness for traced programs or if MNT_NOSUID */
6314 	if ((vp->v_mount->mnt_flag & MNT_NOSUID) || (p->p_lflag & P_LTRACED)) {
6315 		vap->va_mode &= ~(VSUID | VSGID);
6316 	}
6317 
6318 	/*
6319 	 * Disable _POSIX_SPAWN_ALLOW_DATA_EXEC and _POSIX_SPAWN_DISABLE_ASLR
6320 	 * flags for setuid/setgid binaries.
6321 	 */
6322 	if (vap->va_mode & (VSUID | VSGID)) {
6323 		imgp->ip_flags &= ~(IMGPF_ALLOW_DATA_EXEC | IMGPF_DISABLE_ASLR);
6324 	}
6325 
6326 #if CONFIG_MACF
6327 	error = mac_vnode_check_exec(imgp->ip_vfs_context, vp, imgp);
6328 	if (error) {
6329 		return error;
6330 	}
6331 #endif
6332 
6333 	/* Check for execute permission */
6334 	action = KAUTH_VNODE_EXECUTE;
6335 	/* Traced images must also be readable */
6336 	if (p->p_lflag & P_LTRACED) {
6337 		action |= KAUTH_VNODE_READ_DATA;
6338 	}
6339 	if ((error = vnode_authorize(vp, NULL, action, imgp->ip_vfs_context)) != 0) {
6340 		return error;
6341 	}
6342 
6343 #if 0
6344 	/* Don't let it run if anyone had it open for writing */
6345 	vnode_lock(vp);
6346 	if (vp->v_writecount) {
6347 		panic("going to return ETXTBSY %x", vp);
6348 		vnode_unlock(vp);
6349 		return ETXTBSY;
6350 	}
6351 	vnode_unlock(vp);
6352 #endif
6353 
6354 	/* XXX May want to indicate to underlying FS that vnode is open */
6355 
6356 	return error;
6357 }
6358 
6359 
6360 /*
6361  * exec_handle_sugid
6362  *
6363  * Initially clear the P_SUGID in the process flags; if an SUGID process is
6364  * exec'ing a non-SUGID image, then  this is the point of no return.
6365  *
6366  * If the image being activated is SUGID, then replace the credential with a
6367  * copy, disable tracing (unless the tracing process is root), reset the
6368  * mach task port to revoke it, set the P_SUGID bit,
6369  *
6370  * If the saved user and group ID will be changing, then make sure it happens
6371  * to a new credential, rather than a shared one.
6372  *
6373  * Set the security token (this is probably obsolete, given that the token
6374  * should not technically be separate from the credential itself).
6375  *
6376  * Parameters:	struct image_params *	the image parameter block
6377  *
6378  * Returns:	void			No failure indication
6379  *
6380  * Implicit returns:
6381  *		<process credential>	Potentially modified/replaced
6382  *		<task port>		Potentially revoked
6383  *		<process flags>		P_SUGID bit potentially modified
6384  *		<security token>	Potentially modified
6385  */
6386 __attribute__((noinline))
6387 static int
exec_handle_sugid(struct image_params * imgp)6388 exec_handle_sugid(struct image_params *imgp)
6389 {
6390 	proc_t                  p = vfs_context_proc(imgp->ip_vfs_context);
6391 	kauth_cred_t            cred = vfs_context_ucred(imgp->ip_vfs_context);
6392 	int                     i;
6393 	int                     leave_sugid_clear = 0;
6394 	int                     mac_reset_ipc = 0;
6395 	int                     error = 0;
6396 #if CONFIG_MACF
6397 	int                     mac_transition, disjoint_cred = 0;
6398 	int             label_update_return = 0;
6399 
6400 	/*
6401 	 * Determine whether a call to update the MAC label will result in the
6402 	 * credential changing.
6403 	 *
6404 	 * Note:	MAC policies which do not actually end up modifying
6405 	 *		the label subsequently are strongly encouraged to
6406 	 *		return 0 for this check, since a non-zero answer will
6407 	 *		slow down the exec fast path for normal binaries.
6408 	 */
6409 	mac_transition = mac_cred_check_label_update_execve(
6410 		imgp->ip_vfs_context,
6411 		imgp->ip_vp,
6412 		imgp->ip_arch_offset,
6413 		imgp->ip_scriptvp,
6414 		imgp->ip_scriptlabelp,
6415 		imgp->ip_execlabelp,
6416 		p,
6417 		&imgp->ip_px_smpx);
6418 #endif
6419 
6420 	OSBitAndAtomic(~((uint32_t)P_SUGID), &p->p_flag);
6421 
6422 	/*
6423 	 * Order of the following is important; group checks must go last,
6424 	 * as we use the success of the 'ismember' check combined with the
6425 	 * failure of the explicit match to indicate that we will be setting
6426 	 * the egid of the process even though the new process did not
6427 	 * require VSUID/VSGID bits in order for it to set the new group as
6428 	 * its egid.
6429 	 *
6430 	 * Note:	Technically, by this we are implying a call to
6431 	 *		setegid() in the new process, rather than implying
6432 	 *		it used its VSGID bit to set the effective group,
6433 	 *		even though there is no code in that process to make
6434 	 *		such a call.
6435 	 */
6436 	if (((imgp->ip_origvattr->va_mode & VSUID) != 0 &&
6437 	    kauth_cred_getuid(cred) != imgp->ip_origvattr->va_uid) ||
6438 	    ((imgp->ip_origvattr->va_mode & VSGID) != 0 &&
6439 	    ((kauth_cred_ismember_gid(cred, imgp->ip_origvattr->va_gid, &leave_sugid_clear) || !leave_sugid_clear) ||
6440 	    (kauth_cred_getgid(cred) != imgp->ip_origvattr->va_gid)))) {
6441 #if CONFIG_MACF
6442 /* label for MAC transition and neither VSUID nor VSGID */
6443 handle_mac_transition:
6444 #endif
6445 
6446 #if CONFIG_SETUID
6447 		/*
6448 		 * Replace the credential with a copy of itself if euid or
6449 		 * egid change.
6450 		 *
6451 		 * Note:	setuid binaries will automatically opt out of
6452 		 *		group resolver participation as a side effect
6453 		 *		of this operation.  This is an intentional
6454 		 *		part of the security model, which requires a
6455 		 *		participating credential be established by
6456 		 *		escalating privilege, setting up all other
6457 		 *		aspects of the credential including whether
6458 		 *		or not to participate in external group
6459 		 *		membership resolution, then dropping their
6460 		 *		effective privilege to that of the desired
6461 		 *		final credential state.
6462 		 *
6463 		 * Modifications to p_ucred must be guarded using the
6464 		 * proc's ucred lock. This prevents others from accessing
6465 		 * a garbage credential.
6466 		 */
6467 
6468 		if (imgp->ip_origvattr->va_mode & VSUID) {
6469 			kauth_cred_proc_update(p, PROC_SETTOKEN_NONE,
6470 			    ^bool (kauth_cred_t parent __unused, kauth_cred_t model) {
6471 				return kauth_cred_model_setresuid(model,
6472 				KAUTH_UID_NONE,
6473 				imgp->ip_origvattr->va_uid,
6474 				imgp->ip_origvattr->va_uid,
6475 				KAUTH_UID_NONE);
6476 			});
6477 		}
6478 
6479 		if (imgp->ip_origvattr->va_mode & VSGID) {
6480 			kauth_cred_proc_update(p, PROC_SETTOKEN_NONE,
6481 			    ^bool (kauth_cred_t parent __unused, kauth_cred_t model) {
6482 				return kauth_cred_model_setresgid(model,
6483 				KAUTH_GID_NONE,
6484 				imgp->ip_origvattr->va_gid,
6485 				imgp->ip_origvattr->va_gid);
6486 			});
6487 		}
6488 #endif /* CONFIG_SETUID */
6489 
6490 #if CONFIG_MACF
6491 		/*
6492 		 * If a policy has indicated that it will transition the label,
6493 		 * before making the call into the MAC policies, get a new
6494 		 * duplicate credential, so they can modify it without
6495 		 * modifying any others sharing it.
6496 		 */
6497 		if (mac_transition) {
6498 			/*
6499 			 * This hook may generate upcalls that require
6500 			 * importance donation from the kernel.
6501 			 * (23925818)
6502 			 */
6503 			thread_t thread = current_thread();
6504 			thread_enable_send_importance(thread, TRUE);
6505 			kauth_proc_label_update_execve(p,
6506 			    imgp->ip_vfs_context,
6507 			    imgp->ip_vp,
6508 			    imgp->ip_arch_offset,
6509 			    imgp->ip_scriptvp,
6510 			    imgp->ip_scriptlabelp,
6511 			    imgp->ip_execlabelp,
6512 			    &imgp->ip_csflags,
6513 			    &imgp->ip_px_smpx,
6514 			    &disjoint_cred,                     /* will be non zero if disjoint */
6515 			    &label_update_return);
6516 			thread_enable_send_importance(thread, FALSE);
6517 
6518 			if (disjoint_cred) {
6519 				/*
6520 				 * If updating the MAC label resulted in a
6521 				 * disjoint credential, flag that we need to
6522 				 * set the P_SUGID bit.  This protects
6523 				 * against debuggers being attached by an
6524 				 * insufficiently privileged process onto the
6525 				 * result of a transition to a more privileged
6526 				 * credential.
6527 				 */
6528 				leave_sugid_clear = 0;
6529 			}
6530 
6531 			imgp->ip_mac_return = label_update_return;
6532 		}
6533 
6534 		mac_reset_ipc = mac_proc_check_inherit_ipc_ports(p, p->p_textvp, p->p_textoff, imgp->ip_vp, imgp->ip_arch_offset, imgp->ip_scriptvp);
6535 
6536 #endif  /* CONFIG_MACF */
6537 
6538 		/*
6539 		 * If 'leave_sugid_clear' is non-zero, then we passed the
6540 		 * VSUID and MACF checks, and successfully determined that
6541 		 * the previous cred was a member of the VSGID group, but
6542 		 * that it was not the default at the time of the execve,
6543 		 * and that the post-labelling credential was not disjoint.
6544 		 * So we don't set the P_SUGID or reset mach ports and fds
6545 		 * on the basis of simply running this code.
6546 		 */
6547 		if (mac_reset_ipc || !leave_sugid_clear) {
6548 			/*
6549 			 * Have mach reset the task and thread ports.
6550 			 * We don't want anyone who had the ports before
6551 			 * a setuid exec to be able to access/control the
6552 			 * task/thread after.
6553 			 */
6554 			ipc_task_reset((imgp->ip_new_thread != NULL) ?
6555 			    get_threadtask(imgp->ip_new_thread) : proc_task(p));
6556 			ipc_thread_reset((imgp->ip_new_thread != NULL) ?
6557 			    imgp->ip_new_thread : current_thread());
6558 		}
6559 
6560 		if (!leave_sugid_clear) {
6561 			/*
6562 			 * Flag the process as setuid.
6563 			 */
6564 			OSBitOrAtomic(P_SUGID, &p->p_flag);
6565 
6566 			/*
6567 			 * Radar 2261856; setuid security hole fix
6568 			 * XXX For setuid processes, attempt to ensure that
6569 			 * stdin, stdout, and stderr are already allocated.
6570 			 * We do not want userland to accidentally allocate
6571 			 * descriptors in this range which has implied meaning
6572 			 * to libc.
6573 			 */
6574 			for (i = 0; i < 3; i++) {
6575 				if (fp_get_noref_locked(p, i) != NULL) {
6576 					continue;
6577 				}
6578 
6579 				/*
6580 				 * Do the kernel equivalent of
6581 				 *
6582 				 *      if i == 0
6583 				 *              (void) open("/dev/null", O_RDONLY);
6584 				 *      else
6585 				 *              (void) open("/dev/null", O_WRONLY);
6586 				 */
6587 
6588 				struct fileproc *fp;
6589 				int indx;
6590 				int flag;
6591 				struct nameidata *ndp = NULL;
6592 
6593 				if (i == 0) {
6594 					flag = FREAD;
6595 				} else {
6596 					flag = FWRITE;
6597 				}
6598 
6599 				if ((error = falloc(p,
6600 				    &fp, &indx, imgp->ip_vfs_context)) != 0) {
6601 					continue;
6602 				}
6603 
6604 				ndp = kalloc_type(struct nameidata,
6605 				    Z_WAITOK | Z_ZERO | Z_NOFAIL);
6606 
6607 				NDINIT(ndp, LOOKUP, OP_OPEN, FOLLOW, UIO_SYSSPACE,
6608 				    CAST_USER_ADDR_T("/dev/null"),
6609 				    imgp->ip_vfs_context);
6610 
6611 				if ((error = vn_open(ndp, flag, 0)) != 0) {
6612 					fp_free(p, indx, fp);
6613 					kfree_type(struct nameidata, ndp);
6614 					break;
6615 				}
6616 
6617 				struct fileglob *fg = fp->fp_glob;
6618 
6619 				fg->fg_flag = flag;
6620 				fg->fg_ops = &vnops;
6621 				fp_set_data(fp, ndp->ni_vp);
6622 
6623 				vnode_put(ndp->ni_vp);
6624 
6625 				proc_fdlock(p);
6626 				procfdtbl_releasefd(p, indx, NULL);
6627 				fp_drop(p, indx, fp, 1);
6628 				proc_fdunlock(p);
6629 
6630 				kfree_type(struct nameidata, ndp);
6631 			}
6632 		}
6633 	}
6634 #if CONFIG_MACF
6635 	else {
6636 		/*
6637 		 * We are here because we were told that the MAC label will
6638 		 * be transitioned, and the binary is not VSUID or VSGID; to
6639 		 * deal with this case, we could either duplicate a lot of
6640 		 * code, or we can indicate we want to default the P_SUGID
6641 		 * bit clear and jump back up.
6642 		 */
6643 		if (mac_transition) {
6644 			leave_sugid_clear = 1;
6645 			goto handle_mac_transition;
6646 		}
6647 	}
6648 
6649 #endif  /* CONFIG_MACF */
6650 
6651 	/* Update the process' identity version and set the security token */
6652 	proc_setpidversion(p, OSIncrementAtomic(&nextpidversion));
6653 	task_set_uniqueid(proc_task(p));
6654 
6655 	/*
6656 	 * Implement the semantic where the effective user and group become
6657 	 * the saved user and group in exec'ed programs.
6658 	 */
6659 	kauth_cred_proc_update(p, PROC_SETTOKEN_ALWAYS,
6660 	    ^bool (kauth_cred_t parent __unused, kauth_cred_t model) {
6661 		posix_cred_t pcred = posix_cred_get(model);
6662 
6663 		if (pcred->cr_svuid == pcred->cr_uid &&
6664 		pcred->cr_svgid == pcred->cr_gid) {
6665 		        return false;
6666 		}
6667 
6668 		pcred->cr_svuid = pcred->cr_uid;
6669 		pcred->cr_svgid = pcred->cr_gid;
6670 		return true;
6671 	});
6672 
6673 	return error;
6674 }
6675 
6676 
6677 /*
6678  * create_unix_stack
6679  *
6680  * Description:	Set the user stack address for the process to the provided
6681  *		address.  If a custom stack was not set as a result of the
6682  *		load process (i.e. as specified by the image file for the
6683  *		executable), then allocate the stack in the provided map and
6684  *		set up appropriate guard pages for enforcing administrative
6685  *		limits on stack growth, if they end up being needed.
6686  *
6687  * Parameters:	p			Process to set stack on
6688  *		load_result		Information from mach-o load commands
6689  *		map			Address map in which to allocate the new stack
6690  *
6691  * Returns:	KERN_SUCCESS		Stack successfully created
6692  *		!KERN_SUCCESS		Mach failure code
6693  */
6694 __attribute__((noinline))
6695 static kern_return_t
create_unix_stack(vm_map_t map,load_result_t * load_result,proc_t p)6696 create_unix_stack(vm_map_t map, load_result_t* load_result,
6697     proc_t p)
6698 {
6699 	mach_vm_size_t          size, prot_size;
6700 	mach_vm_offset_t        addr, prot_addr;
6701 	kern_return_t           kr;
6702 
6703 	mach_vm_address_t       user_stack = load_result->user_stack;
6704 
6705 	proc_lock(p);
6706 	p->user_stack = (uintptr_t)user_stack;
6707 	if (load_result->custom_stack) {
6708 		p->p_lflag |= P_LCUSTOM_STACK;
6709 	}
6710 	proc_unlock(p);
6711 	if (vm_map_page_shift(map) < (int)PAGE_SHIFT) {
6712 		DEBUG4K_LOAD("map %p user_stack 0x%llx custom %d user_stack_alloc_size 0x%llx\n", map, user_stack, load_result->custom_stack, load_result->user_stack_alloc_size);
6713 	}
6714 
6715 	if (load_result->user_stack_alloc_size > 0) {
6716 		/*
6717 		 * Allocate enough space for the maximum stack size we
6718 		 * will ever authorize and an extra page to act as
6719 		 * a guard page for stack overflows. For default stacks,
6720 		 * vm_initial_limit_stack takes care of the extra guard page.
6721 		 * Otherwise we must allocate it ourselves.
6722 		 */
6723 		if (mach_vm_round_page_overflow(load_result->user_stack_alloc_size, &size)) {
6724 			return KERN_INVALID_ARGUMENT;
6725 		}
6726 		addr = vm_map_trunc_page(load_result->user_stack - size,
6727 		    vm_map_page_mask(map));
6728 		kr = mach_vm_allocate_kernel(map, &addr, size,
6729 		    VM_FLAGS_FIXED, VM_MEMORY_STACK);
6730 		if (kr != KERN_SUCCESS) {
6731 			// Can't allocate at default location, try anywhere
6732 			addr = 0;
6733 			kr = mach_vm_allocate_kernel(map, &addr, size,
6734 			    VM_FLAGS_ANYWHERE, VM_MEMORY_STACK);
6735 			if (kr != KERN_SUCCESS) {
6736 				return kr;
6737 			}
6738 
6739 			user_stack = addr + size;
6740 			load_result->user_stack = (user_addr_t)user_stack;
6741 
6742 			proc_lock(p);
6743 			p->user_stack = (uintptr_t)user_stack;
6744 			proc_unlock(p);
6745 		}
6746 
6747 		load_result->user_stack_alloc = (user_addr_t)addr;
6748 
6749 		/*
6750 		 * And prevent access to what's above the current stack
6751 		 * size limit for this process.
6752 		 */
6753 		if (load_result->user_stack_size == 0) {
6754 			load_result->user_stack_size = proc_limitgetcur(p, RLIMIT_STACK);
6755 			prot_size = vm_map_trunc_page(size - load_result->user_stack_size, vm_map_page_mask(map));
6756 		} else {
6757 			prot_size = PAGE_SIZE;
6758 		}
6759 
6760 		prot_addr = addr;
6761 		kr = mach_vm_protect(map,
6762 		    prot_addr,
6763 		    prot_size,
6764 		    FALSE,
6765 		    VM_PROT_NONE);
6766 		if (kr != KERN_SUCCESS) {
6767 			(void)mach_vm_deallocate(map, addr, size);
6768 			return kr;
6769 		}
6770 	}
6771 
6772 	return KERN_SUCCESS;
6773 }
6774 
6775 #include <sys/reboot.h>
6776 
6777 /*
6778  * load_init_program_at_path
6779  *
6780  * Description:	Load the "init" program; in most cases, this will be "launchd"
6781  *
6782  * Parameters:	p			Process to call execve() to create
6783  *					the "init" program
6784  *		scratch_addr		Page in p, scratch space
6785  *		path			NULL terminated path
6786  *
6787  * Returns:	KERN_SUCCESS		Success
6788  *		!KERN_SUCCESS           See execve/mac_execve for error codes
6789  *
6790  * Notes:	The process that is passed in is the first manufactured
6791  *		process on the system, and gets here via bsd_ast() firing
6792  *		for the first time.  This is done to ensure that bsd_init()
6793  *		has run to completion.
6794  *
6795  *		The address map of the first manufactured process matches the
6796  *		word width of the kernel. Once the self-exec completes, the
6797  *		initproc might be different.
6798  */
6799 static int
load_init_program_at_path(proc_t p,user_addr_t scratch_addr,const char * path)6800 load_init_program_at_path(proc_t p, user_addr_t scratch_addr, const char* path)
6801 {
6802 	int retval[2];
6803 	int error;
6804 	struct execve_args init_exec_args;
6805 	user_addr_t argv0 = USER_ADDR_NULL, argv1 = USER_ADDR_NULL;
6806 
6807 	/*
6808 	 * Validate inputs and pre-conditions
6809 	 */
6810 	assert(p);
6811 	assert(scratch_addr);
6812 	assert(path);
6813 
6814 	/*
6815 	 * Copy out program name.
6816 	 */
6817 	size_t path_length = strlen(path) + 1;
6818 	argv0 = scratch_addr;
6819 	error = copyout(path, argv0, path_length);
6820 	if (error) {
6821 		return error;
6822 	}
6823 
6824 	scratch_addr = USER_ADDR_ALIGN(scratch_addr + path_length, sizeof(user_addr_t));
6825 
6826 	/*
6827 	 * Put out first (and only) argument, similarly.
6828 	 * Assumes everything fits in a page as allocated above.
6829 	 */
6830 	if (boothowto & RB_SINGLE) {
6831 		const char *init_args = "-s";
6832 		size_t init_args_length = strlen(init_args) + 1;
6833 
6834 		argv1 = scratch_addr;
6835 		error = copyout(init_args, argv1, init_args_length);
6836 		if (error) {
6837 			return error;
6838 		}
6839 
6840 		scratch_addr = USER_ADDR_ALIGN(scratch_addr + init_args_length, sizeof(user_addr_t));
6841 	}
6842 
6843 	if (proc_is64bit(p)) {
6844 		user64_addr_t argv64bit[3] = {};
6845 
6846 		argv64bit[0] = argv0;
6847 		argv64bit[1] = argv1;
6848 		argv64bit[2] = USER_ADDR_NULL;
6849 
6850 		error = copyout(argv64bit, scratch_addr, sizeof(argv64bit));
6851 		if (error) {
6852 			return error;
6853 		}
6854 	} else {
6855 		user32_addr_t argv32bit[3] = {};
6856 
6857 		argv32bit[0] = (user32_addr_t)argv0;
6858 		argv32bit[1] = (user32_addr_t)argv1;
6859 		argv32bit[2] = USER_ADDR_NULL;
6860 
6861 		error = copyout(argv32bit, scratch_addr, sizeof(argv32bit));
6862 		if (error) {
6863 			return error;
6864 		}
6865 	}
6866 
6867 	/*
6868 	 * Set up argument block for fake call to execve.
6869 	 */
6870 	init_exec_args.fname = argv0;
6871 	init_exec_args.argp = scratch_addr;
6872 	init_exec_args.envp = USER_ADDR_NULL;
6873 
6874 	/*
6875 	 * So that init task is set with uid,gid 0 token
6876 	 *
6877 	 * The access to the cred is safe:
6878 	 * the proc isn't running yet, it's stable.
6879 	 */
6880 	set_security_token(p, proc_ucred_unsafe(p));
6881 
6882 	return execve(p, &init_exec_args, retval);
6883 }
6884 
6885 static const char * init_programs[] = {
6886 #if DEBUG
6887 	"/usr/appleinternal/sbin/launchd.debug",
6888 #endif
6889 #if DEVELOPMENT || DEBUG
6890 	"/usr/appleinternal/sbin/launchd.development",
6891 #endif
6892 	"/sbin/launchd",
6893 };
6894 
6895 /*
6896  * load_init_program
6897  *
6898  * Description:	Load the "init" program; in most cases, this will be "launchd"
6899  *
6900  * Parameters:	p			Process to call execve() to create
6901  *					the "init" program
6902  *
6903  * Returns:	(void)
6904  *
6905  * Notes:	The process that is passed in is the first manufactured
6906  *		process on the system, and gets here via bsd_ast() firing
6907  *		for the first time.  This is done to ensure that bsd_init()
6908  *		has run to completion.
6909  *
6910  *		In DEBUG & DEVELOPMENT builds, the launchdsuffix boot-arg
6911  *		may be used to select a specific launchd executable. As with
6912  *		the kcsuffix boot-arg, setting launchdsuffix to "" or "release"
6913  *		will force /sbin/launchd to be selected.
6914  *
6915  *              Search order by build:
6916  *
6917  * DEBUG	DEVELOPMENT	RELEASE		PATH
6918  * ----------------------------------------------------------------------------------
6919  * 1		1		NA		/usr/appleinternal/sbin/launchd.$LAUNCHDSUFFIX
6920  * 2		NA		NA		/usr/appleinternal/sbin/launchd.debug
6921  * 3		2		NA		/usr/appleinternal/sbin/launchd.development
6922  * 4		3		1		/sbin/launchd
6923  */
6924 void
load_init_program(proc_t p)6925 load_init_program(proc_t p)
6926 {
6927 	uint32_t i;
6928 	int error;
6929 	vm_map_t map = current_map();
6930 	mach_vm_offset_t scratch_addr = 0;
6931 	mach_vm_size_t map_page_size = vm_map_page_size(map);
6932 
6933 	(void) mach_vm_allocate_kernel(map, &scratch_addr, map_page_size, VM_FLAGS_ANYWHERE, VM_KERN_MEMORY_NONE);
6934 #if CONFIG_MEMORYSTATUS
6935 	(void) memorystatus_init_at_boot_snapshot();
6936 #endif /* CONFIG_MEMORYSTATUS */
6937 
6938 #if DEBUG || DEVELOPMENT
6939 	/* Check for boot-arg suffix first */
6940 	char launchd_suffix[64];
6941 	if (PE_parse_boot_argn("launchdsuffix", launchd_suffix, sizeof(launchd_suffix))) {
6942 		char launchd_path[128];
6943 		boolean_t is_release_suffix = ((launchd_suffix[0] == 0) ||
6944 		    (strcmp(launchd_suffix, "release") == 0));
6945 
6946 		if (is_release_suffix) {
6947 			printf("load_init_program: attempting to load /sbin/launchd\n");
6948 			error = load_init_program_at_path(p, (user_addr_t)scratch_addr, "/sbin/launchd");
6949 			if (!error) {
6950 				return;
6951 			}
6952 
6953 			panic("Process 1 exec of launchd.release failed, errno %d", error);
6954 		} else {
6955 			strlcpy(launchd_path, "/usr/appleinternal/sbin/launchd.", sizeof(launchd_path));
6956 			strlcat(launchd_path, launchd_suffix, sizeof(launchd_path));
6957 
6958 			printf("load_init_program: attempting to load %s\n", launchd_path);
6959 			error = load_init_program_at_path(p, (user_addr_t)scratch_addr, launchd_path);
6960 			if (!error) {
6961 				return;
6962 			} else if (error != ENOENT) {
6963 				printf("load_init_program: failed loading %s: errno %d\n", launchd_path, error);
6964 			}
6965 		}
6966 	}
6967 #endif
6968 
6969 	error = ENOENT;
6970 	for (i = 0; i < sizeof(init_programs) / sizeof(init_programs[0]); i++) {
6971 		printf("load_init_program: attempting to load %s\n", init_programs[i]);
6972 		error = load_init_program_at_path(p, (user_addr_t)scratch_addr, init_programs[i]);
6973 		if (!error) {
6974 			return;
6975 		} else if (error != ENOENT) {
6976 			printf("load_init_program: failed loading %s: errno %d\n", init_programs[i], error);
6977 		}
6978 	}
6979 
6980 	panic("Process 1 exec of %s failed, errno %d", ((i == 0) ? "<null>" : init_programs[i - 1]), error);
6981 }
6982 
6983 /*
6984  * load_return_to_errno
6985  *
6986  * Description:	Convert a load_return_t (Mach error) to an errno (BSD error)
6987  *
6988  * Parameters:	lrtn			Mach error number
6989  *
6990  * Returns:	(int)			BSD error number
6991  *		0			Success
6992  *		EBADARCH		Bad architecture
6993  *		EBADMACHO		Bad Mach object file
6994  *		ESHLIBVERS		Bad shared library version
6995  *		ENOMEM			Out of memory/resource shortage
6996  *		EACCES			Access denied
6997  *		ENOENT			Entry not found (usually "file does
6998  *					does not exist")
6999  *		EIO			An I/O error occurred
7000  *		EBADEXEC		The executable is corrupt/unknown
7001  */
7002 static int
load_return_to_errno(load_return_t lrtn)7003 load_return_to_errno(load_return_t lrtn)
7004 {
7005 	switch (lrtn) {
7006 	case LOAD_SUCCESS:
7007 		return 0;
7008 	case LOAD_BADARCH:
7009 		return EBADARCH;
7010 	case LOAD_BADMACHO:
7011 	case LOAD_BADMACHO_UPX:
7012 		return EBADMACHO;
7013 	case LOAD_SHLIB:
7014 		return ESHLIBVERS;
7015 	case LOAD_NOSPACE:
7016 	case LOAD_RESOURCE:
7017 		return ENOMEM;
7018 	case LOAD_PROTECT:
7019 		return EACCES;
7020 	case LOAD_ENOENT:
7021 		return ENOENT;
7022 	case LOAD_IOERROR:
7023 		return EIO;
7024 	case LOAD_DECRYPTFAIL:
7025 		return EAUTH;
7026 	case LOAD_FAILURE:
7027 	default:
7028 		return EBADEXEC;
7029 	}
7030 }
7031 
7032 #include <mach/mach_types.h>
7033 #include <mach/vm_prot.h>
7034 #include <mach/semaphore.h>
7035 #include <mach/sync_policy.h>
7036 #include <kern/clock.h>
7037 #include <mach/kern_return.h>
7038 
7039 /*
7040  * execargs_alloc
7041  *
7042  * Description:	Allocate the block of memory used by the execve arguments.
7043  *		At the same time, we allocate a page so that we can read in
7044  *		the first page of the image.
7045  *
7046  * Parameters:	struct image_params *	the image parameter block
7047  *
7048  * Returns:	0			Success
7049  *		EINVAL			Invalid argument
7050  *		EACCES			Permission denied
7051  *		EINTR			Interrupted function
7052  *		ENOMEM			Not enough space
7053  *
7054  * Notes:	This is a temporary allocation into the kernel address space
7055  *		to enable us to copy arguments in from user space.  This is
7056  *		necessitated by not mapping the process calling execve() into
7057  *		the kernel address space during the execve() system call.
7058  *
7059  *		We assemble the argument and environment, etc., into this
7060  *		region before copying it as a single block into the child
7061  *		process address space (at the top or bottom of the stack,
7062  *		depending on which way the stack grows; see the function
7063  *		exec_copyout_strings() for details).
7064  *
7065  *		This ends up with a second (possibly unnecessary) copy compared
7066  *		with assembing the data directly into the child address space,
7067  *		instead, but since we cannot be guaranteed that the parent has
7068  *		not modified its environment, we can't really know that it's
7069  *		really a block there as well.
7070  */
7071 
7072 
7073 static int execargs_waiters = 0;
7074 static LCK_MTX_DECLARE_ATTR(execargs_cache_lock, &proc_lck_grp, &proc_lck_attr);
7075 
7076 static void
execargs_lock_lock(void)7077 execargs_lock_lock(void)
7078 {
7079 	lck_mtx_lock_spin(&execargs_cache_lock);
7080 }
7081 
7082 static void
execargs_lock_unlock(void)7083 execargs_lock_unlock(void)
7084 {
7085 	lck_mtx_unlock(&execargs_cache_lock);
7086 }
7087 
7088 static wait_result_t
execargs_lock_sleep(void)7089 execargs_lock_sleep(void)
7090 {
7091 	return lck_mtx_sleep(&execargs_cache_lock, LCK_SLEEP_DEFAULT, &execargs_free_count, THREAD_INTERRUPTIBLE);
7092 }
7093 
7094 static kern_return_t
execargs_purgeable_allocate(char ** execarg_address)7095 execargs_purgeable_allocate(char **execarg_address)
7096 {
7097 	mach_vm_offset_t addr = 0;
7098 	kern_return_t kr = mach_vm_allocate_kernel(bsd_pageable_map, &addr,
7099 	    BSD_PAGEABLE_SIZE_PER_EXEC, VM_FLAGS_ANYWHERE | VM_FLAGS_PURGABLE,
7100 	    VM_KERN_MEMORY_NONE);
7101 	*execarg_address = (char *)addr;
7102 	assert(kr == KERN_SUCCESS);
7103 	return kr;
7104 }
7105 
7106 static kern_return_t
execargs_purgeable_reference(void * execarg_address)7107 execargs_purgeable_reference(void *execarg_address)
7108 {
7109 	int state = VM_PURGABLE_NONVOLATILE;
7110 	kern_return_t kr = vm_purgable_control(bsd_pageable_map, (vm_offset_t) execarg_address, VM_PURGABLE_SET_STATE, &state);
7111 
7112 	assert(kr == KERN_SUCCESS);
7113 	return kr;
7114 }
7115 
7116 static kern_return_t
execargs_purgeable_volatilize(void * execarg_address)7117 execargs_purgeable_volatilize(void *execarg_address)
7118 {
7119 	int state = VM_PURGABLE_VOLATILE | VM_PURGABLE_ORDERING_OBSOLETE;
7120 	kern_return_t kr;
7121 	kr = vm_purgable_control(bsd_pageable_map, (vm_offset_t) execarg_address, VM_PURGABLE_SET_STATE, &state);
7122 
7123 	assert(kr == KERN_SUCCESS);
7124 
7125 	return kr;
7126 }
7127 
7128 static void
execargs_wakeup_waiters(void)7129 execargs_wakeup_waiters(void)
7130 {
7131 	thread_wakeup(&execargs_free_count);
7132 }
7133 
7134 static int
execargs_alloc(struct image_params * imgp)7135 execargs_alloc(struct image_params *imgp)
7136 {
7137 	kern_return_t kret;
7138 	wait_result_t res;
7139 	int i, cache_index = -1;
7140 
7141 	execargs_lock_lock();
7142 
7143 	while (execargs_free_count == 0) {
7144 		execargs_waiters++;
7145 		res = execargs_lock_sleep();
7146 		execargs_waiters--;
7147 		if (res != THREAD_AWAKENED) {
7148 			execargs_lock_unlock();
7149 			return EINTR;
7150 		}
7151 	}
7152 
7153 	execargs_free_count--;
7154 
7155 	for (i = 0; i < execargs_cache_size; i++) {
7156 		vm_offset_t element = execargs_cache[i];
7157 		if (element) {
7158 			cache_index = i;
7159 			imgp->ip_strings = (char *)(execargs_cache[i]);
7160 			execargs_cache[i] = 0;
7161 			break;
7162 		}
7163 	}
7164 
7165 	assert(execargs_free_count >= 0);
7166 
7167 	execargs_lock_unlock();
7168 
7169 	if (cache_index == -1) {
7170 		kret = execargs_purgeable_allocate(&imgp->ip_strings);
7171 	} else {
7172 		kret = execargs_purgeable_reference(imgp->ip_strings);
7173 	}
7174 
7175 	assert(kret == KERN_SUCCESS);
7176 	if (kret != KERN_SUCCESS) {
7177 		return ENOMEM;
7178 	}
7179 
7180 	/* last page used to read in file headers */
7181 	imgp->ip_vdata = imgp->ip_strings + (NCARGS + PAGE_SIZE);
7182 	imgp->ip_strendp = imgp->ip_strings;
7183 	imgp->ip_argspace = NCARGS;
7184 	imgp->ip_strspace = (NCARGS + PAGE_SIZE);
7185 
7186 	return 0;
7187 }
7188 
7189 /*
7190  * execargs_free
7191  *
7192  * Description:	Free the block of memory used by the execve arguments and the
7193  *		first page of the executable by a previous call to the function
7194  *		execargs_alloc().
7195  *
7196  * Parameters:	struct image_params *	the image parameter block
7197  *
7198  * Returns:	0			Success
7199  *		EINVAL			Invalid argument
7200  *		EINTR			Oeration interrupted
7201  */
7202 static int
execargs_free(struct image_params * imgp)7203 execargs_free(struct image_params *imgp)
7204 {
7205 	kern_return_t kret;
7206 	int i;
7207 	boolean_t needs_wakeup = FALSE;
7208 
7209 	kret = execargs_purgeable_volatilize(imgp->ip_strings);
7210 
7211 	execargs_lock_lock();
7212 	execargs_free_count++;
7213 
7214 	for (i = 0; i < execargs_cache_size; i++) {
7215 		vm_offset_t element = execargs_cache[i];
7216 		if (element == 0) {
7217 			execargs_cache[i] = (vm_offset_t) imgp->ip_strings;
7218 			imgp->ip_strings = NULL;
7219 			break;
7220 		}
7221 	}
7222 
7223 	assert(imgp->ip_strings == NULL);
7224 
7225 	if (execargs_waiters > 0) {
7226 		needs_wakeup = TRUE;
7227 	}
7228 
7229 	execargs_lock_unlock();
7230 
7231 	if (needs_wakeup == TRUE) {
7232 		execargs_wakeup_waiters();
7233 	}
7234 
7235 	return kret == KERN_SUCCESS ? 0 : EINVAL;
7236 }
7237 
7238 void
uthread_set_exec_data(struct uthread * uth,struct image_params * imgp)7239 uthread_set_exec_data(struct uthread *uth, struct image_params *imgp)
7240 {
7241 	uth->uu_save.uus_exec_data.imgp = imgp;
7242 }
7243 
7244 size_t
thread_get_current_exec_path(char * path,size_t size)7245 thread_get_current_exec_path(char *path, size_t size)
7246 {
7247 	struct uthread *uth = current_uthread();
7248 	struct image_params *imgp = uth->uu_save.uus_exec_data.imgp;
7249 	size_t string_size = 0;
7250 	char *exec_path;
7251 
7252 	if (path == NULL || imgp == NULL || imgp->ip_strings == NULL) {
7253 		return 0;
7254 	}
7255 
7256 	exec_path = imgp->ip_strings + strlen(EXECUTABLE_KEY);
7257 	string_size = imgp->ip_strendp - exec_path;
7258 	string_size = MIN(MAXPATHLEN, string_size);
7259 	string_size = MIN(size, string_size);
7260 
7261 	string_size = strlcpy(path, exec_path, string_size);
7262 	return string_size;
7263 }
7264 static void
exec_resettextvp(proc_t p,struct image_params * imgp)7265 exec_resettextvp(proc_t p, struct image_params *imgp)
7266 {
7267 	vnode_t vp;
7268 	off_t offset;
7269 	vnode_t tvp  = p->p_textvp;
7270 	int ret;
7271 
7272 	vp = imgp->ip_vp;
7273 	offset = imgp->ip_arch_offset;
7274 
7275 	if (vp == NULLVP) {
7276 		panic("exec_resettextvp: expected valid vp");
7277 	}
7278 
7279 	ret = vnode_ref(vp);
7280 	proc_lock(p);
7281 	if (ret == 0) {
7282 		p->p_textvp = vp;
7283 		p->p_textoff = offset;
7284 	} else {
7285 		p->p_textvp = NULLVP;   /* this is paranoia */
7286 		p->p_textoff = 0;
7287 	}
7288 	proc_unlock(p);
7289 
7290 	if (tvp != NULLVP) {
7291 		if (vnode_getwithref(tvp) == 0) {
7292 			vnode_rele(tvp);
7293 			vnode_put(tvp);
7294 		}
7295 	}
7296 }
7297 
7298 // Includes the 0-byte (therefore "SIZE" instead of "LEN").
7299 static const size_t CS_CDHASH_STRING_SIZE = CS_CDHASH_LEN * 2 + 1;
7300 
7301 static void
cdhash_to_string(char str[CS_CDHASH_STRING_SIZE],uint8_t const * const cdhash)7302 cdhash_to_string(char str[CS_CDHASH_STRING_SIZE], uint8_t const * const cdhash)
7303 {
7304 	static char const nibble[] = "0123456789abcdef";
7305 
7306 	/* Apparently still the safest way to get a hex representation
7307 	 * of binary data.
7308 	 * xnu's printf routines have %*D/%20D in theory, but "not really", see:
7309 	 * <rdar://problem/33328859> confusion around %*D/%nD in printf
7310 	 */
7311 	for (int i = 0; i < CS_CDHASH_LEN; ++i) {
7312 		str[i * 2] = nibble[(cdhash[i] & 0xf0) >> 4];
7313 		str[i * 2 + 1] = nibble[cdhash[i] & 0x0f];
7314 	}
7315 	str[CS_CDHASH_STRING_SIZE - 1] = 0;
7316 }
7317 
7318 /*
7319  * __EXEC_WAITING_ON_TASKGATED_CODE_SIGNATURE_UPCALL__
7320  *
7321  * Description: Waits for the userspace daemon to respond to the request
7322  *              we made. Function declared non inline to be visible in
7323  *		stackshots and spindumps as well as debugging.
7324  */
7325 __attribute__((noinline)) int
__EXEC_WAITING_ON_TASKGATED_CODE_SIGNATURE_UPCALL__(mach_port_t task_access_port,int32_t new_pid)7326 __EXEC_WAITING_ON_TASKGATED_CODE_SIGNATURE_UPCALL__(mach_port_t task_access_port, int32_t new_pid)
7327 {
7328 	return find_code_signature(task_access_port, new_pid);
7329 }
7330 
7331 /*
7332  * Update signature dependent process state, called by
7333  * process_signature.
7334  */
7335 static int
proc_process_signature(proc_t p,os_reason_t * signature_failure_reason)7336 proc_process_signature(proc_t p, os_reason_t *signature_failure_reason)
7337 {
7338 	int error = 0;
7339 	char const *error_msg = NULL;
7340 
7341 	kern_return_t kr = machine_task_process_signature(proc_get_task_raw(p), proc_platform(p), proc_sdk(p), &error_msg);
7342 
7343 	if (kr != KERN_SUCCESS) {
7344 		error = EINVAL;
7345 
7346 		if (error_msg != NULL) {
7347 			uint32_t error_msg_len = (uint32_t)strlen(error_msg) + 1;
7348 			mach_vm_address_t data_addr = 0;
7349 			int reason_error = 0;
7350 			int kcdata_error = 0;
7351 
7352 			os_reason_t reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_SECURITY_POLICY);
7353 			reason->osr_flags = OS_REASON_FLAG_GENERATE_CRASH_REPORT | OS_REASON_FLAG_CONSISTENT_FAILURE;
7354 
7355 			if ((reason_error = os_reason_alloc_buffer_noblock(reason,
7356 			    kcdata_estimate_required_buffer_size(1, error_msg_len))) == 0 &&
7357 			    (kcdata_error = kcdata_get_memory_addr(&reason->osr_kcd_descriptor,
7358 			    EXIT_REASON_USER_DESC, error_msg_len,
7359 			    &data_addr)) == KERN_SUCCESS) {
7360 				kern_return_t mc_error = kcdata_memcpy(&reason->osr_kcd_descriptor, (mach_vm_address_t)data_addr,
7361 				    error_msg, error_msg_len);
7362 
7363 				if (mc_error != KERN_SUCCESS) {
7364 					printf("process_signature: failed to copy reason string (kcdata_memcpy error: %d)\n",
7365 					    mc_error);
7366 				}
7367 			} else {
7368 				printf("failed to allocate space for reason string (os_reason_alloc_buffer error: %d, kcdata error: %d, length: %u)\n",
7369 				    reason_error, kcdata_error, error_msg_len);
7370 			}
7371 
7372 			assert(*signature_failure_reason == NULL); // shouldn't have gotten so far
7373 			*signature_failure_reason = reason;
7374 		}
7375 	}
7376 	return error;
7377 }
7378 
7379 static int
process_signature(proc_t p,struct image_params * imgp)7380 process_signature(proc_t p, struct image_params *imgp)
7381 {
7382 	mach_port_t port = IPC_PORT_NULL;
7383 	kern_return_t kr = KERN_FAILURE;
7384 	int error = EACCES;
7385 	boolean_t unexpected_failure = FALSE;
7386 	struct cs_blob *csb;
7387 	boolean_t require_success = FALSE;
7388 	int spawn = (imgp->ip_flags & IMGPF_SPAWN);
7389 	const int vfexec = 0;
7390 	os_reason_t signature_failure_reason = OS_REASON_NULL;
7391 
7392 	/*
7393 	 * Override inherited code signing flags with the
7394 	 * ones for the process that is being successfully
7395 	 * loaded
7396 	 */
7397 	proc_lock(p);
7398 	proc_csflags_update(p, imgp->ip_csflags);
7399 	proc_unlock(p);
7400 
7401 	/* Set the switch_protect flag on the map */
7402 	if (proc_getcsflags(p) & (CS_HARD | CS_KILL)) {
7403 		vm_map_switch_protect(get_task_map(proc_task(p)), TRUE);
7404 	}
7405 	/* set the cs_enforced flags in the map */
7406 	if (proc_getcsflags(p) & CS_ENFORCEMENT) {
7407 		vm_map_cs_enforcement_set(get_task_map(proc_task(p)), TRUE);
7408 	} else {
7409 		vm_map_cs_enforcement_set(get_task_map(proc_task(p)), FALSE);
7410 	}
7411 
7412 	/*
7413 	 * image activation may be failed due to policy
7414 	 * which is unexpected but security framework does not
7415 	 * approve of exec, kill and return immediately.
7416 	 */
7417 	if (imgp->ip_mac_return != 0) {
7418 		KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
7419 		    proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_SECURITY_POLICY, 0, 0);
7420 		signature_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_SECURITY_POLICY);
7421 		error = imgp->ip_mac_return;
7422 		unexpected_failure = TRUE;
7423 		goto done;
7424 	}
7425 
7426 	if (imgp->ip_cs_error != OS_REASON_NULL) {
7427 		signature_failure_reason = imgp->ip_cs_error;
7428 		imgp->ip_cs_error = OS_REASON_NULL;
7429 		error = EACCES;
7430 		goto done;
7431 	}
7432 
7433 	/* call the launch constraints hook */
7434 	os_reason_t launch_constraint_reason;
7435 	if ((error = mac_proc_check_launch_constraints(p, imgp, &launch_constraint_reason)) != 0) {
7436 		signature_failure_reason = launch_constraint_reason;
7437 		goto done;
7438 	}
7439 
7440 #if XNU_TARGET_OS_OSX
7441 	/* Check for platform passed in spawn attr if iOS binary is being spawned */
7442 	if (proc_platform(p) == PLATFORM_IOS) {
7443 		struct _posix_spawnattr *psa = (struct _posix_spawnattr *) imgp->ip_px_sa;
7444 		if (psa == NULL || psa->psa_platform == 0) {
7445 			boolean_t no_sandbox_entitled = FALSE;
7446 #if DEBUG || DEVELOPMENT
7447 			/*
7448 			 * Allow iOS binaries to spawn on internal systems
7449 			 * if no-sandbox entitlement is present of unentitled_ios_sim_launch
7450 			 * boot-arg set to true
7451 			 */
7452 			if (unentitled_ios_sim_launch) {
7453 				no_sandbox_entitled = TRUE;
7454 			} else {
7455 				no_sandbox_entitled = IOVnodeHasEntitlement(imgp->ip_vp,
7456 				    (int64_t)imgp->ip_arch_offset, "com.apple.private.security.no-sandbox");
7457 			}
7458 #endif /* DEBUG || DEVELOPMENT */
7459 			if (!no_sandbox_entitled) {
7460 				signature_failure_reason = os_reason_create(OS_REASON_EXEC,
7461 				    EXEC_EXIT_REASON_WRONG_PLATFORM);
7462 				error = EACCES;
7463 				goto done;
7464 			}
7465 			printf("Allowing spawn of iOS binary %s since it has "
7466 			    "com.apple.private.security.no-sandbox entitlement or unentitled_ios_sim_launch "
7467 			    "boot-arg set to true\n", p->p_name);
7468 		} else if (psa->psa_platform != PLATFORM_IOS) {
7469 			/* Simulator binary spawned with wrong platform */
7470 			signature_failure_reason = os_reason_create(OS_REASON_EXEC,
7471 			    EXEC_EXIT_REASON_WRONG_PLATFORM);
7472 			error = EACCES;
7473 			goto done;
7474 		} else {
7475 			printf("Allowing spawn of iOS binary %s since correct platform was passed in spawn\n",
7476 			    p->p_name);
7477 		}
7478 	}
7479 #endif /* XNU_TARGET_OS_OSX */
7480 
7481 	/* If the code signature came through the image activation path, we skip the
7482 	 * taskgated / externally attached path. */
7483 	if (imgp->ip_csflags & CS_SIGNED) {
7484 		error = 0;
7485 		goto done;
7486 	}
7487 
7488 	/* The rest of the code is for signatures that either already have been externally
7489 	 * attached (likely, but not necessarily by a previous run through the taskgated
7490 	 * path), or that will now be attached by taskgated. */
7491 
7492 	kr = task_get_task_access_port(proc_task(p), &port);
7493 	if (KERN_SUCCESS != kr || !IPC_PORT_VALID(port)) {
7494 		error = 0;
7495 		if (require_success) {
7496 			KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
7497 			    proc_getpid(p), OS_REASON_CODESIGNING, CODESIGNING_EXIT_REASON_TASK_ACCESS_PORT, 0, 0);
7498 			signature_failure_reason = os_reason_create(OS_REASON_CODESIGNING, CODESIGNING_EXIT_REASON_TASK_ACCESS_PORT);
7499 			error = EACCES;
7500 		}
7501 		goto done;
7502 	}
7503 
7504 	/*
7505 	 * taskgated returns KERN_SUCCESS if it has completed its work
7506 	 * and the exec should continue, KERN_FAILURE if the exec should
7507 	 * fail, or it may error out with different error code in an
7508 	 * event of mig failure (e.g. process was signalled during the
7509 	 * rpc call, taskgated died, mig server died etc.).
7510 	 */
7511 
7512 	kr = __EXEC_WAITING_ON_TASKGATED_CODE_SIGNATURE_UPCALL__(port, proc_getpid(p));
7513 	switch (kr) {
7514 	case KERN_SUCCESS:
7515 		error = 0;
7516 		break;
7517 	case KERN_FAILURE:
7518 		error = EACCES;
7519 
7520 		KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
7521 		    proc_getpid(p), OS_REASON_CODESIGNING, CODESIGNING_EXIT_REASON_TASKGATED_INVALID_SIG, 0, 0);
7522 		signature_failure_reason = os_reason_create(OS_REASON_CODESIGNING, CODESIGNING_EXIT_REASON_TASKGATED_INVALID_SIG);
7523 		goto done;
7524 	default:
7525 		error = EACCES;
7526 
7527 		KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
7528 		    proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_TASKGATED_OTHER, 0, 0);
7529 		signature_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_TASKGATED_OTHER);
7530 		unexpected_failure = TRUE;
7531 		goto done;
7532 	}
7533 
7534 	/* Only do this if exec_resettextvp() did not fail */
7535 	if (p->p_textvp != NULLVP) {
7536 		csb = ubc_cs_blob_get(p->p_textvp, -1, -1, p->p_textoff);
7537 
7538 		if (csb != NULL) {
7539 			/* As the enforcement we can do here is very limited, we only allow things that
7540 			 * are the only reason why this code path still exists:
7541 			 * Adhoc signed non-platform binaries without special cs_flags and without any
7542 			 * entitlements (unrestricted ones still pass AMFI). */
7543 			if (
7544 				/* Revalidate the blob if necessary through bumped generation count. */
7545 				(ubc_cs_generation_check(p->p_textvp) == 0 ||
7546 				ubc_cs_blob_revalidate(p->p_textvp, csb, imgp, 0, proc_platform(p)) == 0) &&
7547 				/* Only CS_ADHOC, no CS_KILL, CS_HARD etc. */
7548 				(csb->csb_flags & CS_ALLOWED_MACHO) == CS_ADHOC &&
7549 				/* If it has a CMS blob, it's not adhoc. The CS_ADHOC flag can lie. */
7550 				csblob_find_blob_bytes((const uint8_t *)csb->csb_mem_kaddr, csb->csb_mem_size,
7551 				CSSLOT_SIGNATURESLOT,
7552 				CSMAGIC_BLOBWRAPPER) == NULL &&
7553 				/* It could still be in a trust cache (unlikely with CS_ADHOC), or a magic path. */
7554 				csb->csb_platform_binary == 0 &&
7555 				/* No entitlements, not even unrestricted ones. */
7556 				csb->csb_entitlements_blob == NULL &&
7557 				csb->csb_der_entitlements_blob == NULL) {
7558 				proc_lock(p);
7559 				proc_csflags_set(p, CS_SIGNED | CS_VALID);
7560 				proc_unlock(p);
7561 			} else {
7562 				uint8_t cdhash[CS_CDHASH_LEN];
7563 				char cdhash_string[CS_CDHASH_STRING_SIZE];
7564 				proc_getcdhash(p, cdhash);
7565 				cdhash_to_string(cdhash_string, cdhash);
7566 				printf("ignoring detached code signature on '%s' with cdhash '%s' "
7567 				    "because it is invalid, or not a simple adhoc signature.\n",
7568 				    p->p_name, cdhash_string);
7569 			}
7570 		}
7571 	}
7572 
7573 done:
7574 	if (0 == error) {
7575 		/*
7576 		 * Update the new process's signature-dependent process state.
7577 		 * state.
7578 		 */
7579 
7580 		error = proc_process_signature(p, &signature_failure_reason);
7581 	}
7582 
7583 	if (0 == error) {
7584 		/*
7585 		 * Update the new main thread's signature-dependent thread
7586 		 * state. This was also called when the thread was created,
7587 		 * but for the main thread the signature was not yet attached
7588 		 * at that time.
7589 		 */
7590 		kr = thread_process_signature(imgp->ip_new_thread, proc_get_task_raw(p));
7591 
7592 		if (kr != KERN_SUCCESS) {
7593 			error = EINVAL;
7594 			signature_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_MACHINE_THREAD);
7595 		}
7596 	}
7597 
7598 	if (0 == error) {
7599 		/* The process's code signature related properties are
7600 		 * fully set up, so this is an opportune moment to log
7601 		 * platform binary execution, if desired. */
7602 		if (platform_exec_logging != 0 && csproc_get_platform_binary(p)) {
7603 			uint8_t cdhash[CS_CDHASH_LEN];
7604 			char cdhash_string[CS_CDHASH_STRING_SIZE];
7605 			proc_getcdhash(p, cdhash);
7606 			cdhash_to_string(cdhash_string, cdhash);
7607 
7608 			os_log(peLog, "CS Platform Exec Logging: Executing platform signed binary "
7609 			    "'%s' with cdhash %s\n", p->p_name, cdhash_string);
7610 		}
7611 	} else {
7612 		if (!unexpected_failure) {
7613 			proc_csflags_set(p, CS_KILLED);
7614 		}
7615 		/* make very sure execution fails */
7616 		if (vfexec || spawn) {
7617 			assert(signature_failure_reason != OS_REASON_NULL);
7618 			psignal_vfork_with_reason(p, proc_task(p), imgp->ip_new_thread,
7619 			    SIGKILL, signature_failure_reason);
7620 			signature_failure_reason = OS_REASON_NULL;
7621 			error = 0;
7622 		} else {
7623 			assert(signature_failure_reason != OS_REASON_NULL);
7624 			psignal_with_reason(p, SIGKILL, signature_failure_reason);
7625 			signature_failure_reason = OS_REASON_NULL;
7626 		}
7627 	}
7628 
7629 	if (port != IPC_PORT_NULL) {
7630 		ipc_port_release_send(port);
7631 	}
7632 
7633 	/* If we hit this, we likely would have leaked an exit reason */
7634 	assert(signature_failure_reason == OS_REASON_NULL);
7635 	return error;
7636 }
7637 
7638 /*
7639  * Typically as soon as we start executing this process, the
7640  * first instruction will trigger a VM fault to bring the text
7641  * pages (as executable) into the address space, followed soon
7642  * thereafter by dyld data structures (for dynamic executable).
7643  * To optimize this, as well as improve support for hardware
7644  * debuggers that can only access resident pages present
7645  * in the process' page tables, we prefault some pages if
7646  * possible. Errors are non-fatal.
7647  */
7648 #ifndef PREVENT_CALLER_STACK_USE
7649 #define PREVENT_CALLER_STACK_USE __attribute__((noinline))
7650 #endif
7651 static void PREVENT_CALLER_STACK_USE
exec_prefault_data(proc_t p __unused,struct image_params * imgp,load_result_t * load_result)7652 exec_prefault_data(proc_t p __unused, struct image_params *imgp, load_result_t *load_result)
7653 {
7654 	int ret;
7655 	size_t expected_all_image_infos_size;
7656 	kern_return_t kr;
7657 
7658 	/*
7659 	 * Prefault executable or dyld entry point.
7660 	 */
7661 	if (vm_map_page_shift(current_map()) < (int)PAGE_SHIFT) {
7662 		DEBUG4K_LOAD("entry_point 0x%llx\n", (uint64_t)load_result->entry_point);
7663 	}
7664 	kr = vm_fault(current_map(),
7665 	    vm_map_trunc_page(load_result->entry_point,
7666 	    vm_map_page_mask(current_map())),
7667 	    VM_PROT_READ | VM_PROT_EXECUTE,
7668 	    FALSE, VM_KERN_MEMORY_NONE,
7669 	    THREAD_UNINT, NULL, 0);
7670 	if (kr != KERN_SUCCESS) {
7671 		DEBUG4K_ERROR("map %p va 0x%llx -> 0x%x\n", current_map(), (uint64_t)vm_map_trunc_page(load_result->entry_point, vm_map_page_mask(current_map())), kr);
7672 	}
7673 
7674 	if (imgp->ip_flags & IMGPF_IS_64BIT_ADDR) {
7675 		expected_all_image_infos_size = sizeof(struct user64_dyld_all_image_infos);
7676 	} else {
7677 		expected_all_image_infos_size = sizeof(struct user32_dyld_all_image_infos);
7678 	}
7679 
7680 	/* Decode dyld anchor structure from <mach-o/dyld_images.h> */
7681 	if (load_result->dynlinker &&
7682 	    load_result->all_image_info_addr &&
7683 	    load_result->all_image_info_size >= expected_all_image_infos_size) {
7684 		union {
7685 			struct user64_dyld_all_image_infos      infos64;
7686 			struct user32_dyld_all_image_infos      infos32;
7687 		} all_image_infos;
7688 
7689 		/*
7690 		 * Pre-fault to avoid copyin() going through the trap handler
7691 		 * and recovery path.
7692 		 */
7693 		if (vm_map_page_shift(current_map()) < (int)PAGE_SHIFT) {
7694 			DEBUG4K_LOAD("all_image_info_addr 0x%llx\n", load_result->all_image_info_addr);
7695 		}
7696 		kr = vm_fault(current_map(),
7697 		    vm_map_trunc_page(load_result->all_image_info_addr,
7698 		    vm_map_page_mask(current_map())),
7699 		    VM_PROT_READ | VM_PROT_WRITE,
7700 		    FALSE, VM_KERN_MEMORY_NONE,
7701 		    THREAD_UNINT, NULL, 0);
7702 		if (kr != KERN_SUCCESS) {
7703 //			printf("%s:%d map %p va 0x%llx -> 0x%x\n", __FUNCTION__, __LINE__, current_map(), vm_map_trunc_page(load_result->all_image_info_addr, vm_map_page_mask(current_map())), kr);
7704 		}
7705 		if ((load_result->all_image_info_addr & PAGE_MASK) + expected_all_image_infos_size > PAGE_SIZE) {
7706 			/* all_image_infos straddles a page */
7707 			kr = vm_fault(current_map(),
7708 			    vm_map_trunc_page(load_result->all_image_info_addr + expected_all_image_infos_size - 1,
7709 			    vm_map_page_mask(current_map())),
7710 			    VM_PROT_READ | VM_PROT_WRITE,
7711 			    FALSE, VM_KERN_MEMORY_NONE,
7712 			    THREAD_UNINT, NULL, 0);
7713 			if (kr != KERN_SUCCESS) {
7714 //				printf("%s:%d map %p va 0x%llx -> 0x%x\n", __FUNCTION__, __LINE__, current_map(), vm_map_trunc_page(load_result->all_image_info_addr + expected_all_image_infos_size -1, vm_map_page_mask(current_map())), kr);
7715 			}
7716 		}
7717 
7718 		if (vm_map_page_shift(current_map()) < (int)PAGE_SHIFT) {
7719 			DEBUG4K_LOAD("copyin(0x%llx, 0x%lx)\n", load_result->all_image_info_addr, expected_all_image_infos_size);
7720 		}
7721 		ret = copyin((user_addr_t)load_result->all_image_info_addr,
7722 		    &all_image_infos,
7723 		    expected_all_image_infos_size);
7724 		if (ret == 0 && all_image_infos.infos32.version >= DYLD_ALL_IMAGE_INFOS_ADDRESS_MINIMUM_VERSION) {
7725 			user_addr_t notification_address;
7726 			user_addr_t dyld_image_address;
7727 			user_addr_t dyld_version_address;
7728 			user_addr_t dyld_all_image_infos_address;
7729 			user_addr_t dyld_slide_amount;
7730 
7731 			if (imgp->ip_flags & IMGPF_IS_64BIT_ADDR) {
7732 				notification_address = (user_addr_t)all_image_infos.infos64.notification;
7733 				dyld_image_address = (user_addr_t)all_image_infos.infos64.dyldImageLoadAddress;
7734 				dyld_version_address = (user_addr_t)all_image_infos.infos64.dyldVersion;
7735 				dyld_all_image_infos_address = (user_addr_t)all_image_infos.infos64.dyldAllImageInfosAddress;
7736 			} else {
7737 				notification_address = all_image_infos.infos32.notification;
7738 				dyld_image_address = all_image_infos.infos32.dyldImageLoadAddress;
7739 				dyld_version_address = all_image_infos.infos32.dyldVersion;
7740 				dyld_all_image_infos_address = all_image_infos.infos32.dyldAllImageInfosAddress;
7741 			}
7742 
7743 			/*
7744 			 * dyld statically sets up the all_image_infos in its Mach-O
7745 			 * binary at static link time, with pointers relative to its default
7746 			 * load address. Since ASLR might slide dyld before its first
7747 			 * instruction is executed, "dyld_slide_amount" tells us how far
7748 			 * dyld was loaded compared to its default expected load address.
7749 			 * All other pointers into dyld's image should be adjusted by this
7750 			 * amount. At some point later, dyld will fix up pointers to take
7751 			 * into account the slide, at which point the all_image_infos_address
7752 			 * field in the structure will match the runtime load address, and
7753 			 * "dyld_slide_amount" will be 0, if we were to consult it again.
7754 			 */
7755 
7756 			dyld_slide_amount = (user_addr_t)load_result->all_image_info_addr - dyld_all_image_infos_address;
7757 
7758 #if 0
7759 			kprintf("exec_prefault: 0x%016llx 0x%08x 0x%016llx 0x%016llx 0x%016llx 0x%016llx\n",
7760 			    (uint64_t)load_result->all_image_info_addr,
7761 			    all_image_infos.infos32.version,
7762 			    (uint64_t)notification_address,
7763 			    (uint64_t)dyld_image_address,
7764 			    (uint64_t)dyld_version_address,
7765 			    (uint64_t)dyld_all_image_infos_address);
7766 #endif
7767 
7768 			if (vm_map_page_shift(current_map()) < (int)PAGE_SHIFT) {
7769 				DEBUG4K_LOAD("notification_address 0x%llx dyld_slide_amount 0x%llx\n", (uint64_t)notification_address, (uint64_t)dyld_slide_amount);
7770 			}
7771 			kr = vm_fault(current_map(),
7772 			    vm_map_trunc_page(notification_address + dyld_slide_amount,
7773 			    vm_map_page_mask(current_map())),
7774 			    VM_PROT_READ | VM_PROT_EXECUTE,
7775 			    FALSE, VM_KERN_MEMORY_NONE,
7776 			    THREAD_UNINT, NULL, 0);
7777 			if (kr != KERN_SUCCESS) {
7778 //				printf("%s:%d map %p va 0x%llx -> 0x%x\n", __FUNCTION__, __LINE__, current_map(), vm_map_trunc_page(notification_address + dyld_slide_amount, vm_map_page_mask(current_map())), kr);
7779 			}
7780 			if (vm_map_page_shift(current_map()) < (int)PAGE_SHIFT) {
7781 				DEBUG4K_LOAD("dyld_image_address 0x%llx dyld_slide_amount 0x%llx\n", (uint64_t)dyld_image_address, (uint64_t)dyld_slide_amount);
7782 			}
7783 			kr = vm_fault(current_map(),
7784 			    vm_map_trunc_page(dyld_image_address + dyld_slide_amount,
7785 			    vm_map_page_mask(current_map())),
7786 			    VM_PROT_READ | VM_PROT_EXECUTE,
7787 			    FALSE, VM_KERN_MEMORY_NONE,
7788 			    THREAD_UNINT, NULL, 0);
7789 			if (kr != KERN_SUCCESS) {
7790 //				printf("%s:%d map %p va 0x%llx -> 0x%x\n", __FUNCTION__, __LINE__, current_map(), vm_map_trunc_page(dyld_image_address + dyld_slide_amount, vm_map_page_mask(current_map())), kr);
7791 			}
7792 			if (vm_map_page_shift(current_map()) < (int)PAGE_SHIFT) {
7793 				DEBUG4K_LOAD("dyld_version_address 0x%llx dyld_slide_amount 0x%llx\n", (uint64_t)dyld_version_address, (uint64_t)dyld_slide_amount);
7794 			}
7795 			kr = vm_fault(current_map(),
7796 			    vm_map_trunc_page(dyld_version_address + dyld_slide_amount,
7797 			    vm_map_page_mask(current_map())),
7798 			    VM_PROT_READ,
7799 			    FALSE, VM_KERN_MEMORY_NONE,
7800 			    THREAD_UNINT, NULL, 0);
7801 			if (kr != KERN_SUCCESS) {
7802 //				printf("%s:%d map %p va 0x%llx -> 0x%x\n", __FUNCTION__, __LINE__, current_map(), vm_map_trunc_page(dyld_version_address + dyld_slide_amount, vm_map_page_mask(current_map())), kr);
7803 			}
7804 			if (vm_map_page_shift(current_map()) < (int)PAGE_SHIFT) {
7805 				DEBUG4K_LOAD("dyld_all_image_infos_address 0x%llx dyld_slide_amount 0x%llx\n", (uint64_t)dyld_version_address, (uint64_t)dyld_slide_amount);
7806 			}
7807 			kr = vm_fault(current_map(),
7808 			    vm_map_trunc_page(dyld_all_image_infos_address + dyld_slide_amount,
7809 			    vm_map_page_mask(current_map())),
7810 			    VM_PROT_READ | VM_PROT_WRITE,
7811 			    FALSE, VM_KERN_MEMORY_NONE,
7812 			    THREAD_UNINT, NULL, 0);
7813 			if (kr != KERN_SUCCESS) {
7814 //				printf("%s:%d map %p va 0x%llx -> 0x%x\n", __FUNCTION__, __LINE__, current_map(), vm_map_trunc_page(dyld_all_image_infos_address + dyld_slide_amount, vm_map_page_mask(current_map())), kr);
7815 			}
7816 		}
7817 	}
7818 }
7819 
7820 static int
7821 sysctl_libmalloc_experiments SYSCTL_HANDLER_ARGS
7822 {
7823 #pragma unused(oidp, arg2, req)
7824 	int changed;
7825 	errno_t error;
7826 	uint64_t value = os_atomic_load_wide(&libmalloc_experiment_factors, relaxed);
7827 
7828 	error = sysctl_io_number(req, value, sizeof(value), &value, &changed);
7829 	if (error) {
7830 		return error;
7831 	}
7832 
7833 	if (changed) {
7834 		os_atomic_store_wide(&libmalloc_experiment_factors, value, relaxed);
7835 	}
7836 
7837 	return 0;
7838 }
7839 
7840 EXPERIMENT_FACTOR_PROC(_kern, libmalloc_experiments, CTLTYPE_QUAD | CTLFLAG_RW, 0, 0, &sysctl_libmalloc_experiments, "A", "");
7841