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