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